@diy-accounting-uk/diya-submit 0.1.4 → 0.1.8

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 CHANGED
@@ -45,7 +45,7 @@ can read the tools first. The first tool call without a token gets 401 with a `W
45
45
  challenge. The client finds the sign-in through `/.well-known/oauth-protected-resource/mcp`, registers itself, and
46
46
  the user signs in with their Submit account. The ci form of the URL is
47
47
  `https://ci-submit.diyaccounting.co.uk/mcp`. The hosted tool set is `HOSTED_TOOL_NAMES` in
48
- `lib/hosted-tools.js`: `open_book` reads the DIYA cloud only. The sign-in pair, the filesystem tools,
48
+ `lib/hosted-tools.js`: `open_book` reads the DIY Accounting Submit account only. The sign-in pair, the filesystem tools,
49
49
  the practice tools that still take an HMRC token, and `run_for_clients` are not registered.
50
50
 
51
51
  ## HMRC fraud prevention data
@@ -67,11 +67,12 @@ HMRC requires data about the device behind each request. The two surfaces send d
67
67
  | `list_vat_obligations` | VAT obligations for `vrn` (or `clientId`), filtered by `from`, `to`, `status`. Uses the session's HMRC authorisation; optional `hmrcAccount` (the authorisation's own by default), `govTestScenario`. |
68
68
  | `submit_vat_return` | Files the seven confirmed boxes (`vatDueSales`, `vatDueAcquisitions`, `vatReclaimedCurrPeriod`, `totalValueSalesExVAT`, `totalValuePurchasesExVAT`, `totalValueGoodsSuppliedExVAT`, `totalAcquisitionsExVAT`) for `periodStart` to `periodEnd`, for `vatNumber` or `clientId`. Uses the session's HMRC authorisation. Answers `receipt`, `periodKey`, `receiptId`. |
69
69
  | `get_vat_receipt` | A stored VAT return receipt by `name` (`<receiptId>.json`); optional `clientId`. Answers HMRC's `processingDate`, `formBundleNumber`, `paymentIndicator` and `chargeRefNumber`. |
70
- | `render_micro_entity_accounts_sandbox` | The rendered micro-entity iXBRL for confirmed figures, without reaching the Companies House gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `balanceSheet`, `averageEmployees`, `director`, `statementsAccepted`. |
71
- | `render_small_company_accounts_sandbox` | The rendered small-company (FRS 102 section 1A) iXBRL for confirmed figures, without reaching the gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `averageEmployees`, `director`, `statementsAccepted` (four small-company statements) and `smallCompany` (`filleted`, `principalActivity`, `accountingPolicies`, `directors`, `balanceSheet`, `profitAndLoss`, `fixedAssetNote`). |
70
+ | `list_accounts_receipts` | The signed-in account's newest 25 accounts filings, newest first, with `more: true` when there are older ones it does not list; optional `clientId`. Each accepted filing answers `name` (the receipt name `revision.revisesReceipt` takes), `companyNumber`, `periodStart`, `periodEnd`, `accountsType`, `status`, `revisedAccounts`, `filedWithCompanyTaxReturn`, `revisable` and `filedOn`, and `problem` with the reason when the receipt cannot be read or its filed document does not read as accounts; each rejected filing answers its `submissionNumber` and Companies House's `rejections`. Call it before revising accounts already filed. Hosted outside prod and on the local server. |
71
+ | `render_micro_entity_accounts_sandbox` | The rendered micro-entity iXBRL for confirmed figures, without reaching the Companies House gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `balanceSheet`, `averageEmployees`, `director`, `statementsAccepted`; optional `revision` (`originalDateOfApproval`, `nonCompliance`, `amendments`, and optionally `revisesReceipt`, the name of the accepted accounts receipt it revises, which the filing route checks) renders revised accounts that replace accounts already filed; optional `documentLanguage` (`cy` files the accounts in Welsh, for a company registered in Wales), `directorsAdvances` (one row per director: `name`, `terms`, `balanceAtStart`, `advanced`, `repaid`, `balanceAtEnd`, printed in the note on advances and credits to directors), and for a dormant company `dormant`, `dormantTradingStatus` (`neverTraded` or `noLongerTrading`), `shareClass` and `nominalValue`. |
72
+ | `render_small_company_accounts_sandbox` | The rendered small-company (FRS 102 section 1A) iXBRL for confirmed figures, without reaching the gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `averageEmployees`, `director`, `statementsAccepted` (four small-company statements) and `smallCompany` (`filleted`, `principalActivity`, `accountingPolicies`, `directors`, `balanceSheet`, `profitAndLoss`, `fixedAssetNote`); optional `revision` and `documentLanguage` as for the micro-entity render, and `smallCompany.directorsAdvances` (inside `smallCompany`, each row naming one of `smallCompany.directors`, closing at `balanceSheet.currentYear.amountsOwedByDirectors`). A dormant company files micro-entity accounts. |
72
73
  | `request_companies_house_codes` | A link where the user types the Companies House codes instead of the chat. `kind` is `accounts`, `confirmation-statement` (with `directors` in filing order) or `confirmation-statement-data`; answers `entryId`, `url`, `expiresAt`. The entry lasts ten minutes and one filing call uses it up. With `clientIds` (no `companyNumber`) the page asks for one code per practice client and each client's filing call, including through `run_for_clients`, takes only its own. |
73
- | `submit_micro_entity_accounts_sandbox` | Files the same figures with the codes the user typed on that link, named by `codesEntryId`; answers `submissionNumber`. |
74
- | `submit_small_company_accounts_sandbox` | Files the small-company figures with the codes named by `codesEntryId`, for `companyNumber` or `clientId`; answers `submissionNumber`. Poll it with `poll_submission` kind `accounts`. |
74
+ | `submit_micro_entity_accounts_sandbox` | Files the same figures with the codes the user typed on that link, named by `codesEntryId`; answers `submissionNumber`. With `revision`, files revised accounts that replace accounts already filed for the same period. Takes the render tool's optional fields. |
75
+ | `submit_small_company_accounts_sandbox` | Files the small-company figures with the codes named by `codesEntryId`, for `companyNumber` or `clientId`; answers `submissionNumber`. Poll it with `poll_submission` kind `accounts`. With `revision`, files revised accounts that replace accounts already filed for the same period. Takes the render tool's optional fields. |
75
76
  | `poll_submission` | The outcome of a Companies House filing, `kind` `accounts` or `confirmation-statement`, for a `submissionNumber`: `PENDING`, `ACCEPT` (with `receiptId`) or `REJECT` (with `rejections`). |
76
77
 
77
78
  The filing tools call the deployed REST API at `DIYA_SUBMIT_BASE_URL` with the MCP's own sign-in bearer (`sign_in`), and poll a 202 answer to its terminal status. They validate required inputs before any request.
@@ -6,7 +6,7 @@
6
6
  // app/services/microEntityAccounts.js, shared with the nightly company
7
7
  // book pull; this file re-exports it for the MCP tool registration.
8
8
  // derive_company_tax_return: the Company Tax Return figures from the loaded
9
- // Company book, the file the web "Fill from your books" card reads.
9
+ // Company book, the file the web "Fill from your records" card reads.
10
10
 
11
11
  import { mkdirSync, writeFileSync } from "node:fs";
12
12
  import { basename, dirname, resolve as resolvePath } from "node:path";
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // book-read-tools.js -- diya-gl's read tools over the session's open DIYA-GL book: the report, the
5
+ // trial balance, the book checks, the ledger lines, the chart of accounts and the book's profile.
6
+ // Each calls the published @diy-accounting-uk/diya-gl tool's own handler with the session's book and
7
+ // lines; no engine code lives here. The titles and descriptions use Submit's customer wording.
8
+
9
+ import { z } from "zod";
10
+
11
+ import { LINE_GROUPINGS } from "@diy-accounting-uk/diya-gl/dist/app/lib/book-queries.js";
12
+ import { TOOLS as DIYA_GL_TOOLS } from "@diy-accounting-uk/diya-gl/dist/app/lib/mcp/diya-gl-tools.js";
13
+
14
+ import { READS } from "./tool-annotations.js";
15
+
16
+ // The open book alone, never a book or lines passed in a call: diya-gl's handlers take either.
17
+ function openBookOnly(session) {
18
+ if (!session.book || !session.lines) throw new Error("No book is loaded. Call open_book first.");
19
+ return { book: session.book, lines: session.lines };
20
+ }
21
+
22
+ function diyaGlRead(name) {
23
+ return (session, params = {}) => DIYA_GL_TOOLS[name].handler(openBookOnly(session), params);
24
+ }
25
+
26
+ const oneOrMany = (description) =>
27
+ z
28
+ .union([z.string(), z.array(z.string())])
29
+ .optional()
30
+ .describe(description);
31
+
32
+ /**
33
+ * The read tools keyed by MCP name, in the shape server.js's TOOLS table uses; createServer
34
+ * registers them beside it.
35
+ */
36
+ export const BOOK_READ_TOOLS = {
37
+ report: {
38
+ title: "Report a DIYA-GL book's figures",
39
+ annotations: READS,
40
+ description:
41
+ "Works out the figures of the open DIYA-GL book (one business's sales, purchases and bank lines for a year): " +
42
+ "the profit and loss account, the balance sheet, the tax and VAT figures and the compliance checks, each figure " +
43
+ "with the label the spreadsheet prints for it, and the book checks. Use this when the person asks what their " +
44
+ "profit, turnover, tax bill or VAT due is, or which lines make up a figure (entryNumbers). It does not change the " +
45
+ "book, file anything or contact HMRC.",
46
+ inputSchema: {
47
+ entryNumbers: z
48
+ .union([z.boolean(), z.array(z.string())])
49
+ .optional()
50
+ .describe(
51
+ "true gives every figure the entryNumbers of the lines behind it; a list of figure keys (for example " +
52
+ "section/profit-loss-account/sales-turnover) gives them to those figures only",
53
+ ),
54
+ },
55
+ handler: diyaGlRead("report"),
56
+ },
57
+ trial_balance: {
58
+ title: "Trial balance of a DIYA-GL book",
59
+ annotations: READS,
60
+ description:
61
+ "Answers the trial balance of the open DIYA-GL book of a company: every account's balance in the debit or the credit " +
62
+ "column and the two totals, over the year, one month, one VAT quarter or a date range, with the year-end postings " +
63
+ "of the registers. Name an account to also get the lines and postings behind its balance. Use this when the " +
64
+ "person asks whether their trial balance balances, what an account's balance is, or what moved in a month. " +
65
+ "Company DIYA-GL books only. It does not change the book or contact HMRC.",
66
+ inputSchema: {
67
+ period: z
68
+ .enum(["year", "month", "vatQuarter", "custom"])
69
+ .optional()
70
+ .describe("year (the default), month, vatQuarter, or custom with from and to"),
71
+ month: z.string().optional().describe("YYYY-MM of the month, or of the VAT quarter's last month; needed for month and vatQuarter"),
72
+ from: z.string().optional().describe("First day, YYYY-MM-DD inclusive, for a custom range"),
73
+ to: z.string().optional().describe("Last day, YYYY-MM-DD inclusive, for a custom range"),
74
+ account: z.string().optional().describe("An account id (for example 1300); adds that account's postings"),
75
+ },
76
+ handler: diyaGlRead("trial_balance"),
77
+ },
78
+ checks: {
79
+ title: "Check a DIYA-GL book",
80
+ annotations: READS,
81
+ description:
82
+ "Answers every book check and warning over the open DIYA-GL book, each with its verdict (pass, warn or fail), what it " +
83
+ "means and the entryNumbers of the lines that fail it, with the pass, warn and fail counts. Use this when the " +
84
+ "person asks whether anything is wrong with their records, which entries fall outside the year, which sales " +
85
+ "have no invoice number, whether there are duplicates, or how near they are to the VAT threshold. It does not " +
86
+ "change the book or contact HMRC.",
87
+ inputSchema: {},
88
+ handler: diyaGlRead("checks"),
89
+ },
90
+ lines: {
91
+ title: "Read a DIYA-GL book's lines",
92
+ annotations: READS,
93
+ description:
94
+ "Reads the lines of the open DIYA-GL book (every sale, purchase, bank movement, payslip and journal entry, with " +
95
+ "its entryNumber, journal, account, date, amount, customer, supplier or payee, description, reference and VAT " +
96
+ "fields), filtered and optionally grouped with a count and a total in pence. Filters combine: journal, account, " +
97
+ "dates, text and reference. Use this when the person asks who their best customer is, which suppliers cost most, " +
98
+ "what they spent on something in a month, or for their largest sales or purchases. It does not change the book.",
99
+ inputSchema: {
100
+ journal: oneOrMany("The journals to keep: sales, purchases, bank, payroll or journal"),
101
+ accountMainID: oneOrMany("The account ids to keep, for example 4000 (the chart tool lists them)"),
102
+ from: z.string().optional().describe("The earliest date kept, YYYY-MM-DD inclusive"),
103
+ to: z.string().optional().describe("The latest date kept, YYYY-MM-DD inclusive"),
104
+ text: z.string().optional().describe("Text found in the customer, supplier or payee, or the description, ignoring case"),
105
+ documentReference: z.string().optional().describe("Text found in the reference, ignoring case"),
106
+ groupBy: z.enum(LINE_GROUPINGS).optional().describe("detailComment (customer or supplier), accountMainID or month (YYYY-MM)"),
107
+ top: z.number().int().min(1).optional().describe("Keep at most this many groups, or without groupBy the largest lines"),
108
+ },
109
+ handler: diyaGlRead("lines"),
110
+ },
111
+ chart: {
112
+ title: "Chart of accounts of a DIYA-GL book",
113
+ annotations: READS,
114
+ description:
115
+ "Answers the chart of accounts of the open DIYA-GL book: each account's id, name, group, class and normal side, for a " +
116
+ "company the accounts line it feeds, the spreadsheet column it lands in, how many lines post to it with their " +
117
+ "total in pence, and the report rows it reaches. Use this when the person asks which account to use for " +
118
+ "something, where a cost shows in their accounts, or which accounts have no activity. It does not change the book.",
119
+ inputSchema: {},
120
+ handler: diyaGlRead("chart"),
121
+ },
122
+ book: {
123
+ title: "Profile of a DIYA-GL book",
124
+ annotations: READS,
125
+ description:
126
+ "Answers the profile of the open DIYA-GL book: the product, the accounting period, the business (name, trade, address, " +
127
+ "VAT registration, cash or accruals basis), the tax settings, the bank accounts, the journals with their line " +
128
+ "counts and dates, and the registers it carries (directors, employees, debtors, creditors, fixed assets, " +
129
+ "dividends, members, opening balances, stock). Use this when the person asks what period their records cover, " +
130
+ "whether they are VAT registered, or who their directors or employees are. It does not change the book.",
131
+ inputSchema: {},
132
+ handler: diyaGlRead("book"),
133
+ },
134
+ };
package/lib/book-tools.js CHANGED
@@ -21,6 +21,7 @@
21
21
  // State: one loaded book per session, a plain object this module owns the
22
22
  // shape of. open_book replaces it outright; save_book reads it.
23
23
 
24
+ import { randomUUID } from "node:crypto";
24
25
  import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
25
26
  import { basename, extname, resolve as resolvePath } from "node:path";
26
27
 
@@ -36,10 +37,11 @@ import { stampBook } from "@diy-accounting-uk/diya-gl/dist/app/lib/provenance.js
36
37
 
37
38
  import { storedCredentials } from "./auth.js";
38
39
  import { desktopClientHeaders } from "./client-headers.js";
40
+ import { UNKNOWN_CLIENT } from "./client-kind.js";
39
41
 
40
42
  export const SAVE_FORMATS = ["diya-gl-dir", "diya-gl-zip", "json", "xlsx", "zip"];
41
43
 
42
- // The DIYA cloud forms of open_book/save_book reach DIY Accounting Submit's own storage routes
44
+ // The DIY Accounting Submit account forms of open_book/save_book reach DIY Accounting Submit's own storage routes
43
45
  // (diyaGlListGet.js, diyaGlVersionGet.js, diyaGlPut.js), the same routes the spreadsheets site's
44
46
  // DIYA-GL pages use, over the session's credentials. Configuration comes from the
45
47
  // environment: DIYA_SUBMIT_BASE_URL, the same variable practice-tools.js and submit-tools.js read.
@@ -58,14 +60,21 @@ function baseUrl() {
58
60
  * clientHeaders answers the headers a call to an HMRC route carries for HMRC's fraud prevention
59
61
  * data (the stdio server reads its own machine; the hosted Lambda passes what the caller gives).
60
62
  * @param {{credentials?: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>},
61
- * pollBudgetMs?: number|null, clientHeaders?: () => Promise<Object>}} [options]
62
- * @returns {{book: Object|null, lines: Array|null, product: string|null, sourcePath: string|null,
63
+ * pollBudgetMs?: number|null, clientHeaders?: () => Promise<Object>, client?: string}} [options] - client is the
64
+ * assistant's kind from client-kind.js
65
+ * @returns {{client: string, book: Object|null, lines: Array|null, product: string|null, sourcePath: string|null,
63
66
  * cloud: {bookId: string, clientId: string|null, etag: string}|null,
64
67
  * credentials: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>},
65
68
  * pollBudgetMs: number|null, clientHeaders: () => Promise<Object>}}
66
69
  */
67
- export function createSession({ credentials = storedCredentials, pollBudgetMs = null, clientHeaders = desktopClientHeaders } = {}) {
70
+ export function createSession({
71
+ credentials = storedCredentials,
72
+ pollBudgetMs = null,
73
+ clientHeaders = desktopClientHeaders,
74
+ client = UNKNOWN_CLIENT,
75
+ } = {}) {
68
76
  return {
77
+ client,
69
78
  book: null,
70
79
  lines: null,
71
80
  product: null,
@@ -122,7 +131,16 @@ function summarise(session, bookChecks) {
122
131
  }
123
132
 
124
133
  /**
125
- * The metadata of each book saved in the DIYA cloud, most recently updated first, over the route
134
+ * The summary open_book answers, for the session's loaded book.
135
+ * @param {Object} session
136
+ */
137
+ export async function loadedBookSummary(session) {
138
+ requireLoaded(session);
139
+ return summarise(session, await bookChecksFor(session.book, session.lines));
140
+ }
141
+
142
+ /**
143
+ * The metadata of each book saved in the DIY Accounting Submit account, most recently updated first, over the route
126
144
  * the spreadsheets site's DIYA-GL pages list (GET /api/v1/books): every field the route stores,
127
145
  * the etag a replacing save sends among them. clientId lists a practice client's book set instead
128
146
  * of the practice's own.
@@ -165,7 +183,7 @@ export async function listBooks(session, { clientId } = {}) {
165
183
  }
166
184
 
167
185
  /**
168
- * The session's loaded book from the DIYA cloud by book id, over the same route the spreadsheets
186
+ * The session's loaded book from the DIY Accounting Submit account by book id, over the same route the spreadsheets
169
187
  * site's DIYA-GL pages read (GET /api/v1/books/{bookId}/versions/latest). Replaces the session's
170
188
  * loaded book and records the etag save_book's cloud form needs for its next if-match.
171
189
  */
@@ -279,24 +297,50 @@ function isoDateOrNull(value) {
279
297
  return new Date(value).toISOString().slice(0, 10);
280
298
  }
281
299
 
300
+ // An error from a cloud book route, carrying the HTTP status and the route's code so a caller can
301
+ // answer a stale version, a full account or an oversized book in its own words.
302
+ function cloudRouteError(response, body, fallback) {
303
+ const error = new Error(body?.message || fallback);
304
+ error.status = response.status;
305
+ error.code = body?.error?.code ?? body?.message ?? null;
306
+ return error;
307
+ }
308
+
282
309
  /**
283
- * The session's loaded book to the DIYA cloud by book id, over the same route the spreadsheets
284
- * site's DIYA-GL pages write (PUT /api/v1/books/{bookId}). Carries the if-match etag from the
285
- * session's last cloud open or save of this same bookId; a book saved here for the first time (no
286
- * prior cloud open) sends none, matching a brand-new book on that route.
310
+ * A new cloud book's id: the version 4 UUID the storage route's book id pattern takes.
311
+ * @returns {string}
287
312
  */
288
- async function saveCloudBook(session, { bookId, clientId } = {}) {
289
- requireLoaded(session);
290
- if (!bookId) throw new Error("save_book with cloud: true requires bookId");
291
- const { book, lines } = session;
292
- const info = book.documentInfo ?? {};
293
- const entity = book.entityInformation ?? {};
313
+ export function newCloudBookId() {
314
+ return randomUUID();
315
+ }
294
316
 
295
- const { results } = await bookChecksFor(book, lines);
296
- const bookchecks = JSON.parse(bookChecksJson(results));
297
- const zipBytes = Buffer.from(await writeDiyaGlZip({ book, lines, report: reportFor(book, lines), bookchecks }));
317
+ /**
318
+ * The stored DIYA-GL zip of one version of a cloud book, and the book's metadata, over the route
319
+ * open_book's cloud form reads (GET /api/v1/books/{bookId}/versions/{version}).
320
+ * @param {Object} session
321
+ * @param {{bookId: string, clientId?: string|null, version: number|"latest"}} params
322
+ * @returns {Promise<{bytes: Buffer, metadata: Object}>}
323
+ */
324
+ export async function readCloudVersion(session, { bookId, clientId, version }) {
325
+ const query = clientId ? `?clientId=${encodeURIComponent(clientId)}` : "";
326
+ const response = await fetch(`${baseUrl()}/api/v1/books/${encodeURIComponent(bookId)}/versions/${encodeURIComponent(version)}${query}`, {
327
+ headers: { Authorization: `Bearer ${await session.credentials.accessToken()}` },
328
+ });
329
+ const body = await response.json().catch(() => ({}));
330
+ if (!response.ok) throw cloudRouteError(response, body, `Reading version ${version} failed with HTTP ${response.status}`);
331
+ return { bytes: Buffer.from(body.zipBase64, "base64"), metadata: body.metadata };
332
+ }
298
333
 
299
- const ifMatch = session.cloud?.bookId === bookId ? session.cloud.etag : undefined;
334
+ /**
335
+ * Stores a DIYA-GL zip as the next version of a cloud book (PUT /api/v1/books/{bookId}). ifMatch is
336
+ * the etag of the version the zip replaces, or null for a new book. change says what made this
337
+ * version, for the version list and the activity record.
338
+ * @returns {Promise<Object>} the book's metadata after the write
339
+ */
340
+ export async function putCloudZip(
341
+ session,
342
+ { bookId, clientId, zipBytes, title, product, periodCoveredStart, periodCoveredEnd, ifMatch, change },
343
+ ) {
300
344
  const response = await fetch(`${baseUrl()}/api/v1/books/${encodeURIComponent(bookId)}`, {
301
345
  method: "PUT",
302
346
  headers: {
@@ -305,21 +349,68 @@ async function saveCloudBook(session, { bookId, clientId } = {}) {
305
349
  ...(ifMatch ? { "if-match": ifMatch } : {}),
306
350
  },
307
351
  body: JSON.stringify({
308
- title: entity.organizationIdentifier || bookId,
309
- product: session.product,
310
- periodCoveredStart: isoDateOrNull(info.periodCoveredStart),
311
- periodCoveredEnd: isoDateOrNull(info.periodCoveredEnd),
352
+ title,
353
+ product,
354
+ periodCoveredStart,
355
+ periodCoveredEnd,
312
356
  zipBase64: zipBytes.toString("base64"),
313
357
  ...(clientId ? { clientId } : {}),
358
+ ...(change ? { change } : {}),
314
359
  }),
315
360
  });
316
361
  const body = await response.json().catch(() => ({}));
317
- if (!response.ok) {
318
- throw new Error(body?.message || `save_book (cloud) failed with HTTP ${response.status}`);
319
- }
362
+ if (!response.ok) throw cloudRouteError(response, body, `save_book (cloud) failed with HTTP ${response.status}`);
363
+ return body.metadata;
364
+ }
320
365
 
321
- session.cloud = { bookId, clientId: clientId ?? null, etag: body.metadata.latestETag };
322
- return { path: null, format: "cloud", bookId, etag: body.metadata.latestETag, lineCount: lines.length, bytes: zipBytes.length };
366
+ /**
367
+ * The DIYA-GL zip of a book and lines, with the report and the book checks computed from them: the
368
+ * bytes the cloud stores.
369
+ * @returns {Promise<Buffer>}
370
+ */
371
+ export async function diyaGlZipOf(book, lines) {
372
+ const { results } = await bookChecksFor(book, lines);
373
+ const bookchecks = JSON.parse(bookChecksJson(results));
374
+ return Buffer.from(await writeDiyaGlZip({ book, lines, report: reportFor(book, lines), bookchecks }));
375
+ }
376
+
377
+ /**
378
+ * The session's loaded book to the DIY Accounting Submit account by book id, over the same route the spreadsheets
379
+ * site's DIYA-GL pages write (PUT /api/v1/books/{bookId}). Carries the if-match etag from the
380
+ * session's last cloud open or save of this same bookId; a book saved here for the first time (no
381
+ * prior cloud open), or one saved with newBook, sends none, matching a brand-new book on that route.
382
+ */
383
+ async function saveCloudBook(session, { bookId, clientId, change, newBook = false } = {}) {
384
+ requireLoaded(session);
385
+ if (!bookId) throw new Error("save_book with cloud: true requires bookId");
386
+ const { book, lines } = session;
387
+ const info = book.documentInfo ?? {};
388
+ const entity = book.entityInformation ?? {};
389
+
390
+ const zipBytes = await diyaGlZipOf(book, lines);
391
+ const ifMatch = !newBook && session.cloud?.bookId === bookId ? session.cloud.etag : undefined;
392
+ const metadata = await putCloudZip(session, {
393
+ bookId,
394
+ clientId,
395
+ zipBytes,
396
+ title: entity.organizationIdentifier || bookId,
397
+ product: session.product,
398
+ periodCoveredStart: isoDateOrNull(info.periodCoveredStart),
399
+ periodCoveredEnd: isoDateOrNull(info.periodCoveredEnd),
400
+ ifMatch,
401
+ change,
402
+ });
403
+
404
+ session.cloud = { bookId, clientId: clientId ?? null, etag: metadata.latestETag };
405
+ return {
406
+ path: null,
407
+ format: "cloud",
408
+ bookId,
409
+ etag: metadata.latestETag,
410
+ version: metadata.latestVersion,
411
+ lineCount: lines.length,
412
+ bytes: zipBytes.length,
413
+ };
323
414
  }
324
415
 
325
416
  /**
@@ -329,13 +420,13 @@ async function saveCloudBook(session, { bookId, clientId } = {}) {
329
420
  * engine's own interchange formats; xlsx and zip compose the product's
330
421
  * workbook or package, which fetches the template from
331
422
  * spreadsheets.diyaccounting.co.uk the first time it runs. With cloud: true,
332
- * writes to the DIYA cloud by bookId instead (a practice client's book set
423
+ * writes to the DIY Accounting Submit account by bookId instead (a practice client's book set
333
424
  * with clientId).
334
425
  * @param {Object} session
335
426
  * @param {{path: string, format?: string} | {cloud: true, bookId: string, clientId?: string}} params
336
427
  */
337
- export async function saveBook(session, { path, format, cloud, bookId, clientId } = {}) {
338
- if (cloud) return saveCloudBook(session, { bookId, clientId });
428
+ export async function saveBook(session, { path, format, cloud, bookId, clientId, change, newBook } = {}) {
429
+ if (cloud) return saveCloudBook(session, { bookId, clientId, change, newBook });
339
430
  if (!path) throw new Error("save_book requires a path, or cloud: true and bookId");
340
431
  requireLoaded(session);
341
432
  const { book, lines } = session;
@@ -0,0 +1,44 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // client-kind.js -- the kind of assistant an MCP client is, from the name it gives in
5
+ // initialize's params.clientInfo.name. The kind is a product name, not personal data.
6
+
7
+ export const UNKNOWN_CLIENT = "unknown";
8
+
9
+ // Checked in order: the first kind with a word in the name wins.
10
+ const KIND_WORDS = [
11
+ ["chatgpt", ["openai", "chatgpt"]],
12
+ ["claude", ["claude", "anthropic"]],
13
+ ["gemini", ["gemini", "google"]],
14
+ ["copilot", ["copilot", "microsoft"]],
15
+ ];
16
+
17
+ /**
18
+ * The client kind for a clientInfo.name: chatgpt, claude, gemini, copilot, other for any other
19
+ * name, or unknown when the client gave no name.
20
+ * @param {unknown} name
21
+ * @returns {"chatgpt"|"claude"|"gemini"|"copilot"|"other"|"unknown"}
22
+ */
23
+ export function clientKindOf(name) {
24
+ if (typeof name !== "string" || name.trim() === "") return UNKNOWN_CLIENT;
25
+ const lower = name.toLowerCase();
26
+ for (const [kind, words] of KIND_WORDS) {
27
+ if (words.some((word) => lower.includes(word))) return kind;
28
+ }
29
+ return "other";
30
+ }
31
+
32
+ export const CLIENT_NAME_LOG_LENGTH = 64;
33
+
34
+ /**
35
+ * The client's own name as the session log records it: printable ASCII only, each other character
36
+ * shown as "?", cut to CLIENT_NAME_LOG_LENGTH characters, or null when the client gave no name. A
37
+ * client chooses its name, so the log never takes it whole.
38
+ * @param {unknown} name
39
+ * @returns {string|null}
40
+ */
41
+ export function clientNameForLog(name) {
42
+ if (typeof name !== "string" || name.trim() === "") return null;
43
+ return name.slice(0, CLIENT_NAME_LOG_LENGTH).replace(/[^\x20-\x7e]/g, "?");
44
+ }
@@ -75,12 +75,14 @@ function parseCsvLine(line) {
75
75
  return fields;
76
76
  }
77
77
 
78
+ // NatWest writes "31 Jul 2025"; the same CSV saved again by Excel holds "31-Jul-25".
78
79
  function parseStatementDate(text) {
79
- const match = /^(\d{2}) (\w{3}) (\d{4})$/.exec(text.trim());
80
+ const match = /^(\d{2}) (\w{3}) (\d{4})$/.exec(text.trim()) || /^(\d{2})-(\w{3})-(\d{2})$/.exec(text.trim());
80
81
  if (!match) {
81
82
  throw new Error(`Unrecognised statement date "${text}"`);
82
83
  }
83
- const [, day, monthName, year] = match;
84
+ const [, day, monthName, yearDigits] = match;
85
+ const year = yearDigits.length === 2 ? `20${yearDigits}` : yearDigits;
84
86
  const month = MONTHS[monthName];
85
87
  if (!month) {
86
88
  throw new Error(`Unrecognised statement month "${monthName}"`);