@chrischall/hellofresh-mcp 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,11 +4,11 @@
4
4
  // and delivery records carry the customer's name, email, addresses and
5
5
  // payment token, none of which is ever returned.
6
6
  import { z } from 'zod';
7
- import { minifiedResult, resolveView, todayIso, toolAnnotations } from '@chrischall/mcp-utils';
7
+ import { mapWithConcurrency, minifiedResult, resolveView, todayIso, toolAnnotations } from '@chrischall/mcp-utils';
8
8
  import { parseSku, projectDelivery, projectSubscription, } from '../normalize.js';
9
9
  import { isoWeekOf, shiftWeek } from '../weeks.js';
10
10
  import { LOOKUP, foodMeta } from './hints.js';
11
- import { HF_VIEWS, attempt, boxNumbering, boxNumbers, briefLine, byWeek, compactEstimate, compactSelection, dateOf, estimateFor, hfView, loadAccount, nextBoxNumberParam, readMenu, readPicks, weekParam, } from './shared.js';
11
+ import { HF_VIEWS, PRICE_CONCURRENCY, attempt, boxNumbering, boxNumbers, calculatorGate, briefLine, byWeek, compactSelection, dateOf, estimateFor, estimatedPrice, hellofreshPrice, hfView, loadAccount, nextBoxNumberParam, premiumCentsOf, readMenu, readPicks, weekParam, } from './shared.js';
12
12
  const readOnly = (title) => toolAnnotations({ title, readOnly: true, idempotent: true, openWorld: true });
13
13
  // ---- projections for the compact rung --------------------------------------------
14
14
  function fullVoucher(v) {
@@ -104,10 +104,32 @@ export function registerReadTools(server, deps) {
104
104
  subscription: { ...projected, customerPlanId: subscription.customerPlanId, voucher: fullVoucher(subscription.voucherInfo) },
105
105
  });
106
106
  });
107
+ /** HelloFresh's price for a running week's box (its picks' premiums added), else the labelled local estimate. */
108
+ async function priceWeek(account, delivery, week, selection, full, fallbackBoxNumber, gate) {
109
+ const real = await gate(() => hellofreshPrice(client, account, {
110
+ week,
111
+ sku: delivery.sku,
112
+ people: delivery.servings,
113
+ deliveryOption: delivery.deliveryOption,
114
+ deliveryDate: delivery.deliveryDate,
115
+ recipeIndexes: (selection ?? []).map((m) => m.index),
116
+ premiumCents: selection ? premiumCentsOf(selection) : undefined,
117
+ }, now()));
118
+ if (real.ok)
119
+ return real.value;
120
+ const estimate = estimateFor(delivery, selection ?? [], account, await fallbackBoxNumber());
121
+ if (!selection) {
122
+ const note = 'The menu could not be read, so premium upcharges are not included.';
123
+ estimate.warning = estimate.warning ? `${estimate.warning} ${note}` : note;
124
+ }
125
+ return estimatedPrice(estimate, real.reason, full);
126
+ }
107
127
  server.registerTool('hf_list_deliveries', {
108
128
  description: 'List upcoming HelloFresh deliveries (about the next 7 weeks): each week’s delivery date, meal-pick cutoff, ' +
109
- 'status (running, skipped, delivered), box size and an estimated box total with the voucher discount. ' +
110
- 'Answers "what HelloFresh boxes are coming?" — view "brief" gives one line per week.',
129
+ 'status (running, skipped, delivered), box size and, for running weeks, the box price — HelloFresh’s own ' +
130
+ 'checkout total (voucher, shipping and tax applied) plus the picked meals’ premium upcharge, or a labelled ' +
131
+ 'local estimate when that cannot be read. Answers "what HelloFresh boxes are coming?" — view "brief" gives ' +
132
+ 'one line per week (no prices).',
111
133
  annotations: readOnly('HelloFresh: list deliveries'),
112
134
  _meta: foodMeta('whats-on', {
113
135
  canonical: true,
@@ -117,9 +139,9 @@ export function registerReadTools(server, deps) {
117
139
  view: z
118
140
  .enum(['brief', 'compact', 'full'])
119
141
  .optional()
120
- .describe('"compact" (default): week, dates, status, box size and a short estimate. "brief": one line per week, ' +
121
- '`2026-W49 — 2026-11-30 — running, 2×6, cutoff 11-25`. "full": every allowlisted delivery field ' +
122
- '(allowed actions, alternative delivery-day slots) and the whole estimate.'),
142
+ .describe('"compact" (default): week, dates, status, box size and the price. "brief": one line per week, ' +
143
+ '`2026-W49 — 2026-11-30 — running, 2×6, cutoff 11-25`, no prices (no per-week calls). "full": every ' +
144
+ 'allowlisted delivery field (allowed actions, alternative delivery-day slots) and, for an estimate, every estimate field.'),
123
145
  next_box_number: nextBoxNumberParam,
124
146
  }),
125
147
  }, async ({ view, next_box_number }) => {
@@ -132,23 +154,36 @@ export function registerReadTools(server, deps) {
132
154
  const numbering = boxNumbering(account.subscription, next_box_number);
133
155
  const numbers = boxNumbers(deliveries, numbering.next);
134
156
  const full = view === 'full';
157
+ const running = deliveries.filter((d) => d.status === 'running' && !!d.week);
158
+ const gate = calculatorGate();
159
+ const priced = new Map(await mapWithConcurrency(running, PRICE_CONCURRENCY, async (d) => {
160
+ const menu = await attempt(() => readMenu(client, account, d, d.week));
161
+ const selection = menu.ok ? menu.value.selected : undefined;
162
+ const price = await priceWeek(account, d, d.week, selection, full, async () => numbers.get(d.week), gate);
163
+ return [d.week, price];
164
+ }));
165
+ const anyEstimate = [...priced.values()].some((p) => p.source === 'estimate');
135
166
  return minifiedResult({
136
167
  deliveries: deliveries.map((d) => {
137
- const boxNumber = numbers.get(d.week);
138
- const estimate = boxNumber !== undefined ? estimateFor(d, [], account, boxNumber) : undefined;
139
168
  const base = full ? d : compactDelivery(d);
140
- if (!estimate)
141
- return base;
142
- return { ...base, estimate: full ? estimate : compactEstimate(estimate) };
169
+ const price = d.week ? priced.get(d.week) : undefined;
170
+ return price ? { ...base, price } : base;
143
171
  }),
144
- estimateNote: 'Estimates (running weeks only) are product + fees + shipping minus the voucher, WITHOUT premium meal ' +
145
- `upcharges (hf_get_delivery adds those). ${numbering.note}`,
172
+ ...(priced.size > 0
173
+ ? {
174
+ priceNote: 'Every price amount is in US dollars, for both sources. price.source "hellofresh" is HelloFresh’s own ' +
175
+ 'checkout price; "estimate" is a local fallback (product + fees + shipping − voucher) used when the ' +
176
+ 'calculator could not be read. In both, grandTotal leaves premium recipe upcharges out, premiumUpcharge ' +
177
+ `reports them and totalWithPremiums adds them.${anyEstimate ? ` ${numbering.note}` : ''}`,
178
+ }
179
+ : {}),
146
180
  });
147
181
  });
148
182
  server.registerTool('hf_get_delivery', {
149
183
  description: 'Read one HelloFresh delivery week: delivery date and slot, meal-pick cutoff, status, box size, the meals ' +
150
- 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, and an estimated ' +
151
- 'box total including premium upcharges and the voucher discount.',
184
+ 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, and the box price ' +
185
+ '— HelloFresh’s own checkout total plus the picked meals’ premium upcharge, or a labelled local estimate ' +
186
+ 'when that cannot be read.',
152
187
  annotations: readOnly('HelloFresh: get delivery'),
153
188
  _meta: LOOKUP,
154
189
  inputSchema: z.object({
@@ -159,34 +194,28 @@ export function registerReadTools(server, deps) {
159
194
  .min(1)
160
195
  .max(1000)
161
196
  .optional()
162
- .describe('This box’s number, counting every box ever delivered — overrides the number derived from next_box_number.'),
197
+ .describe('This box’s number, counting every box ever delivered — overrides the number derived from next_box_number. ' +
198
+ 'Only used by the local estimate (when HelloFresh’s price cannot be read).'),
163
199
  next_box_number: nextBoxNumberParam,
164
- view: hfView('compact keeps the essentials; full adds every allowlisted field (prices, slot handle, sub-status) and the whole estimate.'),
200
+ view: hfView('compact keeps the essentials; full adds every allowlisted field (prices, slot handle, sub-status) and, for an estimate, every estimate field.'),
165
201
  }),
166
202
  }, async ({ week, box_number, next_box_number, view }) => {
167
203
  const account = await loadAccount(client);
168
- const [rawDelivery, upcoming] = await Promise.all([
169
- client.getDelivery(account.subscriptionId, week),
170
- client.listDeliveries(),
171
- ]);
172
- const delivery = projectDelivery(rawDelivery);
173
- const running = delivery.status === 'running';
204
+ const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
174
205
  const menu = delivery.status === 'skipped' ? undefined : await attempt(() => readMenu(client, account, delivery, week));
175
- const selection = menu?.ok ? menu.value.selected.map(compactSelection) : undefined;
176
- let estimate;
206
+ const selected = menu?.ok ? menu.value.selected : undefined;
207
+ const full = resolveView(view, HF_VIEWS) === 'full';
177
208
  let boxNumberNote;
178
- if (running) {
209
+ // The upcoming list is read only when the estimate needs a derived box number.
210
+ const fallbackBoxNumber = async () => {
211
+ if (box_number !== undefined)
212
+ return box_number;
179
213
  const numbering = boxNumbering(account.subscription, next_box_number);
180
- if (box_number === undefined)
181
- boxNumberNote = numbering.note;
182
- const boxNumber = box_number ?? boxNumbers((upcoming.items ?? []).map(projectDelivery), numbering.next).get(week);
183
- estimate = estimateFor(delivery, selection ?? [], account, boxNumber);
184
- if (!selection) {
185
- const note = 'The menu could not be read, so premium upcharges are not included.';
186
- estimate.warning = estimate.warning ? `${estimate.warning} ${note}` : note;
187
- }
188
- }
189
- const full = resolveView(view, HF_VIEWS) === 'full';
214
+ boxNumberNote = numbering.note;
215
+ const upcoming = ((await client.listDeliveries()).items ?? []).map(projectDelivery);
216
+ return boxNumbers(upcoming, numbering.next).get(week);
217
+ };
218
+ const price = delivery.status === 'running' ? await priceWeek(account, delivery, week, selected, full, fallbackBoxNumber, calculatorGate()) : undefined;
190
219
  return minifiedResult({
191
220
  ...(full
192
221
  ? delivery
@@ -198,9 +227,9 @@ export function registerReadTools(server, deps) {
198
227
  allowedActions: delivery.allowedActions,
199
228
  oneOffDaySlots: delivery.oneOffDaySlots,
200
229
  }),
201
- ...(selection ? { selection } : {}),
230
+ ...(selected ? { selection: selected.map(compactSelection) } : {}),
202
231
  ...(menu && !menu.ok ? { selectionError: menu.reason } : {}),
203
- ...(estimate ? { estimate: full ? estimate : compactEstimate(estimate) } : {}),
232
+ ...(price ? { price } : {}),
204
233
  ...(boxNumberNote ? { boxNumberNote } : {}),
205
234
  });
206
235
  });
@@ -278,7 +307,8 @@ export function registerReadTools(server, deps) {
278
307
  server.registerTool('hf_recent_picks', {
279
308
  description: 'List the HelloFresh meals picked in recent weeks — the current week and the weeks_back weeks before it — ' +
280
309
  'to avoid repeating a recipe. Best effort: each week’s menu is read separately, and weeks that cannot be ' +
281
- 'read are listed with the reason.',
310
+ 'read are listed with the reason. Weeks before the subscription’s first delivery week had no box ' +
311
+ '(status no_box).',
282
312
  annotations: readOnly('HelloFresh: recent picks'),
283
313
  _meta: foodMeta('lookup', { aliases: ['recent hellofresh meals', 'what did we have'] }),
284
314
  inputSchema: z.object({
@@ -295,6 +325,7 @@ export function registerReadTools(server, deps) {
295
325
  const { weeks: read, recipeNames, unreadable } = await readPicks(client, account, weeks);
296
326
  return minifiedResult({
297
327
  throughWeek: through,
328
+ ...(read.some((w) => w.status === 'no_box') ? { firstDeliveryWeek: account.subscription.firstDeliveryWeek } : {}),
298
329
  weeks: read,
299
330
  recipeNames,
300
331
  ...(unreadable.length > 0 ? { unreadable } : {}),
@@ -1,9 +1,11 @@
1
1
  // Shared bits for the hf_ tools: the account context every call starts from
2
2
  // (the subscription and its plan id), the `week` / `view` parameters, the
3
- // box-number and estimate helpers, and the brief line.
3
+ // real-price (HelloFresh's calculator) and fallback-estimate helpers, the
4
+ // box-number helpers, and the brief line.
4
5
  import { z } from 'zod';
5
- import { McpToolError, messageOf, viewParam } from '@chrischall/mcp-utils';
6
- import { estimateBoxTotal, projectDelivery, projectMenu, } from '../normalize.js';
6
+ import { McpToolError, errorStatusOf, currentCallSignal, messageOf, viewParam } from '@chrischall/mcp-utils';
7
+ import { estimateBoxTotal, projectDelivery, projectFavorites, projectMenu, projectRatings, } from '../normalize.js';
8
+ import { HelloFreshBridgeError } from '../session.js';
7
9
  import { WEEK_PATTERN } from '../weeks.js';
8
10
  // ---- parameters -----------------------------------------------------------------
9
11
  export const HF_VIEWS = ['compact', 'full'];
@@ -57,28 +59,57 @@ export async function customerPlanIdOf(client, account) {
57
59
  throw new McpToolError('HelloFresh returned no customer plan for this subscription.');
58
60
  return plan.id;
59
61
  }
60
- /** The week's menu for the delivery's box size. */
61
- export async function readMenu(client, account, delivery, week) {
62
+ /** The week's RAW menu for the delivery's box size (recipe ids included). */
63
+ export async function readRawMenu(client, account, delivery, week) {
62
64
  if (!delivery.sku || !delivery.servings) {
63
65
  throw new McpToolError(`HelloFresh returned no box size for ${week}, so its menu cannot be read.`);
64
66
  }
65
67
  const customerPlanId = await customerPlanIdOf(client, account);
66
- const menu = await client.getDeliveryMenu({
67
- subscriptionId: account.subscriptionId,
68
- week,
69
- servings: delivery.servings,
70
- sku: delivery.sku,
71
- customerPlanId,
72
- });
73
- return projectMenu(menu);
68
+ try {
69
+ return await client.getDeliveryMenu({
70
+ subscriptionId: account.subscriptionId,
71
+ week,
72
+ servings: delivery.servings,
73
+ sku: delivery.sku,
74
+ customerPlanId,
75
+ });
76
+ }
77
+ catch (err) {
78
+ // HelloFresh answers 404 for a week whose menu it has not published yet (menus appear a few weeks ahead).
79
+ if (errorStatusOf(err) === 404)
80
+ throw new MenuNotPublishedError(week, err);
81
+ throw err;
82
+ }
83
+ }
84
+ /** HelloFresh has no menu for the week yet (404 on the delivery menu). */
85
+ export class MenuNotPublishedError extends McpToolError {
86
+ week;
87
+ constructor(week, cause) {
88
+ super(`The ${week} menu is not published yet: HelloFresh releases each week's menu a few weeks ahead.`, {
89
+ hint: 'Try again closer to the week (hf_list_deliveries shows the cutoff), or plan an earlier week now.',
90
+ status: 404,
91
+ cause,
92
+ });
93
+ this.week = week;
94
+ this.name = 'MenuNotPublishedError';
95
+ }
96
+ }
97
+ /** The week's menu for the delivery's box size. */
98
+ export async function readMenu(client, account, delivery, week) {
99
+ return projectMenu(await readRawMenu(client, account, delivery, week));
74
100
  }
75
101
  /**
76
- * The picks of each week, best effort: a skipped week has none (and reads no
77
- * menu); a week whose delivery or menu cannot be read is listed in
78
- * `unreadable` with the reason. `recipeNames` are the distinct picked names.
102
+ * The picks of each week, best effort: a week before the subscription's
103
+ * `firstDeliveryWeek` had no box (`no_box`, nothing is read); a skipped week
104
+ * has none (and reads no menu); a week whose delivery or menu cannot be read
105
+ * is listed in `unreadable` with the reason. `recipeNames` are the distinct
106
+ * picked names.
79
107
  */
80
108
  export async function readPicks(client, account, weeks) {
81
- const results = await Promise.all(weeks.map(async (week) => {
109
+ const first = account.subscription.firstDeliveryWeek;
110
+ // ISO weeks (YYYY-Www) order as strings.
111
+ const hadNoBox = (week) => !!first && week < first;
112
+ const results = await Promise.all(weeks.filter((week) => !hadNoBox(week)).map(async (week) => {
82
113
  const read = await attempt(async () => {
83
114
  const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
84
115
  if (delivery.status === 'skipped')
@@ -89,12 +120,104 @@ export async function readPicks(client, account, weeks) {
89
120
  return { week, read };
90
121
  }));
91
122
  const read = results.flatMap(({ week, read: r }) => r.ok ? [{ week, status: r.value.delivery.status, deliveryDate: dateOf(r.value.delivery.deliveryDate), picks: r.value.picks }] : []);
123
+ const noBox = weeks.filter(hadNoBox).map((week) => ({ week, status: 'no_box', picks: [] }));
92
124
  return {
93
- weeks: read,
125
+ weeks: [...noBox, ...read].sort(byWeek),
94
126
  recipeNames: [...new Set(read.flatMap((w) => w.picks.map((p) => p.name)).filter((n) => !!n))],
95
127
  unreadable: results.flatMap(({ week, read: r }) => (r.ok ? [] : [{ week, reason: r.reason }])),
96
128
  };
97
129
  }
130
+ // ---- the real price (POST /gw/calculate) ------------------------------------------
131
+ /** How many weeks hf_list_deliveries prices at once (each is a menu read + an in-tab calculator call). */
132
+ export const PRICE_CONCURRENCY = 3;
133
+ export const PREMIUM_NOTE = 'HelloFresh’s own price calculator (its checkout price) leaves premium recipe charges out: premiumUpcharge is ' +
134
+ 'the meals’ upcharge for the box, reported separately and added in totalWithPremiums.';
135
+ export const PREMIUM_UNKNOWN_NOTE = 'HelloFresh’s own price calculator leaves premium recipe charges out, and the menu could not be read, so any ' +
136
+ 'premium upcharge is unknown and NOT included.';
137
+ const roundCents = (dollars) => Math.round(dollars * 100) / 100;
138
+ /** Σ premium upcharge of a selection, in cents. */
139
+ export const premiumCentsOf = (meals) => meals.reduce((sum, m) => sum + m.premiumBoxCents * (m.quantity ?? 1), 0);
140
+ /**
141
+ * The box's price from HelloFresh's own calculator (an in-tab fetch through the
142
+ * bridge). Throws when an input is missing or the calculator fails: callers
143
+ * fall back to the local estimate (`estimatedPrice`) with the reason.
144
+ */
145
+ export async function hellofreshPrice(client, account, input, now) {
146
+ const s = account.subscription;
147
+ const deliveryOption = input.deliveryOption ?? s.deliveryOption?.handle;
148
+ const needed = {
149
+ 'customer id': s.customer?.id,
150
+ postcode: s.shippingAddress?.postcode,
151
+ 'box SKU': input.sku,
152
+ servings: input.people,
153
+ 'delivery option': deliveryOption,
154
+ };
155
+ const missing = Object.keys(needed).filter((k) => needed[k] === undefined || needed[k] === '');
156
+ if (missing.length > 0)
157
+ throw new McpToolError(`HelloFresh returned no ${missing.join(', ')}, which its price calculator needs.`);
158
+ const price = await client.calculatePrice({
159
+ customerId: s.customer.id,
160
+ subscriptionId: account.subscriptionId,
161
+ couponCode: s.couponCode ?? '',
162
+ postcode: s.shippingAddress.postcode,
163
+ customerPlanId: await customerPlanIdOf(client, account),
164
+ sku: input.sku,
165
+ week: input.week,
166
+ deliveryOption: deliveryOption,
167
+ recipeIndexes: input.recipeIndexes,
168
+ isFirstOrder: input.week === s.firstDeliveryWeek,
169
+ // An upcoming box (no date: it is on the upcoming list, so assume so).
170
+ isFutureWeek: input.deliveryDate ? Date.parse(input.deliveryDate) > now : true,
171
+ boxSize: input.people,
172
+ });
173
+ if (input.premiumCents === undefined)
174
+ return { source: 'hellofresh', ...price, note: PREMIUM_UNKNOWN_NOTE };
175
+ const premiumUpcharge = input.premiumCents / 100;
176
+ return {
177
+ source: 'hellofresh',
178
+ ...price,
179
+ premiumUpcharge,
180
+ totalWithPremiums: roundCents(price.grandTotal + premiumUpcharge),
181
+ note: PREMIUM_NOTE,
182
+ };
183
+ }
184
+ /** The local estimate, labelled as the fallback it is, with why HelloFresh's price could not be used. */
185
+ export function estimatedPrice(estimate, reason, full) {
186
+ return {
187
+ source: 'estimate',
188
+ reason: `HelloFresh’s price calculator could not be used (${reason}), so this is a local estimate.`,
189
+ ...estimateInDollars(estimate, full),
190
+ };
191
+ }
192
+ // ---- favourites and ratings -------------------------------------------------------
193
+ export const RATING_SCALES = ['v2', 'v3'];
194
+ /** The user's ratings on each scale, best effort: an unreadable scale is named with the reason. */
195
+ export async function readRatings(client, scales = RATING_SCALES) {
196
+ const reads = await Promise.all(scales.map(async (scale) => ({ scale, read: await attempt(() => client.listRatings(scale)) })));
197
+ const ratings = [];
198
+ let skipped = 0;
199
+ const unreadable = [];
200
+ for (const { scale, read } of reads) {
201
+ if (!read.ok) {
202
+ unreadable.push({ source: `ratings ${scale}`, reason: read.reason });
203
+ continue;
204
+ }
205
+ const projected = projectRatings(read.value, scale);
206
+ ratings.push(...projected.ratings);
207
+ skipped += projected.skipped;
208
+ }
209
+ return { ratings, skipped, unreadable };
210
+ }
211
+ /** Favourites + ratings for the planner, best effort (neither is needed to plan). */
212
+ export async function readPersonal(client) {
213
+ const [favorites, rated] = await Promise.all([attempt(async () => projectFavorites(await client.listFavorites())), readRatings(client)]);
214
+ return {
215
+ ...(favorites.ok ? { favoriteRecipeIds: favorites.value.favorites.map((f) => f.recipeId) } : {}),
216
+ ratings: rated.ratings,
217
+ ratingsSkipped: rated.skipped,
218
+ unreadable: [...(favorites.ok ? [] : [{ source: 'favorites', reason: favorites.reason }]), ...rated.unreadable],
219
+ };
220
+ }
98
221
  // ---- estimates --------------------------------------------------------------------
99
222
  /** Box number per running week (in week order), starting at `next`; skipped weeks take no number. */
100
223
  export function boxNumbers(deliveries, next) {
@@ -137,13 +260,28 @@ export function estimateFor(delivery, selection, account, boxNumber) {
137
260
  }
138
261
  return { boxNumber, ...estimateBoxTotal(delivery, selection, account.subscription.voucherInfo, boxNumber) };
139
262
  }
140
- /** The few estimate fields a compact answer keeps. */
141
- export function compactEstimate(e) {
263
+ /** Cents → US dollars (2 decimals). */
264
+ const usd = (cents) => Math.round(cents) / 100;
265
+ /**
266
+ * The estimate as a `price` shows it: US dollars, named as HelloFresh's own
267
+ * price is — so a caller reads ONE unit whatever the source. `subTotal` is
268
+ * product + fees + shipping before the voucher, `grandTotal` that less the
269
+ * discount (premiums excluded, as HelloFresh's calculator), `totalWithPremiums`
270
+ * adds the meals' `premiumUpcharge`. Compact keeps the totals; full adds the
271
+ * parts and the voucher rule applied.
272
+ */
273
+ export function estimateInDollars(e, full) {
274
+ const beforeDiscount = e.productCents + e.feeCents + e.shippingCents;
142
275
  return {
143
276
  ...(e.boxNumber !== undefined ? { boxNumber: e.boxNumber } : {}),
144
- subtotalCents: e.subtotalCents,
145
- discountCents: e.discountCents,
146
- totalCents: e.totalCents,
277
+ currency: 'USD',
278
+ ...(full ? { product: usd(e.productCents), fees: usd(e.feeCents), shipping: usd(e.shippingCents) } : {}),
279
+ subTotal: usd(beforeDiscount),
280
+ discount: usd(e.discountCents),
281
+ grandTotal: usd(beforeDiscount - e.discountCents),
282
+ premiumUpcharge: usd(e.premiumCents),
283
+ totalWithPremiums: usd(e.totalCents),
284
+ ...(full && e.voucher ? { voucher: e.voucher } : {}),
147
285
  ...(e.warning ? { warning: e.warning } : {}),
148
286
  };
149
287
  }
@@ -157,15 +295,63 @@ export function compactSelection(s) {
157
295
  ...(s.baseIndex !== undefined ? { baseIndex: s.baseIndex } : {}),
158
296
  };
159
297
  }
160
- /** A best-effort read: the value, or the reason it could not be read. */
298
+ /**
299
+ * A best-effort read: the value, or the reason it could not be read. A caller
300
+ * that cancelled is not a reason: its abort propagates.
301
+ */
161
302
  export async function attempt(run) {
162
303
  try {
163
304
  return { ok: true, value: await run() };
164
305
  }
165
306
  catch (err) {
307
+ if (currentCallSignal()?.aborted)
308
+ throw err;
166
309
  return { ok: false, reason: messageOf(err) };
167
310
  }
168
311
  }
312
+ /**
313
+ * Whether a failure is the transport/bridge (unreachable, timed out, the
314
+ * browser session unreadable) rather than HelloFresh answering — an HTTP 4xx
315
+ * or a missing input is not.
316
+ */
317
+ export function isBridgeFailure(err) {
318
+ if (err instanceof HelloFreshBridgeError)
319
+ return true;
320
+ if (err instanceof McpToolError)
321
+ return err.kind === 'transport' || err.kind === 'timeout';
322
+ // Duck-typed: a duplicated @fetchproxy package breaks instanceof.
323
+ return err instanceof Error && err.name.startsWith('Fetchproxy');
324
+ }
325
+ /**
326
+ * The calculator attempts of ONE tool call. The first attempt runs alone
327
+ * (concurrent weeks wait for it); once one fails because of the
328
+ * transport/bridge, every later week skips the calculator and gets that same
329
+ * reason at once, so a down bridge costs one failure (one timeout), not one
330
+ * per week. A cancelled call propagates (see `attempt`).
331
+ */
332
+ export function calculatorGate() {
333
+ let down;
334
+ let first;
335
+ return async function price(run) {
336
+ // Settled either way (it rejects only when the caller cancelled — then this call's own attempt rethrows too).
337
+ if (first)
338
+ await Promise.allSettled([first]);
339
+ if (down !== undefined)
340
+ return { ok: false, reason: down };
341
+ const tried = attempt(async () => {
342
+ try {
343
+ return await run();
344
+ }
345
+ catch (err) {
346
+ if (isBridgeFailure(err))
347
+ down = messageOf(err);
348
+ throw err;
349
+ }
350
+ });
351
+ first ??= tried;
352
+ return tried;
353
+ };
354
+ }
169
355
  // ---- brief ----------------------------------------------------------------------------
170
356
  /** `YYYY-MM-DD` of an ISO timestamp as HelloFresh wrote it (its own offset), or undefined. */
171
357
  export const dateOf = (iso) => iso?.slice(0, 10);
@@ -0,0 +1,9 @@
1
+ // The write tools, registered in roster order: the one-week writes, then the
2
+ // permanent plan writes. See `shared.ts` for the confirm-gated flow they share.
3
+ import { registerPlanWrites } from './plan.js';
4
+ import { registerWeekWrites } from './week.js';
5
+ export { SIZE_VERIFY_DELAY_MS, SIZE_VERIFY_READS } from './shared.js';
6
+ export function registerWriteTools(server, deps) {
7
+ registerWeekWrites(server, deps);
8
+ registerPlanWrites(server, deps);
9
+ }