@chrischall/hellofresh-mcp 0.3.0 → 0.5.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/dist/client.js CHANGED
@@ -53,6 +53,12 @@ export class HelloFreshClient {
53
53
  route: `/api/subscriptions/{id}/delivery_dates/${week}`,
54
54
  });
55
55
  }
56
+ /** A box's carrier tracking, by the public id at the end of the delivery's `tracking.tracking_link`. */
57
+ getTracking(publicId) {
58
+ return this.request('GET', apiPath `/scm/tracking-ids/track/public-id/${publicId}`, {
59
+ route: '/scm/tracking-ids/track/public-id/{id}',
60
+ });
61
+ }
56
62
  getProductOptions(subscriptionId) {
57
63
  return this.request('GET', apiPath `/api/subscriptions/${subscriptionId}/product_options`, {
58
64
  route: '/api/subscriptions/{id}/product_options',
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { readWsPort } from './config.js';
5
5
  import { TOOL_REGISTRARS } from './tools/index.js';
6
6
  import { createProfileStore } from './profiles.js';
7
7
  import { HelloFreshSession } from './session.js';
8
+ import { createSessionCache } from './session-cache.js';
8
9
  import { createHelloFreshBridge } from './transport.js';
9
10
  import { VERSION } from './version.js';
10
11
  // The bridge bootstraps the session: it reads (and refreshes) the apiV2Auth
@@ -19,7 +20,9 @@ await bridge.start().catch(() => { });
19
20
  // Built ONCE, outside the registrars (runMcp builds a server per connection).
20
21
  // Nothing here resolves a credential at boot (deferred-config-error pattern).
21
22
  const fetchImpl = (input, init) => fetch(input, init);
22
- const session = new HelloFreshSession({ bridge, fetchImpl });
23
+ // The session survives a restart through a 0600 file (HELLOFRESH_SESSION_FILE;
24
+ // HELLOFRESH_SESSION_CACHE=false keeps it in memory only). Opening it touches no disk.
25
+ const session = new HelloFreshSession({ bridge, fetchImpl, persistence: createSessionCache() });
23
26
  const deps = {
24
27
  bridge,
25
28
  session,
package/dist/normalize.js CHANGED
@@ -85,6 +85,56 @@ export function projectDelivery(d) {
85
85
  oneOffDaySlots: (d.availableOneOffOptions ?? []).map((o) => ({ handle: o.handle, deliveryDate: o.deliveryDate })),
86
86
  };
87
87
  }
88
+ // ---- tracking --------------------------------------------------------------------
89
+ /** The public id a delivery's HelloFresh tracking link ends in (only a www.hellofresh.com link counts). */
90
+ export function trackingPublicId(t) {
91
+ const m = /^https:\/\/www\.hellofresh\.com\/delivery-tracking\/([0-9a-f-]{8,64})\/?$/i.exec(t?.tracking_link ?? '');
92
+ return m?.[1];
93
+ }
94
+ const opt = (key, value) => (value === undefined || value === null || value === '' ? {} : { [key]: value });
95
+ const step = (s) => ({
96
+ ...opt('status', s.status),
97
+ ...opt('statusDetail', s.status_detail),
98
+ ...opt('at', s.datetime),
99
+ ...opt('message', s.message),
100
+ });
101
+ /**
102
+ * Carrier tracking, allowlisted: carrier, code, live status (HelloFresh's and
103
+ * its internal one) and the status history. Never the signer's name, the box's
104
+ * external id, its lane or the proof-of-delivery photo URLs (only their count).
105
+ */
106
+ export function projectTracking(raw) {
107
+ const boxes = (raw.boxes ?? []).filter((b) => !!b && typeof b === 'object');
108
+ return {
109
+ boxes: boxes.map((b) => {
110
+ const last = b.last_status ?? {};
111
+ const photos = Array.isArray(b.proof_of_delivery_photo_urls) ? b.proof_of_delivery_photo_urls.length : 0;
112
+ const history = (b.statuses ?? []).filter((s) => !!s && typeof s === 'object').map(step);
113
+ const lastAt = Date.parse(last.datetime ?? '');
114
+ const newer = history
115
+ .filter((h) => Date.parse(h.at ?? '') > (Number.isNaN(lastAt) ? -Infinity : lastAt))
116
+ .sort((a, z) => Date.parse(z.at) - Date.parse(a.at))[0];
117
+ return {
118
+ ...opt('carrier', b.carrier),
119
+ ...opt('trackingCode', b.tracking_code),
120
+ ...opt('status', last.status),
121
+ ...opt('statusDetail', last.status_detail),
122
+ ...opt('internalStatus', b.internal_status ?? last.internal_status),
123
+ ...opt('internalStatusDetail', b.internal_status_detail ?? last.internal_status_detail),
124
+ ...opt('statusMessage', last.message),
125
+ ...opt('statusAt', last.datetime),
126
+ ...opt('estimatedDelivery', last.est_delivery_time),
127
+ ...opt('carrierTrackingUrl', b.carrier_tracking_url ?? b.public_url),
128
+ ...opt('trackingUrl', b.hf_tracking_url),
129
+ ...opt('deliveryDate', b.delivery_date),
130
+ delivered: last.status === 'delivered' || newer?.status === 'delivered',
131
+ ...(newer ? { latestEvent: newer } : {}),
132
+ ...(photos > 0 ? { proofOfDeliveryPhotos: photos } : {}),
133
+ history,
134
+ };
135
+ }),
136
+ };
137
+ }
88
138
  const QUICK_TAGS = new Set(['quick', 'easy-prep']);
89
139
  const QUICK_MINUTES = 30;
90
140
  function isSeafoodCategory(category) {
@@ -0,0 +1,33 @@
1
+ // Where the HelloFresh session is kept between runs (lifecycle step 6 in
2
+ // src/session.ts). One small 0600 JSON file, replaced atomically, with a
3
+ // cross-process lock beside it — the fleet's createFileStatePersistence.
4
+ //
5
+ // It holds the token set WITHOUT `user_data` (the customer id and email). On
6
+ // mcp-host it lands in the registration's persistent data dir (MCP_DATA_DIR;
7
+ // mint.yaml declares `state.dataDir: true`), elsewhere under $HOME.
8
+ import { parseBoolEnv } from '@chrischall/mcp-utils';
9
+ import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
10
+ import { isTokenSet } from './session.js';
11
+ /** `HELLOFRESH_SESSION_FILE`, else `<MCP_DATA_DIR or HOME>/.hellofresh-mcp/session.json`. */
12
+ export function sessionCachePath(env = process.env) {
13
+ return resolveStateFile({ env, envVar: 'HELLOFRESH_SESSION_FILE', subdir: '.hellofresh-mcp', fileName: 'session.json' });
14
+ }
15
+ function asPersistedSession(raw) {
16
+ if (typeof raw !== 'object' || raw === null)
17
+ return null;
18
+ const r = raw;
19
+ if (!isTokenSet(r['set']) || typeof r['set'].issued_at !== 'number')
20
+ return null;
21
+ if (typeof r['own'] !== 'boolean' || typeof r['writtenBack'] !== 'boolean')
22
+ return null;
23
+ return { set: r['set'], own: r['own'], writtenBack: r['writtenBack'] };
24
+ }
25
+ /** The session store, or `null` when `HELLOFRESH_SESSION_CACHE` turns it off. */
26
+ export function createSessionCache(env = process.env) {
27
+ if (!parseBoolEnv('HELLOFRESH_SESSION_CACHE', { env, default: true }))
28
+ return null;
29
+ return createFileStatePersistence({
30
+ filePath: sessionCachePath(env),
31
+ validate: asPersistedSession,
32
+ });
33
+ }
package/dist/session.js CHANGED
@@ -25,9 +25,23 @@
25
25
  // out). Only its ACCESS token is used, while still valid (and not
26
26
  // rejected); otherwise the original bridge error is rethrown, its
27
27
  // pairing hint intact. /gw/refresh is never called.
28
- // A set read from the browser is never a fallback: its refresh token may
29
- // already be spent by the browser. A missing cookie (signed out) is NOT a
30
- // read failure and still fails.
28
+ // A set read from the browser is never refreshed as a fallback: its
29
+ // refresh token may already be spent by the browser. Its ACCESS token may
30
+ // stand in while still valid (and not rejected). A missing cookie (signed
31
+ // out) is NOT a read failure and still fails.
32
+ // 6. Optional persistence (`src/session-cache.ts`) carries the newest set —
33
+ // and whether it is our own refresh and was written back — across a
34
+ // restart. It is loaded once, as if this process had just used it, so
35
+ // step 5's rules decide what a stored set may do: the browser's newer
36
+ // cookie still wins, a stored ACCESS token stands in while valid, and only
37
+ // our own never-written-back refresh token is ever POSTed without the
38
+ // browser. `user_data` (customer id, email) is never stored. Refreshing
39
+ // holds the store's cross-process lock and re-reads it first, so a sibling
40
+ // process (Claude Desktop beside Claude Code) that just refreshed is
41
+ // adopted instead of racing it with the same rotating refresh token. A
42
+ // rejected refresh clears the record (unless a sibling's newer one replaced
43
+ // it), so a dead session is not read back off disk. A store failure is
44
+ // logged and never fails a call.
31
45
  //
32
46
  // No token value is ever logged, put in an error message or returned.
33
47
  import { EdgeBlockedError, McpToolError, SessionNotAuthenticatedError, createCachedTokenSource, decodeJwtClaim, detectEdgeBlock, messageOf, parseJsonBody, redactValues, truncateErrorMessage, } from '@chrischall/mcp-utils';
@@ -124,7 +138,7 @@ export function decodeAuthCookie(raw) {
124
138
  }
125
139
  return parsed;
126
140
  }
127
- function isTokenSet(value) {
141
+ export function isTokenSet(value) {
128
142
  if (typeof value !== 'object' || value === null || Array.isArray(value))
129
143
  return false;
130
144
  const v = value;
@@ -139,6 +153,11 @@ export function tokenExpiresAtMs(set) {
139
153
  const exp = decodeJwtClaim(set.access_token, 'exp');
140
154
  return typeof exp === 'number' ? exp * 1000 : 0;
141
155
  }
156
+ /** The record to store for `set`: never its `user_data` (customer id, email). */
157
+ export function toPersistedSession(set, from) {
158
+ const { user_data: _userData, ...rest } = set;
159
+ return { set: rest, own: from.own, writtenBack: from.own && from.writtenBack };
160
+ }
142
161
  /** How many token values to remember for redaction. */
143
162
  const REDACT_HISTORY = 8;
144
163
  export class HelloFreshSession {
@@ -158,6 +177,10 @@ export class HelloFreshSession {
158
177
  /** Whether that refresh was written back to the browser (which may then rotate it on its own). */
159
178
  ownWrittenBack = false;
160
179
  seen = [];
180
+ /** The stored record is read once, on the first lifecycle. */
181
+ restored = false;
182
+ /** Identity of what was last saved, to skip rewriting an unchanged record. */
183
+ savedKey;
161
184
  constructor(opts) {
162
185
  this.opts = opts;
163
186
  this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
@@ -236,12 +259,15 @@ export class HelloFreshSession {
236
259
  }
237
260
  catch (err) {
238
261
  const ours = this.latest;
239
- if (!ours || ours.refresh_token !== this.ownRefreshToken)
262
+ if (!ours)
240
263
  throw err;
241
- // Written back: the browser may have rotated (spent) its refresh token — use the access token only.
242
- if (this.ownWrittenBack ? !this.fresh(ours) : !this.refreshable(ours))
264
+ // Only our own never-written-back refresh token is ours alone to spend; any
265
+ // other set (the browser's, or ours once written back) stands in by its
266
+ // still-valid access token only — the browser may have rotated its refresh token.
267
+ const ownUnwritten = ours.refresh_token === this.ownRefreshToken && !this.ownWrittenBack;
268
+ if (ownUnwritten ? !this.refreshable(ours) : !this.fresh(ours))
243
269
  throw err;
244
- console.error(`[hellofresh-mcp] could not read the browser session (${truncateErrorMessage(this.redact(messageOf(err)), 200)}); using this process's own refreshed session`);
270
+ console.error(`[hellofresh-mcp] could not read the browser session (${truncateErrorMessage(this.redact(messageOf(err)), 200)}); using the last session this server knew of`);
245
271
  return ours;
246
272
  }
247
273
  if (!raw)
@@ -257,12 +283,43 @@ export class HelloFreshSession {
257
283
  return browserIsNewest ? browser : ours;
258
284
  }
259
285
  async lifecycle() {
286
+ if (!this.restored) {
287
+ this.restored = true;
288
+ const stored = await this.loadStored();
289
+ if (stored)
290
+ this.adopt(stored);
291
+ }
260
292
  const newest = await this.newestSet();
261
293
  if (this.fresh(newest)) {
262
- this.latest = newest;
294
+ if (newest !== this.latest) {
295
+ this.latest = newest;
296
+ this.ownRefreshToken = undefined;
297
+ }
298
+ await this.persist();
263
299
  return newest;
264
300
  }
265
- const next = await this.refresh(newest);
301
+ return this.locked(() => this.refreshLocked(newest));
302
+ }
303
+ /** Step 3, holding the store's cross-process lock. */
304
+ async refreshLocked(newest) {
305
+ // A sibling process may have refreshed while we waited: take its set rather
306
+ // than POST a refresh token it has already spent.
307
+ const stored = await this.loadStored();
308
+ if (stored && stored.set.issued_at > newest.issued_at && this.fresh(stored.set)) {
309
+ this.adopt(stored);
310
+ return stored.set;
311
+ }
312
+ let next;
313
+ try {
314
+ next = await this.refresh(newest);
315
+ }
316
+ catch (err) {
317
+ // A dead session must not be read back off disk — unless a sibling's newer record replaced ours.
318
+ if (err instanceof HelloFreshSessionError && (!stored || stored.set.issued_at <= newest.issued_at)) {
319
+ await this.store('clear', () => this.opts.persistence?.clear?.());
320
+ }
321
+ throw err;
322
+ }
266
323
  this.latest = next;
267
324
  this.ownRefreshToken = next.refresh_token;
268
325
  this.ownWrittenBack = false;
@@ -276,8 +333,56 @@ export class HelloFreshSession {
276
333
  this.writeBackWarning = WRITE_BACK_WARNING;
277
334
  console.error(`[hellofresh-mcp] could not write the refreshed session back to the browser: ${truncateErrorMessage(this.redact(messageOf(err)), 200)}`);
278
335
  }
336
+ await this.persist();
279
337
  return next;
280
338
  }
339
+ /** Take a stored record as this process's newest known set. */
340
+ adopt(stored) {
341
+ this.latest = stored.set;
342
+ this.ownRefreshToken = stored.own ? stored.set.refresh_token : undefined;
343
+ this.ownWrittenBack = stored.own && stored.writtenBack;
344
+ this.savedKey = this.keyOf(stored.set);
345
+ this.remember(stored.set);
346
+ }
347
+ keyOf(set) {
348
+ const own = set.refresh_token === this.ownRefreshToken;
349
+ return `${set.access_token}\u0000${set.refresh_token}\u0000${own}\u0000${own && this.ownWrittenBack}`;
350
+ }
351
+ async persist() {
352
+ const set = this.latest;
353
+ if (!this.opts.persistence || !set)
354
+ return;
355
+ const key = this.keyOf(set);
356
+ if (key === this.savedKey)
357
+ return;
358
+ const own = set.refresh_token === this.ownRefreshToken;
359
+ const ok = await this.store('save', () => this.opts.persistence?.save(toPersistedSession(set, { own, writtenBack: this.ownWrittenBack })));
360
+ if (ok)
361
+ this.savedKey = key;
362
+ }
363
+ async loadStored() {
364
+ let stored = null;
365
+ await this.store('load', async () => {
366
+ stored = (await this.opts.persistence?.load()) ?? null;
367
+ });
368
+ return stored;
369
+ }
370
+ locked(fn) {
371
+ const store = this.opts.persistence;
372
+ return store?.withLock ? store.withLock(fn) : fn();
373
+ }
374
+ /** Run a store operation; a failure is logged (redacted), never thrown. */
375
+ async store(op, fn) {
376
+ try {
377
+ await fn();
378
+ return true;
379
+ }
380
+ catch (err) {
381
+ console.error(`[hellofresh-mcp] could not ${op} the ${op === 'load' ? 'saved ' : ''}HelloFresh session on disk ` +
382
+ `(${truncateErrorMessage(this.redact(messageOf(err)), 200)}); continuing without it.`);
383
+ return false;
384
+ }
385
+ }
281
386
  async bridged(fn) {
282
387
  try {
283
388
  return await fn();
@@ -0,0 +1,256 @@
1
+ // HelloFresh customer-support chat ("FreshBot") — docs/HELLOFRESH-API.md
2
+ // "Support chat (Sierra)".
3
+ //
4
+ // The chat on www.hellofresh.com/contact-us is NOT a /gw endpoint: it is a
5
+ // Sierra AI agent (eu.sierra.chat) that a person can take over. Three calls:
6
+ //
7
+ // 1. POST {SIERRA_API}/graphql embedChatRefreshWindowTokenQuery → a window
8
+ // token for a client-chosen window id (no HelloFresh credential needed);
9
+ // 2. POST {SIERRA_API}/chat one client event (`start` opens a
10
+ // conversation, `message` sends text) → a stream of
11
+ // `BOT_CHAT_EVENT_BEGIN{json}BOT_CHAT_EVENT_END` frames: the conversation
12
+ // id and its encryption key (on start), streamed reply text, and `state`
13
+ // snapshots of the whole transcript;
14
+ // 3. POST {SIERRA_API}/chat/live/poll — a long-poll the site runs only while
15
+ // a human agent is involved; with none it answers 204 after ~48 s.
16
+ //
17
+ // The request carries `memory.secrets.CUSTOMER_JWT` = the HelloFresh access
18
+ // token (exactly as the site sends it — that is how FreshBot reads the
19
+ // account). It is never logged, returned or put in an error.
20
+ //
21
+ // Everything here is pure or takes an injected fetch: the tools own the
22
+ // conversation store and the token.
23
+ import { McpToolError, messageOf, truncateErrorMessage } from '@chrischall/mcp-utils';
24
+ export const SIERRA_API = 'https://eu.sierra.chat/-/api';
25
+ /** HelloFresh US's public chat-agent key (it is in the widget's script URL on every page). */
26
+ export const SIERRA_AGENT_KEY = 'rEVzK9YBnPzNiWEBnPzNic4p0Ya-JWIRjGNmiP8amMI';
27
+ export const SUPPORT_SERVICE = 'HelloFresh support chat';
28
+ /** The entry reason the site sends from its "Chat now" button (the one value observed). */
29
+ export const ENTRY_REASON = 'unknown-from_chat_now_button';
30
+ export const CHAT_LOCALE = 'en-US';
31
+ export const DEFAULT_TIME_ZONE = 'America/New_York';
32
+ /** Bound on a start / message turn (the reply streams in the same response). */
33
+ export const TURN_TIMEOUT_MS = 90_000;
34
+ const WINDOW_TOKEN_QUERY = 'query embedChatRefreshWindowTokenQuery($token:String!$userIdentityToken:String$windowId:String){embedBotByToken(token:$token fullscreen:false userIdentityToken:$userIdentityToken windowId:$windowId){__typename ...on EmbedBot{windowToken}...on Node{__isNode:__typename id}}}';
35
+ // ---- the stream -----------------------------------------------------------------
36
+ /** Every frame of a chat answer, in order. A frame that is not JSON is skipped. */
37
+ export function parseChatStream(text) {
38
+ const frames = [];
39
+ for (const m of text.matchAll(/BOT_CHAT_EVENT_BEGIN([\s\S]*?)BOT_CHAT_EVENT_END/g)) {
40
+ try {
41
+ const value = JSON.parse(m[1]);
42
+ if (value && typeof value === 'object' && !Array.isArray(value))
43
+ frames.push(value);
44
+ }
45
+ catch {
46
+ // A malformed frame is skipped: the state snapshots repeat the transcript.
47
+ }
48
+ }
49
+ return frames;
50
+ }
51
+ const META_KEYS = new Set(['timestamp', 'idempotencyKey', 'tags', 'encryptedFullRedactionMode', 'eventId', 'agentInvocationId']);
52
+ const SPEAKER = { USER: 'user', AGENT: 'bot', HUMAN_AGENT: 'human_agent' };
53
+ const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
54
+ function linksOf(attachments) {
55
+ if (!Array.isArray(attachments))
56
+ return undefined;
57
+ const links = attachments.flatMap((a) => {
58
+ const data = a?.data;
59
+ const url = str(data?.path);
60
+ return url && /^https:\/\//.test(url) ? [{ ...(str(data?.label) ? { label: str(data?.label) } : {}), url }] : [];
61
+ });
62
+ return links.length > 0 ? links : undefined;
63
+ }
64
+ /** The state snapshot's events, projected: who said what and when. Unknown shapes are skipped, never guessed at. */
65
+ export function projectEvents(raw) {
66
+ const out = [];
67
+ for (const e of raw) {
68
+ if (!e || typeof e !== 'object' || Array.isArray(e))
69
+ continue;
70
+ const ev = e;
71
+ const kind = Object.keys(ev).find((k) => !META_KEYS.has(k));
72
+ if (!kind)
73
+ continue;
74
+ const base = { ...(str(ev.timestamp) ? { at: str(ev.timestamp) } : {}), ...(str(ev.eventId) ? { id: str(ev.eventId) } : {}) };
75
+ if (kind === 'message') {
76
+ const m = ev.message;
77
+ const text = str(m?.text);
78
+ if (!m || !text || m.isProgressIndicator === true)
79
+ continue;
80
+ const from = SPEAKER[String(m.author)];
81
+ const links = linksOf(m.attachments);
82
+ out.push({
83
+ kind,
84
+ ...(from ? { from } : {}),
85
+ ...(from === 'human_agent' && str(m.displayName) ? { name: str(m.displayName) } : {}),
86
+ text,
87
+ ...base,
88
+ ...(links ? { links } : {}),
89
+ });
90
+ continue;
91
+ }
92
+ if (kind === 'humanAgentParticipation') {
93
+ const type = ev.humanAgentParticipation?.type;
94
+ out.push({ kind: type === 'JOIN' ? 'agentJoined' : type === 'LEAVE' ? 'agentLeft' : kind, ...base });
95
+ continue;
96
+ }
97
+ // humanAgentTyping is transient UI state, not part of the record.
98
+ if (kind === 'humanAgentTyping')
99
+ continue;
100
+ const detail = kind === 'queueInfo' ? ev.queueInfo : undefined;
101
+ out.push({ kind, ...base, ...(detail !== undefined ? { detail } : {}) });
102
+ }
103
+ return out;
104
+ }
105
+ const stateEvents = (frame) => {
106
+ const events = frame.state?.events;
107
+ return Array.isArray(events) ? events : undefined;
108
+ };
109
+ /** The conversation id + key (sent on start) and the transcript of the last state frame. */
110
+ export function readTurn(frames) {
111
+ const turn = {};
112
+ for (const f of frames) {
113
+ if (typeof f.conversationID === 'string')
114
+ turn.conversationID = f.conversationID;
115
+ if (typeof f.encryptionKey === 'string')
116
+ turn.encryptionKey = f.encryptionKey;
117
+ if (f.type === 'state') {
118
+ const events = stateEvents(f);
119
+ if (events)
120
+ turn.events = projectEvents(events);
121
+ }
122
+ }
123
+ return turn;
124
+ }
125
+ // ---- request bodies (the site's own shapes) -------------------------------------------
126
+ export function chatRequestBody(r) {
127
+ const clientEvent = r.event.type === 'start'
128
+ ? { type: 'start', idempotencyKey: r.idempotencyKey }
129
+ : { type: 'message', message: { content: r.event.text }, idempotencyKey: r.idempotencyKey, idempotencyReplayResponse: true };
130
+ return {
131
+ token: SIERRA_AGENT_KEY,
132
+ releaseHash: 'production',
133
+ ...(r.conversation ? { conversationID: r.conversation.conversationID, encryptionKey: r.conversation.encryptionKey } : {}),
134
+ clientEvent,
135
+ userMessageText: r.event.type === 'message' ? r.event.text : '',
136
+ memory: r.memory,
137
+ locale: CHAT_LOCALE,
138
+ timeZone: r.timeZone ?? DEFAULT_TIME_ZONE,
139
+ userMessageIndex: 0,
140
+ windowId: r.windowId,
141
+ };
142
+ }
143
+ export function livePollBody(r) {
144
+ return {
145
+ token: SIERRA_AGENT_KEY,
146
+ releaseHash: 'production',
147
+ conversationID: r.conversation.conversationID,
148
+ encryptionKey: r.conversation.encryptionKey,
149
+ memory: r.memory,
150
+ locale: CHAT_LOCALE,
151
+ timeZone: r.timeZone ?? DEFAULT_TIME_ZONE,
152
+ windowId: r.windowId,
153
+ };
154
+ }
155
+ export class SierraChat {
156
+ fetchImpl;
157
+ redact;
158
+ timeoutMs;
159
+ constructor(opts) {
160
+ this.fetchImpl = opts.fetchImpl;
161
+ this.redact = opts.redact ?? ((t) => t);
162
+ this.timeoutMs = opts.timeoutMs ?? TURN_TIMEOUT_MS;
163
+ }
164
+ /** A window token for `windowId` (the `x-window-token` every chat call carries). */
165
+ async windowToken(windowId) {
166
+ const res = await this.post('/graphql', 'application/json', {
167
+ query: WINDOW_TOKEN_QUERY,
168
+ variables: { token: SIERRA_AGENT_KEY, userIdentityToken: null, windowId },
169
+ });
170
+ const text = await res.text();
171
+ let token;
172
+ try {
173
+ token = JSON.parse(text).data?.embedBotByToken?.windowToken;
174
+ }
175
+ catch {
176
+ // handled below
177
+ }
178
+ if (typeof token !== 'string' || token === '') {
179
+ throw new McpToolError(`${SUPPORT_SERVICE} did not issue a window token (HTTP ${res.status}).`, { kind: 'http', status: res.status });
180
+ }
181
+ return token;
182
+ }
183
+ /** One client event; the reply streams back in the same response. */
184
+ async turn(body, windowToken) {
185
+ const res = await this.post('/chat', 'text/plain', body, { 'x-window-token': windowToken });
186
+ const text = await res.text();
187
+ const frames = parseChatStream(text);
188
+ if (frames.length === 0) {
189
+ throw new McpToolError(`${SUPPORT_SERVICE} answered HTTP ${res.status} with no chat events.`, { kind: 'http', status: res.status });
190
+ }
191
+ return readTurn(frames);
192
+ }
193
+ /** Wait up to `waitMs` for new live-agent events. Running out of time is "nothing new". */
194
+ async poll(body, windowToken, waitMs) {
195
+ let res;
196
+ try {
197
+ res = await this.post('/chat/live/poll', 'text/plain', body, { 'x-window-token': windowToken }, waitMs, true);
198
+ }
199
+ catch (err) {
200
+ if (err instanceof WaitElapsed)
201
+ return { status: 'nothing_new' };
202
+ throw err;
203
+ }
204
+ if (res.status === 204)
205
+ return { status: 'nothing_new' };
206
+ let parsed;
207
+ try {
208
+ parsed = JSON.parse(await res.text());
209
+ }
210
+ catch {
211
+ throw new McpToolError(`${SUPPORT_SERVICE}'s live poll answered something that is not JSON.`, { kind: 'http', status: res.status });
212
+ }
213
+ const se = parsed.streamEvent;
214
+ const events = Array.isArray(se?.state?.events) ? projectEvents(se.state.events) : [];
215
+ return {
216
+ status: 'events',
217
+ events,
218
+ isDelta: se?.isDelta === true,
219
+ ...(typeof se?.stateCursor === 'string' ? { stateCursor: se.stateCursor } : {}),
220
+ };
221
+ }
222
+ async post(path, contentType, body, extraHeaders = {}, timeoutMs = this.timeoutMs, waitIsNormal = false) {
223
+ const signal = AbortSignal.timeout(timeoutMs);
224
+ let res;
225
+ try {
226
+ res = await this.fetchImpl(`${SIERRA_API}${path}`, {
227
+ method: 'POST',
228
+ headers: { 'content-type': contentType, accept: '*/*', ...extraHeaders },
229
+ body: JSON.stringify(body),
230
+ signal,
231
+ });
232
+ }
233
+ catch (err) {
234
+ if (signal.aborted && waitIsNormal)
235
+ throw new WaitElapsed();
236
+ if (signal.aborted) {
237
+ throw new McpToolError(`${SUPPORT_SERVICE} did not answer in time (${timeoutMs} ms).`, { kind: 'timeout', cause: err });
238
+ }
239
+ throw new McpToolError(`Could not reach ${SUPPORT_SERVICE}: ${truncateErrorMessage(this.redact(messageOf(err)), 200)}`, {
240
+ kind: 'transport',
241
+ cause: err,
242
+ });
243
+ }
244
+ if (!res.ok && res.status !== 204) {
245
+ const text = await res.text();
246
+ throw new McpToolError(`${SUPPORT_SERVICE} answered HTTP ${res.status} on ${path}: ${truncateErrorMessage(this.redact(text), 200)}`, {
247
+ kind: res.status === 401 || res.status === 403 ? 'credential_rejected' : 'http',
248
+ status: res.status,
249
+ });
250
+ }
251
+ return res;
252
+ }
253
+ }
254
+ /** The long-poll's own wait ran out (internal: answered as "nothing new"). */
255
+ class WaitElapsed extends Error {
256
+ }
@@ -7,6 +7,7 @@ import { registerHealthcheckTool } from './healthcheck.js';
7
7
  import { registerPlannerTools } from './planner.js';
8
8
  import { registerPromoTools } from './promo.js';
9
9
  import { registerReadTools } from './reads.js';
10
+ import { registerSupportTools } from './support.js';
10
11
  import { registerWriteTools } from './writes/index.js';
11
12
  export const TOOL_REGISTRARS = [
12
13
  registerHealthcheckTool,
@@ -16,4 +17,5 @@ export const TOOL_REGISTRARS = [
16
17
  registerCookingTools,
17
18
  registerFavoriteTools,
18
19
  registerPromoTools,
20
+ registerSupportTools,
19
21
  ];
@@ -5,7 +5,7 @@
5
5
  // payment token, none of which is ever returned.
6
6
  import { z } from 'zod';
7
7
  import { mapWithConcurrency, minifiedResult, resolveView, todayIso, toolAnnotations } from '@chrischall/mcp-utils';
8
- import { parseSku, projectDelivery, projectSubscription, } from '../normalize.js';
8
+ import { parseSku, projectDelivery, projectTracking, trackingPublicId, projectSubscription, } from '../normalize.js';
9
9
  import { isoWeekOf, shiftWeek } from '../weeks.js';
10
10
  import { LOOKUP, foodMeta } from './hints.js';
11
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';
@@ -85,6 +85,26 @@ function applyFilters(meals, f) {
85
85
  // ---- registration -------------------------------------------------------------------
86
86
  export function registerReadTools(server, deps) {
87
87
  const { client } = deps;
88
+ /**
89
+ * The box's carrier tracking, best effort: none before the box is labelled
90
+ * (no HelloFresh tracking link yet); a failed read keeps the delivery's own
91
+ * code and link and says why.
92
+ */
93
+ const readTracking = async (raw, full) => {
94
+ const publicId = trackingPublicId(raw.tracking);
95
+ if (!publicId)
96
+ return {};
97
+ const read = await attempt(async () => projectTracking(await client.getTracking(publicId)));
98
+ if (!read.ok || read.value.boxes.length === 0) {
99
+ return {
100
+ tracking: { trackingCode: raw.tracking?.tracking_code || undefined, trackingUrl: raw.tracking?.tracking_link },
101
+ trackingError: read.ok ? 'HelloFresh returned no tracked box for this delivery.' : read.reason,
102
+ };
103
+ }
104
+ const [first, ...more] = read.value.boxes;
105
+ const shape = (b) => (full ? b : { ...b, history: undefined });
106
+ return { tracking: shape(first), ...(more.length > 0 ? { moreBoxes: more.map(shape) } : {}) };
107
+ };
88
108
  const now = deps.now ?? Date.now;
89
109
  server.registerTool('hf_get_subscription', {
90
110
  description: 'Read the HelloFresh meal-kit subscription: the plan’s box size (meals × people, SKU), price per box, ' +
@@ -181,9 +201,10 @@ export function registerReadTools(server, deps) {
181
201
  });
182
202
  server.registerTool('hf_get_delivery', {
183
203
  description: 'Read one HelloFresh delivery week: delivery date and slot, meal-pick cutoff, status, box size, the meals ' +
184
- 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, and the box price ' +
204
+ 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, the box price ' +
185
205
  '— HelloFresh’s own checkout total plus the picked meals’ premium upcharge, or a labelled local estimate ' +
186
- 'when that cannot be read.',
206
+ 'when that cannot be read — and, once the box is labelled, its carrier tracking: carrier, tracking code, ' +
207
+ 'live status (e.g. delayed / shortage, delivered) and, in the full view, the status history.',
187
208
  annotations: readOnly('HelloFresh: get delivery'),
188
209
  _meta: LOOKUP,
189
210
  inputSchema: z.object({
@@ -201,10 +222,12 @@ export function registerReadTools(server, deps) {
201
222
  }),
202
223
  }, async ({ week, box_number, next_box_number, view }) => {
203
224
  const account = await loadAccount(client);
204
- const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
225
+ const raw = await client.getDelivery(account.subscriptionId, week);
226
+ const delivery = projectDelivery(raw);
205
227
  const menu = delivery.status === 'skipped' ? undefined : await attempt(() => readMenu(client, account, delivery, week));
206
228
  const selected = menu?.ok ? menu.value.selected : undefined;
207
229
  const full = resolveView(view, HF_VIEWS) === 'full';
230
+ const tracking = await readTracking(raw, full);
208
231
  let boxNumberNote;
209
232
  // The upcoming list is read only when the estimate needs a derived box number.
210
233
  const fallbackBoxNumber = async () => {
@@ -231,6 +254,7 @@ export function registerReadTools(server, deps) {
231
254
  ...(menu && !menu.ok ? { selectionError: menu.reason } : {}),
232
255
  ...(price ? { price } : {}),
233
256
  ...(boxNumberNote ? { boxNumberNote } : {}),
257
+ ...tracking,
234
258
  });
235
259
  });
236
260
  server.registerTool('hf_get_menu', {