actual-mcp-server 0.16.2 → 0.16.6
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.
- package/README.md +1 -1
- package/dist/src/actualConnection.js +36 -13
- package/dist/src/lib/ActualConnectionPool.js +147 -43
- package/dist/src/lib/actual-adapter.js +204 -42
- package/dist/src/lib/apiLock.js +60 -0
- package/dist/src/lib/apiState.js +107 -0
- package/dist/src/lib/budgetLoader.js +399 -0
- package/package.json +2 -2
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import api from '@actual-app/api';
|
|
2
|
+
import { withOpTimeout } from './opTimeout.js';
|
|
3
|
+
import { setApiInitialized, setLoadedBudgetSyncId, registerBudgetLoad } from './apiState.js';
|
|
4
|
+
import { createModuleLogger } from './loggerFactory.js';
|
|
5
|
+
const log = createModuleLogger('BUDGET-LOADER');
|
|
6
|
+
/**
|
|
7
|
+
* #390 round 3: the ONE way this codebase loads a budget.
|
|
8
|
+
*
|
|
9
|
+
* Every site used to hand-write `withOpTimeout(() => api.downloadBudget(...))` followed by a
|
|
10
|
+
* record-on-success. That shape is wrong in a way no amount of care fixes, because
|
|
11
|
+
* `withOpTimeout` races rather than cancels: on timeout the download keeps running and later
|
|
12
|
+
* re-points the singleton outside the mutex, and recording only on success leaves the record
|
|
13
|
+
* naming the PREVIOUS budget while the singleton holds the new one, which is the one direction
|
|
14
|
+
* that makes the precondition silently pass.
|
|
15
|
+
*
|
|
16
|
+
* So: clear the record BEFORE starting (an abandonment can then only leave it indeterminate,
|
|
17
|
+
* which forces a re-select), register the promise so a late landing is waited for rather than
|
|
18
|
+
* discovered, and record the true outcome when it settles whether or not anyone is still
|
|
19
|
+
* listening.
|
|
20
|
+
*
|
|
21
|
+
* #396 adds a POST-CONDITION, because a resolved download is not proof a budget is open.
|
|
22
|
+
* See `assertBudgetOpen` below.
|
|
23
|
+
*
|
|
24
|
+
* INVARIANT: nothing in this file may call anything that takes `withApiLock`. Every caller
|
|
25
|
+
* already holds that non-reentrant mutex, so `adapter.*` here would deadlock. It is also what
|
|
26
|
+
* makes this loader safe to call from `actualConnection.ts`, which acquires the lock itself.
|
|
27
|
+
* (#402 tracks making this structural rather than conventional.)
|
|
28
|
+
*/
|
|
29
|
+
/** The closed set of reasons upstream's `_loadBudget` can report, via `withErrorCode`. */
|
|
30
|
+
const KNOWN_LOAD_REASONS = new Set([
|
|
31
|
+
'budget-not-found',
|
|
32
|
+
'opening-budget',
|
|
33
|
+
'out-of-sync-migrations',
|
|
34
|
+
'out-of-sync-data',
|
|
35
|
+
'loading-budget',
|
|
36
|
+
]);
|
|
37
|
+
/** Upper bound on any upstream prose we echo to the client (#396 security review). */
|
|
38
|
+
const MAX_REASON_CHARS = 200;
|
|
39
|
+
/** Sentinel: the diagnostic load worked, so the failure was not deterministic. */
|
|
40
|
+
const RETRY_SUCCEEDED = 'the load succeeded on a second attempt, so this looks transient; retry the operation';
|
|
41
|
+
/** Reported when the syncId has no LOCAL copy. Deliberately says nothing about what does exist. */
|
|
42
|
+
const NO_LOCAL_COPY = 'no local copy of this budget was found';
|
|
43
|
+
/**
|
|
44
|
+
* Brand for "the download resolved but no budget is open", so the caller can tell it from an
|
|
45
|
+
* upstream stall without matching prose. Deliberately NOT a PreflightRefusal: this is an
|
|
46
|
+
* infrastructure failure, not a caller-fixable refusal (`errors.ts` taxonomy).
|
|
47
|
+
*/
|
|
48
|
+
const BUDGET_NOT_OPEN = Symbol.for('actual-mcp.budgetNotOpen');
|
|
49
|
+
function isBudgetNotOpen(err) {
|
|
50
|
+
return !!err && typeof err === 'object' && err[BUDGET_NOT_OPEN] === true;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Read `.message` off anything upstream throws.
|
|
54
|
+
*
|
|
55
|
+
* NO `instanceof Error` GUARD, deliberately. `checkFileOpen()` throws `APIError(...)`, which
|
|
56
|
+
* RETURNS A PLAIN OBJECT (`{ type: 'APIError', message, meta }`). Measured against
|
|
57
|
+
* @actual-app/api 26.8.0: `err instanceof Error` is false and `String(err)` is `[object Object]`,
|
|
58
|
+
* while `.message` works. Same precedent as `actual-adapter.ts` ("Handle Actual APIError plain
|
|
59
|
+
* objects").
|
|
60
|
+
*/
|
|
61
|
+
function messageOf(err) {
|
|
62
|
+
if (err && typeof err === 'object' && typeof err.message === 'string') {
|
|
63
|
+
return err.message;
|
|
64
|
+
}
|
|
65
|
+
return typeof err === 'string' ? err : '';
|
|
66
|
+
}
|
|
67
|
+
function codeOf(err) {
|
|
68
|
+
if (err && typeof err === 'object' && typeof err.code === 'string') {
|
|
69
|
+
return err.code;
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
/** A timeout from `withOpTimeout` is an upstream STALL, never an unloadable budget. */
|
|
74
|
+
function isOpTimeout(err) {
|
|
75
|
+
return /timed out after \d+ms \(ACTUAL_OP_TIMEOUT_MS\)/.test(messageOf(err));
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* #396 POST-CONDITION: is a budget actually open?
|
|
79
|
+
*
|
|
80
|
+
* `api.downloadBudget()` can RESOLVE while leaving nothing open. Upstream's
|
|
81
|
+
* `api/download-budget` discards the `{ error }` that `load-budget` returns, in BOTH branches
|
|
82
|
+
* (loot-core `src/server/api.ts:237` for a local copy, `:261` after a fresh download), and
|
|
83
|
+
* `load-budget` does not throw: it returns an error object having already called `closeBudget()`
|
|
84
|
+
* internally, which unloads prefs. The sync that follows cannot catch it either, because
|
|
85
|
+
* `_fullSync` opens with `if (... || !currentId) return []`, so with nothing loaded it reports
|
|
86
|
+
* success by returning nothing. Reproduced two ways against a real budget (a planted unknown
|
|
87
|
+
* migration id, and a `db.sqlite` that is not a database): the download resolves, nothing is
|
|
88
|
+
* open, and every later call throws `No budget file is open` permanently for that data dir.
|
|
89
|
+
*
|
|
90
|
+
* The probe is `api.getBudgetMonths()`, and it is cheap for a reason worth stating rather than
|
|
91
|
+
* assuming: it is `checkFileOpen()` plus `createAllBudgets()`, and `createAllBudgets()` already
|
|
92
|
+
* ran once inside `_loadBudget` against the SAME in-process `Spreadsheet` singleton, while
|
|
93
|
+
* `meta.createdMonths` is never persisted, so the second call filters to zero new months and does
|
|
94
|
+
* no work beyond one indexed SQLite read. Measured at 0ms with no network call.
|
|
95
|
+
*/
|
|
96
|
+
async function assertBudgetOpen() {
|
|
97
|
+
try {
|
|
98
|
+
await withOpTimeout(() => api.getBudgetMonths(), 'budget-open probe');
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
// An upstream STALL is not an unloadable budget. Propagate it unchanged so it keeps #270's
|
|
102
|
+
// semantics: diagnosing it as a version or data-dir problem would point the user at the wrong
|
|
103
|
+
// subsystem, and its message contains "timed out", which `_shouldDropPoolOnError` classes
|
|
104
|
+
// transient (correctly, for a stall).
|
|
105
|
+
if (isOpTimeout(err))
|
|
106
|
+
throw err;
|
|
107
|
+
// #396 review: classify as "not open" ONLY on the signal that actually means it. Treating
|
|
108
|
+
// EVERY probe rejection as not-open was wrong in the expensive direction: a transient
|
|
109
|
+
// getBudgetMonths failure against a perfectly healthy OPEN budget would poison the singleton,
|
|
110
|
+
// send `diagnose` off to CLOSE and reload that healthy budget, and hand the caller a
|
|
111
|
+
// permanent-sounding "no budget file is open". Anything else is a genuine failure and
|
|
112
|
+
// propagates unchanged; the enclosing `.catch` still fails closed either way.
|
|
113
|
+
if (!/no budget file is open/i.test(messageOf(err)))
|
|
114
|
+
throw err;
|
|
115
|
+
const notOpen = new Error('the budget did not load');
|
|
116
|
+
notOpen[BUDGET_NOT_OPEN] = true;
|
|
117
|
+
throw notOpen;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Strip anything path-shaped from upstream prose before it reaches an MCP client.
|
|
122
|
+
*
|
|
123
|
+
* There is NO redaction backstop on this path: `actualToolsManager.callTool` rethrows and
|
|
124
|
+
* `ActualMCPConnection.executeTool` propagates, so the message reaches the client verbatim, and
|
|
125
|
+
* `redactSecrets` is a winston format that covers log transports only. The five `getSyncError`
|
|
126
|
+
* strings interpolate just the budget UUID and are safe, but `_loadBudget` maps to that enum only
|
|
127
|
+
* for failures it CATCHES: `db.loadClock()`, `prefs.savePrefs` and `startBackupService(id)` sit
|
|
128
|
+
* outside every try/catch, so a raw fs or sqlite error carrying an ABSOLUTE PATH (and therefore a
|
|
129
|
+
* username) can reach here. Capping does not scrub a path, so scrub first.
|
|
130
|
+
*/
|
|
131
|
+
function scrubReason(prose) {
|
|
132
|
+
if (!prose)
|
|
133
|
+
return undefined;
|
|
134
|
+
// #396 review: reject on ANY separator, not just one at a word boundary. The first version
|
|
135
|
+
// required `/` at the string start or after whitespace, a quote or a paren, so
|
|
136
|
+
// `ENOENT:/home/alice/...` and `C:/Users/alice/...` both slipped through WITH the OS username,
|
|
137
|
+
// on a path that has no redaction backstop. The five known-safe upstream reasons are plain
|
|
138
|
+
// prose plus a UUID and contain none of these characters, so rejecting outright costs nothing
|
|
139
|
+
// and cannot leak.
|
|
140
|
+
if (/[/\\~]/.test(prose))
|
|
141
|
+
return undefined;
|
|
142
|
+
return prose.length > MAX_REASON_CHARS ? `${prose.slice(0, MAX_REASON_CHARS)}...` : prose;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Ask upstream WHY the load failed, on the deterministic failure path only.
|
|
146
|
+
*
|
|
147
|
+
* Upstream logs the real reason and throws it away, which is the whole reason a user hitting this
|
|
148
|
+
* has nothing actionable to go on. `api/load-budget` (unlike `api/download-budget`) DOES check the
|
|
149
|
+
* error and throws it with `withErrorCode`, so re-attempting the load through that entry point
|
|
150
|
+
* recovers the exact reason.
|
|
151
|
+
*
|
|
152
|
+
* Runs where a CALLER IS WAITING, never inside the promise `registerBudgetLoad` registers: every
|
|
153
|
+
* `withApiLock` acquisition settles all registrations under ONE bound and fails closed on timeout,
|
|
154
|
+
* so putting two network calls in there would extend the window in which unrelated sessions' lock
|
|
155
|
+
* acquisitions throw, to build a message an abandoned load has no caller to read.
|
|
156
|
+
*/
|
|
157
|
+
/**
|
|
158
|
+
* #404: the cached reason is re-derived every REDIAGNOSE_AFTER_USES failures.
|
|
159
|
+
*
|
|
160
|
+
* The cache exists because `diagnose()` runs INSIDE the process-global api mutex and makes two
|
|
161
|
+
* bounded network calls, so re-running it per failed tool call stalls unrelated sessions. But an
|
|
162
|
+
* entry was previously dropped only by a genuinely successful load or a process restart, so if a
|
|
163
|
+
* budget's failure MODE changed with no success in between, the message reported the first reason
|
|
164
|
+
* indefinitely.
|
|
165
|
+
*
|
|
166
|
+
* Bounding by USES rather than by wall-clock is deliberate: the cost this cache avoids is paid per
|
|
167
|
+
* CALL, so capping in calls bounds staleness in the same unit, needs no clock, and is
|
|
168
|
+
* deterministic under test. At 20, a persistent failure pays the diagnosis roughly 5 percent of
|
|
169
|
+
* the time (the saving the cache exists for is kept) while no operator can see a stale reason for
|
|
170
|
+
* more than 20 failed calls. The fail-closed DECISION is still never cached: every call
|
|
171
|
+
* re-attempts the load and still fails.
|
|
172
|
+
*/
|
|
173
|
+
const REDIAGNOSE_AFTER_USES = 20;
|
|
174
|
+
const reasonCache = new Map();
|
|
175
|
+
/** A load that genuinely succeeded clears any cached reason for that budget. */
|
|
176
|
+
function clearCachedReason(syncId) {
|
|
177
|
+
reasonCache.delete(syncId);
|
|
178
|
+
}
|
|
179
|
+
/** Test-only: the reason cache is module state, so a test suite must be able to reset it. */
|
|
180
|
+
export function _clearReasonCacheForTests() {
|
|
181
|
+
reasonCache.clear();
|
|
182
|
+
}
|
|
183
|
+
async function diagnose(syncId) {
|
|
184
|
+
// #396 review: memoise the reason STRING, never the fail-closed decision. Without this, every
|
|
185
|
+
// tool call while the condition persists pays two bounded network calls WHILE HOLDING the
|
|
186
|
+
// process-global api mutex, so a single unloadable budget stalls unrelated sessions for up to
|
|
187
|
+
// 2 x ACTUAL_OP_TIMEOUT_MS per call. The condition is deterministic, so the second diagnosis
|
|
188
|
+
// would report what the first did. The ticket sanctions exactly this and nothing more: the
|
|
189
|
+
// decision stays uncached, so the load is still re-attempted and still fails closed every time,
|
|
190
|
+
// and a genuinely successful load clears the entry.
|
|
191
|
+
// An empty string means "already diagnosed, and there was nothing safe to report". It must be
|
|
192
|
+
// cached like any other outcome: review round 2 found that caching only the reportable outcomes
|
|
193
|
+
// left the two most persistent failure classes re-diagnosing on every single call, which is
|
|
194
|
+
// precisely the cost this memo exists to remove.
|
|
195
|
+
const cached = reasonCache.get(syncId);
|
|
196
|
+
if (cached !== undefined) {
|
|
197
|
+
cached.uses += 1;
|
|
198
|
+
if (cached.uses <= REDIAGNOSE_AFTER_USES) {
|
|
199
|
+
log.debug('reusing the cached load-failure reason', { syncId, uses: cached.uses });
|
|
200
|
+
return cached.reason || undefined;
|
|
201
|
+
}
|
|
202
|
+
// #404: the entry has served its budget of calls. Drop it and fall through to a fresh
|
|
203
|
+
// diagnosis, so a failure mode that changed without an intervening success is picked up.
|
|
204
|
+
reasonCache.delete(syncId);
|
|
205
|
+
log.debug('re-diagnosing the load failure after the cached reason served its budget', {
|
|
206
|
+
syncId,
|
|
207
|
+
afterUses: REDIAGNOSE_AFTER_USES,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
const budgets = (await withOpTimeout(() => api.getBudgets(), 'diagnose getBudgets'));
|
|
212
|
+
// `api/get-budgets` does NO deduplication: it concatenates the local scan with
|
|
213
|
+
// `get-remote-files`, so a budget synced both ways appears TWICE and only the LOCAL entry
|
|
214
|
+
// carries `id`. Measured: [{"id":"_test-budget"},{"state":"remote"}] for one groupId.
|
|
215
|
+
// Matching on groupId alone can select the remote twin and call loadBudget(undefined).
|
|
216
|
+
const local = budgets.find((b) => b.groupId === syncId && typeof b.id === 'string');
|
|
217
|
+
if (!local) {
|
|
218
|
+
// Deliberately does NOT list what IS available: that would enumerate every budget on the
|
|
219
|
+
// server to a caller the ACL scopes to one.
|
|
220
|
+
reasonCache.set(syncId, { reason: NO_LOCAL_COPY, uses: 0 });
|
|
221
|
+
return NO_LOCAL_COPY;
|
|
222
|
+
}
|
|
223
|
+
const localId = local.id;
|
|
224
|
+
// Registered like any other load: it re-enters upstream's full `_loadBudget` against the
|
|
225
|
+
// process-global singleton, so an abandoned diagnostic could otherwise land later and
|
|
226
|
+
// re-point it outside the lock (the #390 leak with a new author).
|
|
227
|
+
const p = api.loadBudget(localId);
|
|
228
|
+
registerBudgetLoad(p);
|
|
229
|
+
try {
|
|
230
|
+
await withOpTimeout(() => p, 'diagnose loadBudget');
|
|
231
|
+
// The diagnostic load SUCCEEDED, so the singleton now holds a budget nothing selected.
|
|
232
|
+
// Record indeterminate: that forces a re-select on the next operation, which is the safe
|
|
233
|
+
// direction #390 established. This line also satisfies block (4) of
|
|
234
|
+
// budget_selection_precondition.test.js structurally rather than by exemption, and it must
|
|
235
|
+
// stay in THIS brace-balanced block: the guard's window ends at the first `}` that takes
|
|
236
|
+
// depth below zero, so a setter in a sibling `catch` or `finally` arm would be outside it.
|
|
237
|
+
setLoadedBudgetSyncId(null);
|
|
238
|
+
// #396 review: the retry SUCCEEDED, so this was not a deterministic unloadable budget. Say
|
|
239
|
+
// so rather than reporting "upstream discarded the reason", which reads as permanent. The
|
|
240
|
+
// operation still fails (the record is indeterminate by design, which forces a re-select),
|
|
241
|
+
// but the caller is told that retrying is the right move. Not cached: it is not a reason,
|
|
242
|
+
// and the condition it describes is transient.
|
|
243
|
+
return RETRY_SUCCEEDED;
|
|
244
|
+
}
|
|
245
|
+
catch (loadErr) {
|
|
246
|
+
setLoadedBudgetSyncId(null);
|
|
247
|
+
// Prefer the CODE. Upstream attaches it via `withErrorCode` precisely so callers need not
|
|
248
|
+
// parse prose, and the prose is lossy: `getSyncError` collapses out-of-sync-migrations with
|
|
249
|
+
// out-of-sync-data, and opening-budget with loading-budget, so message-only capture
|
|
250
|
+
// distinguishes at most three of the five reasons.
|
|
251
|
+
const code = codeOf(loadErr);
|
|
252
|
+
log.warn('budget load diagnosis', { syncId, code: code ?? null, reason: messageOf(loadErr) });
|
|
253
|
+
const reason = code && KNOWN_LOAD_REASONS.has(code) ? code : scrubReason(messageOf(loadErr));
|
|
254
|
+
// Cache the outcome even when there is nothing reportable. A raw fs or sqlite failure has a
|
|
255
|
+
// `.code` outside KNOWN_LOAD_REASONS and path-shaped prose that `scrubReason` drops, so it
|
|
256
|
+
// yields `undefined`, and that is the ticket's own reproduced "db.sqlite is not a database"
|
|
257
|
+
// case: the one most likely to persist. Storing '' records "diagnosed" without reporting.
|
|
258
|
+
reasonCache.set(syncId, { reason: reason ?? '', uses: 0 });
|
|
259
|
+
return reason;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
catch (diagErr) {
|
|
263
|
+
// A failing diagnostic is LOGGED, never substituted for the post-condition error.
|
|
264
|
+
log.warn('could not diagnose why the budget did not load', { syncId, error: messageOf(diagErr) });
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function postConditionError(syncId, reason) {
|
|
269
|
+
return new Error(`The budget "${syncId}" reported a successful download but no budget file is open, ` +
|
|
270
|
+
`so every subsequent operation would fail. ` +
|
|
271
|
+
(reason ? `Upstream reason: [${reason}]. ` : 'Upstream discarded the reason. ') +
|
|
272
|
+
`Two causes account for almost all of these: a version mismatch between @actual-app/api and ` +
|
|
273
|
+
`the Actual server or budget file (the server version guard logs a warning when it can detect ` +
|
|
274
|
+
`this), and a local budget copy that cannot be opened (check the directory configured by ` +
|
|
275
|
+
`MCP_BRIDGE_DATA_DIR, and note that two server processes sharing one data dir will do this).`);
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* The tracking discipline EVERY singleton-mutating load must follow (#390, #393, #394).
|
|
279
|
+
*
|
|
280
|
+
* Extracted so the two callers cannot drift. `downloadBudget` and `importBudget` are different
|
|
281
|
+
* upstream calls with different failure shapes, but the discipline is identical and getting it
|
|
282
|
+
* subtly different at one site is exactly how #390 stayed reachable for three rounds:
|
|
283
|
+
*
|
|
284
|
+
* 1. Clear the record BEFORE starting, so an abandonment can only leave it INDETERMINATE.
|
|
285
|
+
* That is the safe direction: it forces a re-select. Recording only on success leaves the
|
|
286
|
+
* record naming the PREVIOUS budget while the singleton moves to a new one, which is the one
|
|
287
|
+
* direction that makes the #390 precondition silently pass.
|
|
288
|
+
* 2. Register the promise, so a late landing is WAITED FOR by the next lock acquisition rather
|
|
289
|
+
* than discovered mid-operation. `withOpTimeout` races; it does not cancel.
|
|
290
|
+
* 3. Record the true outcome when it settles, whether or not anyone is still listening, and
|
|
291
|
+
* poison the singleton on failure, because upstream closes the current budget before opening
|
|
292
|
+
* the new one, so "failed" does not mean "unchanged".
|
|
293
|
+
*
|
|
294
|
+
* `verify` is #396's post-condition, and it runs BEFORE the record is written, so the record can
|
|
295
|
+
* only ever describe a mutation that actually took effect.
|
|
296
|
+
*/
|
|
297
|
+
async function trackBudgetMutation(start, describeLoaded, label, verify, onRecorded) {
|
|
298
|
+
const raw = start();
|
|
299
|
+
// Indeterminate from here until it settles. Cleared first, deliberately.
|
|
300
|
+
setLoadedBudgetSyncId(null);
|
|
301
|
+
const tracked = raw
|
|
302
|
+
.then(async (result) => {
|
|
303
|
+
if (verify)
|
|
304
|
+
await verify();
|
|
305
|
+
setLoadedBudgetSyncId(describeLoaded(result));
|
|
306
|
+
// #392 review (finding 5): this runs INSIDE the chain, not after the awaited call. On the
|
|
307
|
+
// abandoned-then-eventually-successful path the caller has already thrown, so a hook placed
|
|
308
|
+
// after the await would never run and the cached failure reason would outlive the load that
|
|
309
|
+
// actually succeeded.
|
|
310
|
+
// Wrapped: a hook cannot be allowed to change the recorded outcome. Unwrapped, a throwing
|
|
311
|
+
// hook would be caught by the trailing .catch, reported as a load failure, and would leave
|
|
312
|
+
// the record written while setApiInitialized(false) says the singleton is dead: an
|
|
313
|
+
// incoherent pair rather than a fail-safe one.
|
|
314
|
+
try {
|
|
315
|
+
onRecorded?.();
|
|
316
|
+
}
|
|
317
|
+
catch (hookErr) {
|
|
318
|
+
log.warn('post-record hook threw; the recorded outcome stands', { error: String(hookErr) });
|
|
319
|
+
}
|
|
320
|
+
return result;
|
|
321
|
+
})
|
|
322
|
+
.catch((err) => {
|
|
323
|
+
// A failed load leaves the singleton in a state nobody can describe: upstream's
|
|
324
|
+
// download and import handlers both close the current budget before opening the new one,
|
|
325
|
+
// so "failed" does not mean "unchanged". Poison it so the next operation re-inits.
|
|
326
|
+
setApiInitialized(false);
|
|
327
|
+
throw err;
|
|
328
|
+
});
|
|
329
|
+
registerBudgetLoad(tracked);
|
|
330
|
+
// On timeout the tracked promise is still running. Leave it REGISTERED: the next operation
|
|
331
|
+
// waits for it inside the lock rather than racing it.
|
|
332
|
+
return await withOpTimeout(() => tracked, label);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* #394: the same discipline for an IMPORT.
|
|
336
|
+
*
|
|
337
|
+
* Upstream's `importBudget` LOADS the imported budget, so it re-points the process-global
|
|
338
|
+
* singleton exactly as a download does, and a large YNAB or zip import exceeding
|
|
339
|
+
* ACTUAL_OP_TIMEOUT_MS is the expected case rather than a rare one. Before this, nothing cleared
|
|
340
|
+
* the record before it started, nothing registered the promise, and the sentinel was written
|
|
341
|
+
* AFTER the await, so a timeout skipped it entirely and the record went on naming the PRE-IMPORT
|
|
342
|
+
* budget while the singleton moved to an out-of-registry, un-ACL'd file. A victim session then
|
|
343
|
+
* passed the #390 precondition legitimately and had its reads served from the importer's file.
|
|
344
|
+
*
|
|
345
|
+
* ACCEPTED COST, recorded because nothing else states it. Registering the import means every
|
|
346
|
+
* subsequent `withApiLock` acquisition waits for it, bounded, and throws on timeout. An import is
|
|
347
|
+
* not "stuck", it is legitimately long: a large YNAB or zip import can run for minutes. So while
|
|
348
|
+
* one runs past ACTUAL_OP_TIMEOUT_MS, other sessions stall for that bound and then fail with
|
|
349
|
+
* "abandoned budget load timed out", and write drains reject their batch. That is a strictly
|
|
350
|
+
* better failure than the silent cross-tenant read it replaces (a victim reading the importer's
|
|
351
|
+
* un-ACL'd file), and it is the same trade #393 accepted for downloads. It is NOT free, and the
|
|
352
|
+
* operator-facing consequence is a process-wide stall for the duration of one tenant's import.
|
|
353
|
+
* Giving imports their own larger bound is tracked separately rather than bolted on here.
|
|
354
|
+
*
|
|
355
|
+
* No `verify` here, deliberately: unlike `download-budget`, upstream's `importBudget` already
|
|
356
|
+
* asserts its own post-condition. It checks `result.error` and then `!result.id`, throwing
|
|
357
|
+
* "no budget was loaded", so it cannot resolve without having loaded something. Verified in the
|
|
358
|
+
* shipped upstream source. Adding a probe would be duplicate work on the write path.
|
|
359
|
+
*/
|
|
360
|
+
export async function importBudgetTracked(start, label = 'importBudget') {
|
|
361
|
+
// A sentinel rather than a real syncId: an imported file is outside the budget registry and
|
|
362
|
+
// outside the ACL, so no session can ever legitimately match it and every session's next
|
|
363
|
+
// operation re-selects its own budget. Configured sync ids are UUIDs, so an `imported:` prefix
|
|
364
|
+
// can never compare equal to one.
|
|
365
|
+
return trackBudgetMutation(start, (result) => `imported:${result.id}`, label);
|
|
366
|
+
}
|
|
367
|
+
export async function loadBudgetTracked(syncId, encryptionPassword, label = 'downloadBudget') {
|
|
368
|
+
try {
|
|
369
|
+
await trackBudgetMutation(() => {
|
|
370
|
+
const started = encryptionPassword
|
|
371
|
+
? api
|
|
372
|
+
.downloadBudget(syncId, { password: encryptionPassword })
|
|
373
|
+
: api.downloadBudget(syncId);
|
|
374
|
+
// Indeterminate from the moment the download starts. `trackBudgetMutation` clears the
|
|
375
|
+
// record too; this repeats it at the CALL SITE on purpose, AFTER the call, because block
|
|
376
|
+
// (4) of tests/unit/budget_selection_precondition.test.js scans FORWARD from the matched
|
|
377
|
+
// line to the end of its brace-balanced block and requires a record there. Satisfying
|
|
378
|
+
// that structurally, rather than exempting this file from the guard, is what keeps the
|
|
379
|
+
// #390 protection worth having.
|
|
380
|
+
setLoadedBudgetSyncId(null);
|
|
381
|
+
return started;
|
|
382
|
+
}, () => syncId, label,
|
|
383
|
+
// #396: the post-condition runs INSIDE the tracked chain, before the record is written, so
|
|
384
|
+
// an ABANDONED load is verified when it lands rather than recording a success nobody
|
|
385
|
+
// checked. The network enrichment below deliberately does NOT run there.
|
|
386
|
+
assertBudgetOpen, () => clearCachedReason(syncId));
|
|
387
|
+
}
|
|
388
|
+
catch (err) {
|
|
389
|
+
// Enrich HERE, where a caller is actually waiting. Every `withApiLock` acquisition settles
|
|
390
|
+
// all registrations under ONE bound and fails closed on timeout, so two network calls inside
|
|
391
|
+
// the tracked chain would extend the window in which unrelated sessions' lock acquisitions
|
|
392
|
+
// throw, to build a message an abandoned load has no caller to read.
|
|
393
|
+
if (isBudgetNotOpen(err)) {
|
|
394
|
+
log.error('download resolved but no budget is open', undefined, { syncId });
|
|
395
|
+
throw postConditionError(syncId, await diagnose(syncId));
|
|
396
|
+
}
|
|
397
|
+
throw err;
|
|
398
|
+
}
|
|
399
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "actual-mcp-server",
|
|
3
3
|
"displayName": "Actual MCP Server",
|
|
4
|
-
"version": "0.16.
|
|
4
|
+
"version": "0.16.6",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22.0.0",
|
|
7
7
|
"npm": ">=10.0.0"
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"verify-tools": "npm run build && node scripts/verify-tools.js",
|
|
31
31
|
"check:coverage": "node scripts/list-actual-api-methods.mjs",
|
|
32
32
|
"direct-sync": "node scripts/direct-sync/bank-sync-direct.mjs",
|
|
33
|
-
"test:unit-js": "node tests/unit/transactions_create.test.js && node tests/unit/generated_tools.smoke.test.js && node tests/unit/schema_validation.test.js && node tests/unit/schema_json_openai_compat.test.js && node tests/unit/config_https_validation.test.js && node tests/unit/config_data_dir.test.js && node tests/unit/config_drift.test.js && node tests/unit/port_alignment.test.js && node tests/unit/dockerfile_data_dir_alignment.test.js && node tests/unit/unraid_template_alignment.test.js && node tests/unit/entrypoint_invariants.test.js && node tests/unit/e2e_spec_collection.test.js && node tests/unit/compose_profile_sync.test.js && node tests/unit/advertised_tools_sync.test.js && node tests/unit/knip_config.test.js && node tests/unit/readme_stats_sync.test.js && node tests/unit/config_insecure_upstream.test.js && node tests/unit/workflow_release_guards.test.js && node tests/unit/report_train_failure.test.js && node tests/unit/unit_chain_membership.test.js && node tests/unit/api_surface_drift.test.js && node tests/unit/write_effect_audit_staleness.test.js && node tests/unit/write_effect_audit_membership.test.js && node tests/unit/tool_annotations.test.js && node tests/unit/tool_id_schema_drift.test.js && node tests/unit/api_coverage_baseline.test.js && node tests/unit/train_preflight.test.js && node tests/unit/verify_published_artifacts.test.js && node tests/unit/report_train_stale.test.js && node tests/unit/stdio_framing_check.test.js && node tests/unit/server_info.test.js && node tests/unit/transfers_create.test.js && node tests/unit/bot_target_branch.test.js && node tests/unit/auth_posture.test.js && node tests/unit/auth_posture_wiring.test.js && node tests/unit/auth-acl.test.js && node tests/unit/bug76.test.js && node tests/unit/budgets_setAmount.test.js && node tests/unit/budgets_hold_for_next_month.test.js && node tests/unit/budgets_transfer.test.js && node tests/unit/transactions_uncategorized.test.js && node tests/unit/httpServer_session_init.test.js && node tests/unit/httpServer_session_not_found.test.js && node tests/unit/manual_mcp_client_retry.test.js && node tests/unit/manual_mcp_client_session.test.js && node tests/unit/manual_mcp_client_circuit.test.js && node tests/unit/manual_runner_killswitch.test.js && node tests/unit/adapter_auth_rate_limit.test.js && node tests/unit/adapter_session_reuse.test.js && node tests/unit/retry_classifier.test.js && node tests/unit/adapter_module_surface.test.js && node tests/unit/adapter_nonidempotent_no_retry.test.js && node tests/unit/pool_liveness.test.js && node tests/unit/pool_shutdown_all.test.js && node tests/unit/query_where_operators.test.js && node tests/unit/query_run_validation.test.js && node tests/unit/adapter_with_write_session.test.js && node tests/unit/category_groups_delete.test.js && node tests/unit/rules_delete.test.js && node tests/unit/schedules_delete.test.js && node tests/unit/accounts_delete.test.js && node tests/unit/update_tools_not_found.test.js && node tests/unit/accounts_close.test.js && node tests/unit/accounts_reopen.test.js && node tests/unit/payees_delete.test.js && node tests/unit/payees_merge.test.js && node tests/unit/rules_create_or_update.test.js && node tests/unit/unhandled-rejection.test.js && node tests/unit/rejection-allowlist-purity.test.js && node tests/unit/httpServer_bearer_auth.test.js && node tests/unit/httpServer_oidc_audience.test.js && node tests/unit/httpServer_oidc_auth_verification.test.js && node tests/unit/httpServer_oidc_jwks_discovery.test.js && node tests/unit/httpServer_body_limit.test.js && node tests/unit/httpServer_bind_host.test.js && node tests/unit/adapter_write_pool_cooperation.test.js && node tests/unit/adapter_drain_listing_cache.test.js && node tests/unit/budget_acl_enforcement.test.js && node tests/unit/budget_preference_store.test.js && node tests/unit/budget_preference_restore.test.js && node tests/unit/tags_list.test.js && node tests/unit/tags_create.test.js && node tests/unit/tags_update.test.js && node tests/unit/tags_delete.test.js && node tests/unit/notes_get.test.js && node tests/unit/notes_update.test.js && node tests/unit/payees_common_list.test.js && node tests/unit/transactions_update_guard.test.js && node tests/unit/transactions_update_splits.test.js && node tests/unit/entities_search.test.js && node tests/unit/transactions_import_schema.test.js && node tests/unit/tool_schema_shape.test.js && node tests/unit/zod_error_format.test.js && node tests/unit/tool_count_sync.test.js && node tests/unit/stdio_transport.test.js && node tests/unit/stdio_budget_switch.test.js && node tests/unit/logger_structured.test.js && node tests/unit/logger_redaction.test.js && node tests/unit/logger_correlation.test.js && node tests/unit/check_coverage.test.js && node tests/unit/adapter_op_timeout.test.js && node tests/unit/adapter_write_queue_wakeup.test.js && node tests/unit/ci_workflow_guards.test.js && node tests/unit/node_version_guard.test.js && node tests/unit/node_version_drift.test.js && node tests/unit/observability_smoke.test.js && node tests/unit/residue_pattern.test.js && node tests/unit/dual_transport_gate.test.js && node tests/unit/manual_assertions_use_helper.test.js && node tests/unit/server_version_guard.test.js && node tests/unit/payee_rules_reference_filter.test.js && node tests/unit/oidc_metadata_discovery.test.js && node tests/unit/httpServer_oauth_metadata_route.test.js && node tests/unit/httpServer_mcp_info_route.test.js && node tests/unit/residue_sweep_balance_account.test.js && node tests/unit/tool_factory.test.js && node tests/unit/budget_registry_parse.test.js && node tests/unit/preferences_get.test.js && node tests/unit/budgets_export.test.js && node tests/unit/budgets_import.test.js && node tests/unit/budgets_import_syncid.test.js && node tests/unit/budget_acl_dynamic.test.js && node tests/unit/budget_acl_identity_map.test.js && node tests/unit/budget_acl_userinfo.test.js && node tests/unit/acl_e2e_fixture_contract.test.js && node tests/unit/budget_acl_middleware.test.js && node tests/unit/rules_stage.test.js",
|
|
33
|
+
"test:unit-js": "node tests/unit/transactions_create.test.js && node tests/unit/generated_tools.smoke.test.js && node tests/unit/schema_validation.test.js && node tests/unit/schema_json_openai_compat.test.js && node tests/unit/config_https_validation.test.js && node tests/unit/config_data_dir.test.js && node tests/unit/config_drift.test.js && node tests/unit/port_alignment.test.js && node tests/unit/dockerfile_data_dir_alignment.test.js && node tests/unit/unraid_template_alignment.test.js && node tests/unit/entrypoint_invariants.test.js && node tests/unit/e2e_spec_collection.test.js && node tests/unit/compose_profile_sync.test.js && node tests/unit/advertised_tools_sync.test.js && node tests/unit/knip_config.test.js && node tests/unit/readme_stats_sync.test.js && node tests/unit/config_insecure_upstream.test.js && node tests/unit/workflow_release_guards.test.js && node tests/unit/report_train_failure.test.js && node tests/unit/unit_chain_membership.test.js && node tests/unit/api_surface_drift.test.js && node tests/unit/write_effect_audit_staleness.test.js && node tests/unit/write_effect_audit_membership.test.js && node tests/unit/tool_annotations.test.js && node tests/unit/tool_id_schema_drift.test.js && node tests/unit/api_coverage_baseline.test.js && node tests/unit/train_preflight.test.js && node tests/unit/verify_published_artifacts.test.js && node tests/unit/report_train_stale.test.js && node tests/unit/stdio_framing_check.test.js && node tests/unit/server_info.test.js && node tests/unit/transfers_create.test.js && node tests/unit/bot_target_branch.test.js && node tests/unit/auth_posture.test.js && node tests/unit/auth_posture_wiring.test.js && node tests/unit/auth-acl.test.js && node tests/unit/bug76.test.js && node tests/unit/budgets_setAmount.test.js && node tests/unit/budgets_hold_for_next_month.test.js && node tests/unit/budgets_transfer.test.js && node tests/unit/transactions_uncategorized.test.js && node tests/unit/httpServer_session_init.test.js && node tests/unit/httpServer_session_not_found.test.js && node tests/unit/manual_mcp_client_retry.test.js && node tests/unit/manual_mcp_client_session.test.js && node tests/unit/manual_mcp_client_circuit.test.js && node tests/unit/manual_runner_killswitch.test.js && node tests/unit/adapter_auth_rate_limit.test.js && node tests/unit/adapter_session_reuse.test.js && node tests/unit/retry_classifier.test.js && node tests/unit/adapter_module_surface.test.js && node tests/unit/adapter_nonidempotent_no_retry.test.js && node tests/unit/pool_liveness.test.js && node tests/unit/pool_shutdown_all.test.js && node tests/unit/query_where_operators.test.js && node tests/unit/query_run_validation.test.js && node tests/unit/adapter_with_write_session.test.js && node tests/unit/category_groups_delete.test.js && node tests/unit/rules_delete.test.js && node tests/unit/schedules_delete.test.js && node tests/unit/accounts_delete.test.js && node tests/unit/update_tools_not_found.test.js && node tests/unit/accounts_close.test.js && node tests/unit/accounts_reopen.test.js && node tests/unit/payees_delete.test.js && node tests/unit/payees_merge.test.js && node tests/unit/rules_create_or_update.test.js && node tests/unit/unhandled-rejection.test.js && node tests/unit/rejection-allowlist-purity.test.js && node tests/unit/httpServer_bearer_auth.test.js && node tests/unit/httpServer_oidc_audience.test.js && node tests/unit/httpServer_oidc_auth_verification.test.js && node tests/unit/httpServer_oidc_jwks_discovery.test.js && node tests/unit/httpServer_body_limit.test.js && node tests/unit/httpServer_bind_host.test.js && node tests/unit/adapter_write_pool_cooperation.test.js && node tests/unit/adapter_drain_listing_cache.test.js && node tests/unit/budget_acl_enforcement.test.js && node tests/unit/budget_selection_precondition.test.js && node tests/unit/budget_load_abandonment.test.js && node tests/unit/budget_loader_postcondition.test.js && node tests/unit/budget_loader_import_allowlist.test.js && node tests/unit/budget_import_tracking.test.js && node tests/unit/pool_shutdown_under_lock.test.js && node tests/unit/budget_preference_store.test.js && node tests/unit/budget_preference_restore.test.js && node tests/unit/tags_list.test.js && node tests/unit/tags_create.test.js && node tests/unit/tags_update.test.js && node tests/unit/tags_delete.test.js && node tests/unit/notes_get.test.js && node tests/unit/notes_update.test.js && node tests/unit/payees_common_list.test.js && node tests/unit/transactions_update_guard.test.js && node tests/unit/transactions_update_splits.test.js && node tests/unit/entities_search.test.js && node tests/unit/transactions_import_schema.test.js && node tests/unit/tool_schema_shape.test.js && node tests/unit/zod_error_format.test.js && node tests/unit/tool_count_sync.test.js && node tests/unit/stdio_transport.test.js && node tests/unit/stdio_budget_switch.test.js && node tests/unit/logger_structured.test.js && node tests/unit/logger_redaction.test.js && node tests/unit/logger_correlation.test.js && node tests/unit/check_coverage.test.js && node tests/unit/adapter_op_timeout.test.js && node tests/unit/adapter_write_queue_wakeup.test.js && node tests/unit/ci_workflow_guards.test.js && node tests/unit/node_version_guard.test.js && node tests/unit/node_version_drift.test.js && node tests/unit/observability_smoke.test.js && node tests/unit/residue_pattern.test.js && node tests/unit/dual_transport_gate.test.js && node tests/unit/manual_assertions_use_helper.test.js && node tests/unit/server_version_guard.test.js && node tests/unit/payee_rules_reference_filter.test.js && node tests/unit/oidc_metadata_discovery.test.js && node tests/unit/httpServer_oauth_metadata_route.test.js && node tests/unit/httpServer_mcp_info_route.test.js && node tests/unit/residue_sweep_balance_account.test.js && node tests/unit/tool_factory.test.js && node tests/unit/budget_registry_parse.test.js && node tests/unit/preferences_get.test.js && node tests/unit/budgets_export.test.js && node tests/unit/budgets_import.test.js && node tests/unit/budgets_import_syncid.test.js && node tests/unit/budget_acl_dynamic.test.js && node tests/unit/budget_acl_identity_map.test.js && node tests/unit/budget_acl_userinfo.test.js && node tests/unit/acl_e2e_fixture_contract.test.js && node tests/unit/budget_acl_middleware.test.js && node tests/unit/rules_stage.test.js",
|
|
34
34
|
"test:adapter": "npm run build && node dist/src/tests_adapter_runner.js",
|
|
35
35
|
"test:e2e": "npx playwright test",
|
|
36
36
|
"test:e2e:docker": "./tests/e2e/run-docker-e2e.sh",
|