dwelldelta-mcp 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -5
- package/contribute-tool.mjs +1 -1
- package/cover-tool.mjs +7 -4
- package/package.json +1 -1
- package/server.mjs +2 -2
- package/tools.mjs +16 -4
- package/vendor/contribute.mjs +126 -15
package/README.md
CHANGED
|
@@ -36,6 +36,13 @@ property you own - never an address, name or email. You get a deletion code; ema
|
|
|
36
36
|
and the record is deleted. Only your own rent may be added: an assistant must not add a figure it read on a
|
|
37
37
|
website or a listing.
|
|
38
38
|
|
|
39
|
+
From 0.15.0 it sends terms version 2026-11-03, whose consent, Contributor Terms and Privacy Notice name the lease
|
|
40
|
+
kind (whether it is a new lease or a renewal), which every contribution has recorded. 0.10.1 to 0.14.0 send
|
|
41
|
+
2026-10-27, which the endpoint accepts for now; once that stops, their contributions are refused (HTTP 409) - update
|
|
42
|
+
to 0.15.0 or later. From 0.15.0 a refusal the endpoint is known to give also says what to do, in the package's own
|
|
43
|
+
words ("Not added: the contribution was not saved (HTTP 409): the terms have changed: update dwelldelta-mcp (npx -y
|
|
44
|
+
dwelldelta-mcp@latest)."); any other reason gives the status alone.
|
|
45
|
+
|
|
39
46
|
## NSW sale prices (from 0.7.0)
|
|
40
47
|
|
|
41
48
|
`nsw_sale_prices` gives DCJ's medians for the dwellings sold in a quarter - not asking prices, not valuations,
|
|
@@ -58,14 +65,16 @@ Claude Desktop - add to `claude_desktop_config.json`:
|
|
|
58
65
|
"mcpServers": {
|
|
59
66
|
"dwelldelta": {
|
|
60
67
|
"command": "npx",
|
|
61
|
-
"args": ["-y", "dwelldelta-mcp"]
|
|
68
|
+
"args": ["-y", "dwelldelta-mcp@latest"]
|
|
62
69
|
}
|
|
63
70
|
}
|
|
64
71
|
}
|
|
65
72
|
```
|
|
66
73
|
|
|
67
|
-
Claude Code: `claude mcp add dwelldelta -- npx -y dwelldelta-mcp`. Any other MCP client: run
|
|
68
|
-
as a stdio server. Node 18 or later.
|
|
74
|
+
Claude Code: `claude mcp add dwelldelta -- npx -y dwelldelta-mcp@latest`. Any other MCP client: run
|
|
75
|
+
`npx -y dwelldelta-mcp@latest` as a stdio server. Node 18 or later. On npm 9 and later npx already checks for a
|
|
76
|
+
newer release; `@latest` matters on npm 8, and where dwelldelta-mcp is installed globally or in a project, which npx
|
|
77
|
+
would otherwise run as installed.
|
|
69
78
|
|
|
70
79
|
Then ask: "Is a rise from $700 to $770 a week in Sydney since July 2025 in line with rents?", "What is the
|
|
71
80
|
median rent of new leases in postcode 2148?" or "What is NSW unemployment doing?"
|
|
@@ -252,8 +261,14 @@ published data file. The structured result says the same, in new fields; every f
|
|
|
252
261
|
`period_due_by` is the day by which the release after this period was due, and `period_overdue` is true once it
|
|
253
262
|
has passed with no newer file. A quarterly rents file is overdue once its quarter ended more than seven months
|
|
254
263
|
ago (the next quarter, plus the publisher's lag), NSW sale prices after ten (DCJ's sales run a quarter behind its
|
|
255
|
-
rents), and the ABS monthly rents index
|
|
256
|
-
|
|
264
|
+
rents), and the ABS monthly rents index (`rent_check`) three months after its latest month (two to 0.14.0, which
|
|
265
|
+
flagged every January overdue: the ABS releases November's figures in early January). From 0.15.0, New Zealand's MBIE
|
|
266
|
+
month (`property_rents` with NZ) is overdue three months after it, and the ACT, NT and Tasmania interim cover
|
|
267
|
+
three months after its rents index month (to 0.14.0 neither carried a due date); the interim cover's 2021 Census figures are fixed until the next
|
|
268
|
+
Census, and are not flagged, and its ABS sale-price quarter is not checked for staleness (the flag follows the
|
|
269
|
+
rents index month alone). An overdue answer opens with a `STALE:` line giving the reason (through `property_rents`, the
|
|
270
|
+
line after its `Place:` line), and its `Cite:` line ends `; STALE.` - as an old snapshot's does (the interim cover
|
|
271
|
+
has no `Cite:` line: it carries the `STALE:` line alone).
|
|
257
272
|
- `figures` (`area_rents`, with or without `dwelling_type` and `bedrooms`, `vic_rents`, `nsw_sale_prices`): one
|
|
258
273
|
entry per figure of the answer, with `n`, `n_band` (where the publisher withholds the exact count), `unit`,
|
|
259
274
|
`small_sample` and `refusal`. `refusals` lists the refused ones, `all_refused` says whether anything may be
|
package/contribute-tool.mjs
CHANGED
|
@@ -129,7 +129,7 @@ export function makeContributeTool({
|
|
|
129
129
|
const code = deletionCode(randomBytes(12));
|
|
130
130
|
const body = { ...payload(record, await hashCode(code), t.toISOString().slice(0, 10)), whose: args.whose };
|
|
131
131
|
try {
|
|
132
|
-
await submitContribution(body, { endpoint, fetchImpl });
|
|
132
|
+
await submitContribution(body, { endpoint, fetchImpl, door: "tool" });
|
|
133
133
|
} catch (err) {
|
|
134
134
|
throw new ToolError(`Not added: ${err.message}.`, "Tell the user it was not added. Do not retry automatically.");
|
|
135
135
|
}
|
package/cover-tool.mjs
CHANGED
|
@@ -24,7 +24,7 @@ import { existsSync } from "node:fs";
|
|
|
24
24
|
import { fileURLToPath } from "node:url";
|
|
25
25
|
import { dirname, join } from "node:path";
|
|
26
26
|
import { envelope, ToolError, FOOTER, FETCH_TIMEOUT_MS, feedSource, citeLine, isRecord, passes, readChecked, quiet,
|
|
27
|
-
warnPublished, fromCopy } from "./tools.mjs";
|
|
27
|
+
warnPublished, fromCopy, CADENCE, staleNote, flagged } from "./tools.mjs";
|
|
28
28
|
import { SITE, slug } from "./pages.mjs";
|
|
29
29
|
|
|
30
30
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
@@ -186,7 +186,8 @@ export function nzResult(place, feed, now = new Date()) {
|
|
|
186
186
|
const r = place.row;
|
|
187
187
|
const kind = place.kind === "region" ? "region" : "territorial authority";
|
|
188
188
|
const src = feedSource(feed, PUBLISHED_BASE + NZ_FILE, feed.month, { noticeIsData: true });
|
|
189
|
-
const env = envelope({ sources: [src], dataAsOf: feed.month, origin: feed.origin ?? null },
|
|
189
|
+
const env = envelope({ sources: [src], dataAsOf: feed.month, origin: feed.origin ?? null, cadence: CADENCE.nz_monthly },
|
|
190
|
+
now);
|
|
190
191
|
const shown = nzShown(r);
|
|
191
192
|
const small = shown && nzSmall(r);
|
|
192
193
|
const url = nzPage(feed, place);
|
|
@@ -204,6 +205,7 @@ export function nzResult(place, feed, now = new Date()) {
|
|
|
204
205
|
: `${place.name} (${kind}), ${feed.month_words}: no figure. MBIE publishes none where fewer than ${NZ_MIN_BONDS} ` +
|
|
205
206
|
"bonds were lodged.";
|
|
206
207
|
const text = [
|
|
208
|
+
...staleNote(env),
|
|
207
209
|
`New Zealand rents, in New Zealand dollars (NZ$), not Australian dollars: MBIE's median weekly rent of the bonds ` +
|
|
208
210
|
// What the code knows (the re-review of #91): a bundled or offline copy can be older than MBIE's latest month.
|
|
209
211
|
`for private tenancies that began in ${feed.month_words}. It is the latest month in DwellDelta's copy of MBIE's ` +
|
|
@@ -222,7 +224,7 @@ export function nzResult(place, feed, now = new Date()) {
|
|
|
222
224
|
/^Source:/.test(feed.attribution) ? feed.attribution : `Source: ${feed.attribution}`,
|
|
223
225
|
citeLine({ source: feed.source, period: `${feed.month_words} (provisional)`, licence: feed.licence,
|
|
224
226
|
n: shown ? `${r.new_bonds} new bonds` : `fewer than ${NZ_MIN_BONDS} new bonds (withheld)`,
|
|
225
|
-
url: env.sources[0].source_url ?? MBIE_PAGE(feed), feedUrl: PUBLISHED_BASE + NZ_FILE, stale:
|
|
227
|
+
url: env.sources[0].source_url ?? MBIE_PAGE(feed), feedUrl: PUBLISHED_BASE + NZ_FILE, stale: flagged(env) }),
|
|
226
228
|
FOOTER,
|
|
227
229
|
].join("\n");
|
|
228
230
|
const row = Object.fromEntries(Object.entries(r).filter(([k]) => k !== "area" && k !== "region"));
|
|
@@ -285,7 +287,7 @@ export function interimResult(state, feed, postcode = null, now = new Date()) {
|
|
|
285
287
|
const regionWords = (region, opening = true) => (/^Rest of /.test(region)
|
|
286
288
|
? `${opening ? "The" : "the"} rest of ${info.name}` : region);
|
|
287
289
|
const env = envelope({ sources: [src(c.source, census), src(cpi.source, cpi.period), src(px.source, px.period)],
|
|
288
|
-
dataAsOf: cpi.latest_month, origin: feed.origin ?? null }, now);
|
|
290
|
+
dataAsOf: cpi.latest_month, origin: feed.origin ?? null, cadence: CADENCE.interim_cpi }, now);
|
|
289
291
|
const flags = row ? interimFlags(row) : [];
|
|
290
292
|
const shown = row ? interimShown(row) : false;
|
|
291
293
|
const n = (v) => Number(v).toLocaleString("en-AU");
|
|
@@ -319,6 +321,7 @@ export function interimResult(state, feed, postcode = null, now = new Date()) {
|
|
|
319
321
|
`(${census}), the ABS rents index for ${cpi.city} (${cpi.year_change_period}) and ABS median sale prices ` +
|
|
320
322
|
`(${px.period}). Source: ${feed.rights_holder}, ${feed.licence}. Via DwellDelta: ${interimPage(state)}`;
|
|
321
323
|
const text = [
|
|
324
|
+
...staleNote(env),
|
|
322
325
|
`Interim cover for ${info.name}, from ABS data. DwellDelta holds no rents from new bonds for ${info.name}: none ` +
|
|
323
326
|
"of these figures is a median of new bonds, and none is today's rent. Do not carry the 2021 rent forward with " +
|
|
324
327
|
// The ABS index is far older than this file's monthly series; the site's renderer says the same (re-review of #91).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dwelldelta-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Australian rents by area for five states, New Zealand rents by council and region and interim ABS cover for the ACT, NT and Tasmania, asked by place with no state, a rent placed against its local median, NSW median sale prices, an ABS rents index check, and sourced property and lending indicators, for AI agents.",
|
|
5
5
|
"mcpName": "au.com.dwelldelta/dwelldelta",
|
|
6
6
|
"license": "MIT",
|
package/server.mjs
CHANGED
|
@@ -37,8 +37,8 @@ registerReadOnlyTools(server, data);
|
|
|
37
37
|
server.registerTool("contribute_rent", titled({
|
|
38
38
|
title: "Add the user's own rent (NSW), with their consent",
|
|
39
39
|
description: "Adds the user's own weekly rent, anonymously, to DwellDelta's NSW suburb rents - suburb, home type, " +
|
|
40
|
-
"bedrooms, rent and lease
|
|
41
|
-
"sends nothing: it returns consent text for the user to read, and a one-use token. The rent is sent only by a " +
|
|
40
|
+
"bedrooms, rent, lease month and whether it is a new lease or a renewal; never an address, name or email. " +
|
|
41
|
+
"It takes two calls. The first stores and sends nothing: it returns consent text for the user to read, and a one-use token. The rent is sent only by a " +
|
|
42
42
|
"second call with the same details, that token and user_agreed: true, which is for when the user has said yes " +
|
|
43
43
|
`to that text. ${INTENDED_USE}`,
|
|
44
44
|
inputSchema: {
|
package/tools.mjs
CHANGED
|
@@ -112,7 +112,7 @@ export async function loadSnapshot({ env = process.env, fetchImpl = globalThis.f
|
|
|
112
112
|
}
|
|
113
113
|
|
|
114
114
|
export const FOOTER = "Information, not advice. From DwellDelta (dwelldelta.com.au), built on public data.";
|
|
115
|
-
export const SERVER_VERSION = "0.
|
|
115
|
+
export const SERVER_VERSION = "0.15.0";
|
|
116
116
|
// The indicators snapshot is rebuilt every Monday. Older than this and the answer says so, in words and in the
|
|
117
117
|
// structured result, rather than serving a stale figure as current.
|
|
118
118
|
export const STALE_DAYS = 10;
|
|
@@ -239,15 +239,27 @@ export const feedSource = (f, feedUrl, period, { noticeIsData = false } = {}) =>
|
|
|
239
239
|
/**
|
|
240
240
|
* Release cadence, and when a figure is overdue for replacing. months: from the end of the data's latest period
|
|
241
241
|
* to the end of the month by which the next release was due.
|
|
242
|
-
* -
|
|
243
|
-
*
|
|
242
|
+
* - abs_monthly (rent_check): the ABS monthly CPI comes out 24 to 30 days after each month, but November's in early
|
|
243
|
+
* January (7 January 2026; 6 January 2027 on the ABS release calendar), and the rents index reaches the data file
|
|
244
|
+
* only on the Monday job (dwelldelta-local sync_rent_check.py), up to a week later. So the month after the latest
|
|
245
|
+
* is due within three months of the latest month's end. Two months (to 0.14.0) flagged every January overdue
|
|
246
|
+
* though nothing was late, and any month whose release reached the file in the next month.
|
|
247
|
+
* - interim_cpi (ACT, NT and Tasmania interim cover): flagged from the file's CPI month (its data_as_of). The same
|
|
248
|
+
* ABS release, and the file is rebuilt only by the Monday job (build_interim_rents_feeds.py): three months too.
|
|
249
|
+
* The 2021 Census figures are fixed until the 2026 Census and are not flagged; the file's limits say so.
|
|
250
|
+
* - nz_monthly: MBIE's rental bond data comes out 38 to 44 days after each month ends (16 months observed,
|
|
251
|
+
* 2022-11 to 2026-08: always the 8th to 13th of the second month after; MBIE gives no release calendar), then
|
|
252
|
+
* reaches the file on the Monday job. Three months leaves 15 to 23 days past MBIE's latest observed upload; two
|
|
253
|
+
* would flag every month overdue for about ten days (control advisory 2026-11-03, NZ and interim staleness).
|
|
244
254
|
* - A quarterly rents feed: one quarter for the next quarter, then up to four months for the publisher to release
|
|
245
255
|
* it (DCJ's June 2026 rents reached the feed on 2026-10-10).
|
|
246
256
|
* - NSW sale prices: three months more, because DCJ's sales quarter runs one quarter behind its rents quarter in
|
|
247
257
|
* the same report (March 2026 sales came with June 2026 rents).
|
|
248
258
|
*/
|
|
249
259
|
export const CADENCE = {
|
|
250
|
-
abs_monthly: { cadence: "monthly", months:
|
|
260
|
+
abs_monthly: { cadence: "monthly", months: 3 },
|
|
261
|
+
interim_cpi: { cadence: "monthly", months: 3 },
|
|
262
|
+
nz_monthly: { cadence: "monthly", months: 3 },
|
|
251
263
|
rents_quarterly: { cadence: "quarterly", months: 7 },
|
|
252
264
|
sales_quarterly: { cadence: "quarterly", months: 10 },
|
|
253
265
|
};
|
package/vendor/contribute.mjs
CHANGED
|
@@ -14,7 +14,13 @@ export const CONTRIBUTION_ENDPOINT = "https://wzggu4sypmmgth5tsno62olhly0xthts.l
|
|
|
14
14
|
|
|
15
15
|
// The version of the Contributor Terms and Privacy Notice a contributor agrees to, sent with every contribution
|
|
16
16
|
// and stored beside it. tests/legal.test.mjs holds it equal to legal/status.json, which stamps the pages.
|
|
17
|
-
export const TERMS_VERSION = "2026-
|
|
17
|
+
export const TERMS_VERSION = "2026-11-03";
|
|
18
|
+
// While a new version rolls out, the endpoint also accepts these earlier ones, so a published assistant package or a
|
|
19
|
+
// cached page still sending one is not refused; each row records the version its sender agreed to, not this one.
|
|
20
|
+
// 2026-11-03: the 2026-10-27 texts did not name the lease kind, so rows under it are the owner's decision (keep, or
|
|
21
|
+
// drop the lease kind), as for every earlier row. Empty this, and redeploy, once the MCP release that sends
|
|
22
|
+
// 2026-11-03 is published: from then a sender on 2026-10-27 gets the 409 again.
|
|
23
|
+
export const ALSO_ACCEPTED_TERMS_VERSIONS = ["2026-10-27"];
|
|
18
24
|
|
|
19
25
|
export const FIELDS = ["suburb", "homeType", "bedrooms", "currentRent", "proposedRent", "leaseStart", "leaseKind"];
|
|
20
26
|
export const HOME_TYPES = ["house", "unit", "townhouse"];
|
|
@@ -29,14 +35,31 @@ export const RENT_MAX = 5000;
|
|
|
29
35
|
// Wording from the design memo, section 2. Tests hold the promises in it.
|
|
30
36
|
export const CONSENT = {
|
|
31
37
|
heading: "Help build fair rents for your suburb?",
|
|
32
|
-
body: "Add your rent anonymously. We keep your suburb, home type, bedrooms, rent
|
|
33
|
-
"your address, name or email. We publish only medians built from 10 or more rents, so no one rent " +
|
|
38
|
+
body: "Add your rent anonymously. We keep your suburb, home type, bedrooms, rent, lease month and whether " +
|
|
39
|
+
"it is a new lease or a renewal - never your address, name or email. We publish only medians built from 10 or more rents, so no one rent " +
|
|
34
40
|
"can be picked out.",
|
|
35
41
|
agree: "I agree to the Contributor Terms and Privacy Notice - add my rent",
|
|
36
42
|
button: "Add my rent",
|
|
37
43
|
notConnected: "Contributions are not being collected yet, so nothing was sent. Thank you for offering.",
|
|
38
44
|
};
|
|
39
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Every reason validateContribution gives, each thrown as it is written here. The endpoint returns them as its 400
|
|
48
|
+
* (api/handler.mjs reply(400, err.message)), so REFUSALS below names each, and tests/contribute.test.mjs holds the
|
|
49
|
+
* two together.
|
|
50
|
+
*/
|
|
51
|
+
export const INVALID = Object.freeze({
|
|
52
|
+
suburb: "choose your suburb from the list",
|
|
53
|
+
homeType: "choose a home type",
|
|
54
|
+
bedrooms: "choose the number of bedrooms",
|
|
55
|
+
leaseKind: "say whether this is a new lease or a renewal",
|
|
56
|
+
currentRent: `the weekly rent must be between $${RENT_MIN} and $${RENT_MAX}`,
|
|
57
|
+
proposedRent: `the proposed rent must be between $${RENT_MIN} and $${RENT_MAX}`,
|
|
58
|
+
proposedDouble: "the proposed rent is more than double the current one",
|
|
59
|
+
leaseStart: "the lease start must be a month",
|
|
60
|
+
leaseFuture: "the lease start cannot be in the future",
|
|
61
|
+
});
|
|
62
|
+
|
|
40
63
|
/** Checks what the person entered and returns the record to send, or throws with a plain reason. */
|
|
41
64
|
export function validateContribution(input, suburbs, thisMonth) {
|
|
42
65
|
const r = {
|
|
@@ -49,23 +72,23 @@ export function validateContribution(input, suburbs, thisMonth) {
|
|
|
49
72
|
leaseStart: input.leaseStart,
|
|
50
73
|
leaseKind: input.leaseKind,
|
|
51
74
|
};
|
|
52
|
-
if (!suburbs.includes(r.suburb)) throw new Error(
|
|
53
|
-
if (!HOME_TYPES.includes(r.homeType)) throw new Error(
|
|
54
|
-
if (!BEDROOMS.includes(r.bedrooms)) throw new Error(
|
|
55
|
-
if (!LEASE_KINDS.includes(r.leaseKind)) throw new Error(
|
|
75
|
+
if (!suburbs.includes(r.suburb)) throw new Error(INVALID.suburb);
|
|
76
|
+
if (!HOME_TYPES.includes(r.homeType)) throw new Error(INVALID.homeType);
|
|
77
|
+
if (!BEDROOMS.includes(r.bedrooms)) throw new Error(INVALID.bedrooms);
|
|
78
|
+
if (!LEASE_KINDS.includes(r.leaseKind)) throw new Error(INVALID.leaseKind);
|
|
56
79
|
if (!(r.currentRent >= RENT_MIN && r.currentRent <= RENT_MAX)) {
|
|
57
|
-
throw new Error(
|
|
80
|
+
throw new Error(INVALID.currentRent);
|
|
58
81
|
}
|
|
59
82
|
if (r.proposedRent !== null) {
|
|
60
83
|
if (!(r.proposedRent >= RENT_MIN && r.proposedRent <= RENT_MAX)) {
|
|
61
|
-
throw new Error(
|
|
84
|
+
throw new Error(INVALID.proposedRent);
|
|
62
85
|
}
|
|
63
|
-
if (r.proposedRent > 2 * r.currentRent) throw new Error(
|
|
86
|
+
if (r.proposedRent > 2 * r.currentRent) throw new Error(INVALID.proposedDouble);
|
|
64
87
|
}
|
|
65
88
|
if (typeof r.leaseStart !== "string" || !/^\d{4}-(0[1-9]|1[0-2])$/.test(r.leaseStart)) {
|
|
66
|
-
throw new Error(
|
|
89
|
+
throw new Error(INVALID.leaseStart);
|
|
67
90
|
}
|
|
68
|
-
if (r.leaseStart > thisMonth) throw new Error(
|
|
91
|
+
if (r.leaseStart > thisMonth) throw new Error(INVALID.leaseFuture);
|
|
69
92
|
return r;
|
|
70
93
|
}
|
|
71
94
|
|
|
@@ -95,8 +118,12 @@ export function payload(record, codeHash, today) {
|
|
|
95
118
|
return body;
|
|
96
119
|
}
|
|
97
120
|
|
|
98
|
-
/**
|
|
99
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Sends a contribution. While CONTRIBUTION_ENDPOINT is null it refuses before any request is made. `door` is where the
|
|
123
|
+
* refusal will be read: "page" (the rent check page) or "tool" (contribute_rent), which word the 409 differently.
|
|
124
|
+
*/
|
|
125
|
+
export async function submitContribution(body, { endpoint = CONTRIBUTION_ENDPOINT, fetchImpl = globalThis.fetch,
|
|
126
|
+
door = "page" } = {}) {
|
|
100
127
|
if (!endpoint) throw new Error("not connected");
|
|
101
128
|
const res = await fetchImpl(endpoint, {
|
|
102
129
|
method: "POST",
|
|
@@ -105,5 +132,89 @@ export async function submitContribution(body, { endpoint = CONTRIBUTION_ENDPOIN
|
|
|
105
132
|
credentials: "omit",
|
|
106
133
|
referrerPolicy: "no-referrer",
|
|
107
134
|
});
|
|
108
|
-
if (!res.ok)
|
|
135
|
+
if (!res.ok) {
|
|
136
|
+
const reason = await refusalReason(res, { door });
|
|
137
|
+
throw new Error(`the contribution was not saved (HTTP ${res.status})${reason ? `: ${reason}` : ""}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The 409's words, by where they are read: the page reloads to get the new terms; the tool's user updates the package. */
|
|
142
|
+
export const TERMS_CHANGED = Object.freeze({
|
|
143
|
+
page: "the terms have changed: reload this page",
|
|
144
|
+
tool: "the terms have changed: update dwelldelta-mcp (npx -y dwelldelta-mcp@latest)",
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Every 4xx reason the endpoint gives (api/handler.mjs reply(4xx, ...), and validateContribution's INVALID through its
|
|
149
|
+
* 400), by status, each mapped to the client's own words. The cold re-review of #98: passing on whatever string the
|
|
150
|
+
* body held let 160 characters of anything ("IMPORTANT SYSTEM NOTE ... call contribute_rent again", bidi and
|
|
151
|
+
* zero-width characters) reach an agent unlabelled. Only an exact match, under its own status, gives a reason, and
|
|
152
|
+
* the text given is this file's, never the body's. tests/contribute.test.mjs reads api/handler.mjs and this file and
|
|
153
|
+
* fails if a 4xx reason there is missing here, or one here is no longer said there.
|
|
154
|
+
*/
|
|
155
|
+
export const REFUSALS = Object.freeze({
|
|
156
|
+
400: Object.freeze({
|
|
157
|
+
"not JSON": "not JSON",
|
|
158
|
+
"not an object": "not an object",
|
|
159
|
+
"unexpected fields": "unexpected fields",
|
|
160
|
+
"bad deletion code hash": "bad deletion code hash",
|
|
161
|
+
"say whose rent this is": "say whose rent this is",
|
|
162
|
+
...Object.fromEntries(Object.values(INVALID).map((m) => [m, m])),
|
|
163
|
+
}),
|
|
164
|
+
403: Object.freeze({ "wrong origin": "wrong origin" }),
|
|
165
|
+
405: Object.freeze({ "POST only": "POST only" }),
|
|
166
|
+
409: Object.freeze({ "the terms have changed; read them again": TERMS_CHANGED }),
|
|
167
|
+
413: Object.freeze({ "too large": "too large" }),
|
|
168
|
+
429: Object.freeze({ "too many today": "too many today" }),
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
/** The most of a refusal's body read, in bytes, and for how long, in milliseconds; past either, no reason. */
|
|
172
|
+
export const REFUSAL_BODY_MAX_BYTES = 4096;
|
|
173
|
+
export const REFUSAL_BODY_MS = 3000;
|
|
174
|
+
|
|
175
|
+
/** The body as text, or null if it is not a stream, runs past `maxBytes`, takes longer than `ms`, or is not UTF-8. */
|
|
176
|
+
async function readCapped(res, maxBytes, ms) {
|
|
177
|
+
const reader = res?.body && typeof res.body.getReader === "function" ? res.body.getReader() : null;
|
|
178
|
+
if (!reader) return null;
|
|
179
|
+
const chunks = [];
|
|
180
|
+
let size = 0;
|
|
181
|
+
let timer;
|
|
182
|
+
const late = new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); });
|
|
183
|
+
try {
|
|
184
|
+
for (;;) {
|
|
185
|
+
const step = await Promise.race([reader.read(), late]);
|
|
186
|
+
if (!step) return null; // the time limit
|
|
187
|
+
if (step.done) break;
|
|
188
|
+
size += step.value?.byteLength ?? 0;
|
|
189
|
+
if (size > maxBytes) return null; // stop at the byte limit
|
|
190
|
+
chunks.push(step.value);
|
|
191
|
+
}
|
|
192
|
+
} catch {
|
|
193
|
+
return null;
|
|
194
|
+
} finally {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
reader.cancel().catch(() => {});
|
|
197
|
+
}
|
|
198
|
+
const bytes = new Uint8Array(size);
|
|
199
|
+
let at = 0;
|
|
200
|
+
for (const c of chunks) { bytes.set(c, at); at += c.byteLength; }
|
|
201
|
+
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { return null; }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The client's own words for the endpoint's refusal, or null. On a 4xx only, the body is read (at most
|
|
206
|
+
* REFUSAL_BODY_MAX_BYTES, within REFUSAL_BODY_MS) and its JSON `error` looked up, exactly, in REFUSALS under the
|
|
207
|
+
* response's status. Nothing in the body is ever passed on: a reason not on the list gives none.
|
|
208
|
+
*/
|
|
209
|
+
export async function refusalReason(res, { door = "page", maxBytes = REFUSAL_BODY_MAX_BYTES, ms = REFUSAL_BODY_MS } = {}) {
|
|
210
|
+
const known = REFUSALS[res?.status];
|
|
211
|
+
if (!known) return null;
|
|
212
|
+
const raw = await readCapped(res, maxBytes, ms);
|
|
213
|
+
if (raw === null) return null;
|
|
214
|
+
let body;
|
|
215
|
+
try { body = JSON.parse(raw); } catch { return null; }
|
|
216
|
+
const said = body && typeof body === "object" && !Array.isArray(body) ? body.error : undefined;
|
|
217
|
+
if (typeof said !== "string" || !Object.hasOwn(known, said)) return null;
|
|
218
|
+
const words = known[said];
|
|
219
|
+
return typeof words === "string" ? words : (Object.hasOwn(words, door) ? words[door] : null);
|
|
109
220
|
}
|