Compare commits

...

4 Commits

Author SHA1 Message Date
Maurice 98c883b4e8 test(assistant): load the tool cap's groups without awaiting in a loop
The cap suite added eleven no-await-in-loop and two non-null assertion
warnings to the server tests, past the lint ratchet. Independent sessions
now run side by side and the sequential loads go through a recursive
helper.
2026-11-25 22:48:57 +01:00
Maurice df82208bd5 fix(assistant): keep every step within the 128 tools OpenAI and Azure accept
A trip chat offered 130 tools in its first step and up to 359 with every
group loaded. OpenAI's APIs and Azure refuse a request with more than 128
function tools (array_above_max_length), so the trip assistant failed at
once on an OpenAI style or Azure Foundry connection, while Anthropic and
the ChatGPT login took the longer list.

The trip's bookings, its packing lists and to-dos, changes to its budget
and its tags now load as groups like the addons do, which brings the core
to 63 tools, so any one group fits beside it. Loading a group that would
pass the limit unloads the one used longest ago, a call to one of its
tools loads it again, and groups asked for together that do not fit are
named so the model loads them later. The groups that are part of the trip
carry no domain on their change cards. Reading the costs stays in the
core.
2026-11-25 22:34:41 +01:00
Maurice 18867d9499 fix(weather): answer the day 16 days out with climate instead of an error
The detailed weather took the forecast path for any day whose distance
from now was at most 16 days, measured as a fraction of a day. Open-Meteo's
forecast reaches today + 15 calendar days, and the day 16 out lies 15.x
days from now, so it was asked of the forecast, refused with a 400, and
the day showed "No weather data". The cutoff now counts calendar days and
sends anything past today + 15 to the climate path. The forecast measures
its range from the place's own date, which trails UTC in the Americas for
part of the day, so a refusal of that range also falls back to climate.

Closes #3216
2026-11-25 22:21:16 +01:00
github-actions[bot] 13910464e5 chore: bump version to 5.2.1 [skip ci] 2026-11-25 13:18:29 +00:00
16 changed files with 525 additions and 119 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2 apiVersion: v2
name: trek name: trek
version: 5.2.0 version: 5.2.1
description: Minimal Helm chart for TREK app description: Minimal Helm chart for TREK app
appVersion: "5.2.0" appVersion: "5.2.1"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@trek/client", "name": "@trek/client",
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
+5 -5
View File
@@ -1,12 +1,12 @@
{ {
"name": "@trek/root", "name": "@trek/root",
"version": "5.2.0", "version": "5.2.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@trek/root", "name": "@trek/root",
"version": "5.2.0", "version": "5.2.1",
"workspaces": [ "workspaces": [
"client", "client",
"server", "server",
@@ -30,7 +30,7 @@
}, },
"client": { "client": {
"name": "@trek/client", "name": "@trek/client",
"version": "5.2.0", "version": "5.2.1",
"dependencies": { "dependencies": {
"@assistant-ui/react": "0.15.37", "@assistant-ui/react": "0.15.37",
"@capacitor/action-sheet": "^8.1.1", "@capacitor/action-sheet": "^8.1.1",
@@ -25991,7 +25991,7 @@
}, },
"server": { "server": {
"name": "@trek/server", "name": "@trek/server",
"version": "5.2.0", "version": "5.2.1",
"dependencies": { "dependencies": {
"@aws-lite/client": "^0.24.1", "@aws-lite/client": "^0.24.1",
"@aws-lite/s3": "^0.2.7", "@aws-lite/s3": "^0.2.7",
@@ -26408,7 +26408,7 @@
}, },
"shared": { "shared": {
"name": "@trek/shared", "name": "@trek/shared",
"version": "5.2.0", "version": "5.2.1",
"dependencies": { "dependencies": {
"isomorphic-dompurify": "^3.23.0", "isomorphic-dompurify": "^3.23.0",
"zod": "^4.6.7" "zod": "^4.6.7"
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "@trek/root", "name": "@trek/root",
"private": true, "private": true,
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@trek/server", "name": "@trek/server",
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
@@ -11,9 +11,10 @@ import { PACKAGE_HELD_READS, PACKAGE_TOOL_CONTROLLERS } from './cards/registry';
* annotated read-only runs at once, every other one waits as a change card. * annotated read-only runs at once, every other one waits as a change card.
* *
* Offering all of them in every step would cost a lot of tokens and runs past * Offering all of them in every step would cost a lot of tokens and runs past
* what some providers take in one request, so a turn starts with the core of * what some providers take in one request (MAX_OFFERED_TOOLS), so a turn
* a trip (days, places, bookings, packing, to-dos, budget, weather, search) * starts with the core of a trip (days, places, the plan, weather, search)
* and the model loads an addon's tools when it needs them (USE_TOOLS_TOOL). * and the model loads the rest of the trip and the addons when it needs them
* (USE_TOOLS_TOOL).
*/ */
/** /**
@@ -286,7 +287,14 @@ export function checkDenylist(names: Iterable<string>): string[] {
return problems; return problems;
} }
type ToolGroups = Readonly<Record<string, { about: string; controllers: readonly string[] }>>; interface ToolGroup {
about: string;
controllers: readonly string[];
/** A part of the trip itself rather than of the rest of TREK: its changes carry no place in TREK of their own. */
tripPart?: true;
}
type ToolGroups = Readonly<Record<string, ToolGroup>>;
/** /**
* The tool groups a turn can load, by the MCP controller that registers the * The tool groups a turn can load, by the MCP controller that registers the
@@ -295,6 +303,30 @@ type ToolGroups = Readonly<Record<string, { about: string; controllers: readonly
* belongs to the core, which every step offers. * belongs to the core, which every step offers.
*/ */
const CORE_TOOL_GROUPS: ToolGroups = { const CORE_TOOL_GROUPS: ToolGroups = {
bookings: {
about:
"The trip's bookings: flights, trains, stays and every other reservation, the hotels and other " +
'accommodation, airports and the live status of a flight.',
controllers: ['ReservationsMcp', 'ReservationsReadMcp', 'AccommodationsMcp', 'AirportsMcp', 'FlightLiveMcp'],
tripPart: true,
},
packing: {
about: "The trip's packing lists (items, bags, templates) and its to-do list.",
controllers: ['PackingMcp', 'TodoMcp'],
tripPart: true,
},
budget: {
about:
"Changing the trip's budget: costs, who paid and who shares them, settlements and frozen exchange rates. " +
'Reading the costs needs nothing loaded.',
controllers: ['BudgetMcp'],
tripPart: true,
},
tags: {
about: 'Tags and categories of places.',
controllers: ['TagsMcp', 'TripTagsMcp', 'CategoriesMcp'],
tripPart: true,
},
tours: { tours: {
about: about:
'Tours: hikes (also over several days in stages), city walks, bike tours (road, gravel, mountain bike), ' + 'Tours: hikes (also over several days in stages), city walks, bike tours (road, gravel, mountain bike), ' +
@@ -407,6 +439,11 @@ export function withPackageControllers(
export const ASSISTANT_TOOL_GROUPS = withPackageControllers(CORE_TOOL_GROUPS, PACKAGE_TOOL_CONTROLLERS); export const ASSISTANT_TOOL_GROUPS = withPackageControllers(CORE_TOOL_GROUPS, PACKAGE_TOOL_CONTROLLERS);
/** Whether a group is a part of the trip itself, whose changes show no place in TREK beside them. */
export function isTripPart(group: string): boolean {
return ASSISTANT_TOOL_GROUPS[group]?.tripPart === true;
}
const GROUP_OF_CONTROLLER = new Map( const GROUP_OF_CONTROLLER = new Map(
Object.entries(ASSISTANT_TOOL_GROUPS).flatMap(([group, { controllers }]) => Object.entries(ASSISTANT_TOOL_GROUPS).flatMap(([group, { controllers }]) =>
controllers.map((controller) => [controller, group] as const), controllers.map((controller) => [controller, group] as const),
@@ -428,7 +465,8 @@ function useToolsDescription(core: string): string {
Object.entries(ASSISTANT_TOOL_GROUPS) Object.entries(ASSISTANT_TOOL_GROUPS)
.map(([group, { about }]) => `"${group}" (${about})`) .map(([group, { about }]) => `"${group}" (${about})`)
.join('; ') + .join('; ') +
`. ${core}` `. ${core} Only so many tools fit in one step: loading a group can unload the one used longest ago, ` +
'which comes back when you call one of its tools.'
); );
} }
@@ -449,8 +487,7 @@ const USE_TOOLS_PARAMETERS: AiToolSpec['parameters'] = {
export const HOME_USE_TOOLS_SPEC: AiToolSpec = { export const HOME_USE_TOOLS_SPEC: AiToolSpec = {
name: USE_TOOLS_TOOL, name: USE_TOOLS_TOOL,
description: useToolsDescription( description: useToolsDescription(
'Reading the trips (list_trips, and a trip by its id: days, places, bookings, packing, to-dos, budget, weather) ' + 'Reading the trips (list_trips, and a trip by its id: days, places, costs, weather) needs nothing loaded.',
'needs nothing loaded.',
), ),
parameters: USE_TOOLS_PARAMETERS, parameters: USE_TOOLS_PARAMETERS,
}; };
@@ -458,7 +495,7 @@ export const HOME_USE_TOOLS_SPEC: AiToolSpec = {
export const USE_TOOLS_SPEC: AiToolSpec = { export const USE_TOOLS_SPEC: AiToolSpec = {
name: USE_TOOLS_TOOL, name: USE_TOOLS_TOOL,
description: useToolsDescription( description: useToolsDescription(
'The trip itself (days, places, bookings, packing, to-dos, budget, weather, search) needs nothing loaded.', 'The trip itself (days, places, the plan, notes, costs, weather, search) needs nothing loaded.',
), ),
parameters: { parameters: {
type: 'object', type: 'object',
@@ -19,6 +19,12 @@ export const MAX_READS_PER_STEP = 30;
/** Answer cards one step shows; the reads past it answer the model as usual, without a card. */ /** Answer cards one step shows; the reads past it answer the model as usual, without a card. */
export const MAX_CARDS_PER_STEP = 12; export const MAX_CARDS_PER_STEP = 12;
/**
* The most tools one request offers the model: OpenAI's APIs and Azure refuse
* a longer list (`array_above_max_length`), whatever else the provider takes.
*/
export const MAX_OFFERED_TOOLS = 128;
/** What a tool answer may cost the conversation, as JSON text, after it was cut down to its structure. */ /** What a tool answer may cost the conversation, as JSON text, after it was cut down to its structure. */
export const MAX_TOOL_OUTPUT_CHARS = 40_000; export const MAX_TOOL_OUTPUT_CHARS = 40_000;
@@ -31,6 +31,7 @@ import {
HOME_USE_TOOLS_SPEC, HOME_USE_TOOLS_SPEC,
isOfferedTool, isOfferedTool,
isStudioController, isStudioController,
isTripPart,
JOURNEY_PINNED_ARG, JOURNEY_PINNED_ARG,
keptAtHome, keptAtHome,
USE_TOOLS_SPEC, USE_TOOLS_SPEC,
@@ -39,6 +40,7 @@ import {
import { import {
ASSISTANT_SCOPES, ASSISTANT_SCOPES,
ASSISTANT_SERVER_TOOLS, ASSISTANT_SERVER_TOOLS,
MAX_OFFERED_TOOLS,
PINNED_ARG, PINNED_ARG,
PREVIEW_BOOK_PAGE_TOOL, PREVIEW_BOOK_PAGE_TOOL,
REMEMBER_TOOL, REMEMBER_TOOL,
@@ -82,6 +84,8 @@ export interface ToolHint {
destructive: boolean; destructive: boolean;
creates: boolean; creates: boolean;
group: string | null; group: string | null;
/** The group is a part of the trip itself (its bookings, its packing), not a place elsewhere in TREK. */
tripPart?: true;
} }
interface ListedTool { interface ListedTool {
@@ -218,6 +222,15 @@ function modelSchema(name: string, schema: Record<string, unknown>, pinArg: stri
return { ...rest, properties, ...(required.length > 0 ? { required } : {}) }; return { ...rest, properties, ...(required.length > 0 ? { required } : {}) };
} }
function hintOf(annotations: { destructiveHint?: boolean; idempotentHint?: boolean }, group: string | null): ToolHint {
return {
destructive: annotations.destructiveHint === true,
creates: annotations.idempotentHint === false,
group,
...(group && isTripPart(group) ? { tripPart: true as const } : {}),
};
}
function readResult(result: unknown): ToolRun { function readResult(result: unknown): ToolRun {
const record = (result ?? {}) as { content?: unknown; isError?: unknown }; const record = (result ?? {}) as { content?: unknown; isError?: unknown };
const text = Array.isArray(record.content) const text = Array.isArray(record.content)
@@ -264,7 +277,7 @@ export class AssistantToolSession {
private readonly pinArg: string = PINNED_ARG, private readonly pinArg: string = PINNED_ARG,
) {} ) {}
/** The groups this turn loaded; the core is always there. */ /** The groups this turn loaded, the one used longest ago first; the core is always there. */
private readonly loaded = new Set<string>(); private readonly loaded = new Set<string>();
/** Reads the model called before their group was loaded in this turn, by name, with that group; told once. */ /** Reads the model called before their group was loaded in this turn, by name, with that group; told once. */
@@ -286,6 +299,10 @@ export class AssistantToolSession {
specs(): AiToolSpec[] { specs(): AiToolSpec[] {
// The step these specs go to sees every loaded group's schema. // The step these specs go to sees every loaded group's schema.
this.unoffered.clear(); this.unoffered.clear();
return this.offeredSpecs();
}
private offeredSpecs(): AiToolSpec[] {
const listed = [...this.tools.values()] const listed = [...this.tools.values()]
.filter((tool) => tool.offered) .filter((tool) => tool.offered)
.filter((tool) => !this.grouped || tool.hint.group === null || this.loaded.has(tool.hint.group)) .filter((tool) => !this.grouped || tool.hint.group === null || this.loaded.has(tool.hint.group))
@@ -345,7 +362,7 @@ export class AssistantToolSession {
// name from an earlier turn), so it wrote the arguments without the // name from an earlier turn), so it wrote the arguments without the
// schema (#2967). Its group is loaded here, so the next step offers the // schema (#2967). Its group is loaded here, so the next step offers the
// schema. // schema.
this.loaded.add(unloaded); this.use([unloaded]);
this.unoffered.add(unloaded); this.unoffered.add(unloaded);
} }
const group = this.tools.get(name)?.hint.group; const group = this.tools.get(name)?.hint.group;
@@ -382,6 +399,8 @@ export class AssistantToolSession {
if (name === OPEN_JOURNEY_CHAT_TOOL && this.offersJournalChat) { if (name === OPEN_JOURNEY_CHAT_TOOL && this.offersJournalChat) {
return openJourneyChat(args, await this.invoke(OPEN_JOURNEY_CHAT_READ, {})); return openJourneyChat(args, await this.invoke(OPEN_JOURNEY_CHAT_READ, {}));
} }
const group = this.tools.get(name)?.hint.group;
if (group && this.loaded.delete(group)) this.loaded.add(group);
const final = name === TRANSIT_CREATE_TOOL ? await this.withFoundItinerary(args) : args; const final = name === TRANSIT_CREATE_TOOL ? await this.withFoundItinerary(args) : args;
const run = await this.invoke(name, final); const run = await this.invoke(name, final);
this.audit(name); this.audit(name);
@@ -436,9 +455,54 @@ ${hint}`,
const groups = asked.filter((group) => group in ASSISTANT_TOOL_GROUPS); const groups = asked.filter((group) => group in ASSISTANT_TOOL_GROUPS);
if (groups.length === 0) if (groups.length === 0)
return { ok: false, value: `Name one of: ${Object.keys(ASSISTANT_TOOL_GROUPS).join(', ')}` }; return { ok: false, value: `Name one of: ${Object.keys(ASSISTANT_TOOL_GROUPS).join(', ')}` };
for (const group of groups) this.loaded.add(group); const { unloaded, refused } = this.use(groups);
const tools = [...this.tools.values()].filter((tool) => tool.hint.group && groups.includes(tool.hint.group)); const loaded = groups.filter((group) => !refused.includes(group));
return { ok: true, value: { loaded: groups, tools: tools.map((tool) => tool.name) } }; const tools = [...this.tools.values()].filter((tool) => tool.hint.group && loaded.includes(tool.hint.group));
return {
ok: true,
value: {
loaded,
tools: tools.map((tool) => tool.name),
...(unloaded.length > 0 ? { unloaded } : {}),
...(refused.length > 0
? {
notLoaded: refused,
note: 'Too many tools for one step: load these on their own once the others are done.',
}
: {}),
},
};
}
/**
* Loads groups as the ones used last, then unloads the ones used longest
* ago until the step offers no more than MAX_OFFERED_TOOLS. Groups asked for
* together that do not fit even alone are left out from the last one asked.
*/
private use(groups: readonly string[]): { unloaded: string[]; refused: string[] } {
for (const group of groups) {
this.loaded.delete(group);
this.loaded.add(group);
}
const unloaded: string[] = [];
const refused: string[] = [];
const drop = (group: string) => {
this.loaded.delete(group);
this.unoffered.delete(group);
};
while (this.offeredSpecs().length > MAX_OFFERED_TOOLS) {
const oldest = [...this.loaded].find((group) => !groups.includes(group));
if (oldest) {
drop(oldest);
unloaded.push(oldest);
continue;
}
const last = [...this.loaded].reverse().find((group) => groups.includes(group) && !refused.includes(group));
if (!last || this.loaded.size === 1) break;
drop(last);
refused.push(last);
}
return { unloaded, refused };
} }
async close(): Promise<void> { async close(): Promise<void> {
@@ -620,11 +684,7 @@ export class AssistantToolsService implements OnApplicationBootstrap {
inputSchema, inputSchema,
kind, kind,
pinned: pinNamesOf(pin.arg).some((key) => key in properties), pinned: pinNamesOf(pin.arg).some((key) => key in properties),
hint: { hint: hintOf(annotations, entry ? groupOf(entry) : null),
destructive: annotations.destructiveHint === true,
creates: annotations.idempotentHint === false,
group: entry ? groupOf(entry) : null,
},
offered: true, offered: true,
}; };
if (offer.keep(listed)) tools.set(tool.name, { ...listed, offered: offer.offered?.(listed) ?? true }); if (offer.keep(listed)) tools.set(tool.name, { ...listed, offered: offer.offered?.(listed) ?? true });
@@ -29,7 +29,7 @@ How you work:
- The trip card may start with what the user is asking about. A question about "this place", "it" or "here" is about that; never ask which place they mean then. - The trip card may start with what the user is asking about. A question about "this place", "it" or "here" is about that; never ask which place they mean then.
- The user can name days, places and bookings with "@" before the name. The trip card then lists what they named, with the ids; use those. - The user can name days, places and bookings with "@" before the name. The trip card then lists what they named, with the ids; use those.
- The app shows the places your searches find as cards with a picture, and the weather you look up as a strip. Do not list them again in your text; say in a sentence or two which ones you suggest and why. - The app shows the places your searches find as cards with a picture, and the weather you look up as a strip. Do not list them again in your text; say in a sentence or two which ones you suggest and why.
- Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips. - Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first, and neither are those of the trip's bookings, its packing lists and to-dos, changes to its budget and its tags: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips.
- Propose a deletion only when the user asks for it; it cannot be undone, and the card says so. - Propose a deletion only when the user asks for it; it cannot be undone, and the card says so.
- You cannot share, invite people, publish links or calendar feeds, change who can see a trip, leave, copy or delete the trip, or make a new one. If asked, say so in one sentence and where in TREK the user can do it. - You cannot share, invite people, publish links or calendar feeds, change who can see a trip, leave, copy or delete the trip, or make a new one. If asked, say so in one sentence and where in TREK the user can do it.
- Keep what will matter later with remember_for_trip on your own, without asking: who travels, needs, likes and dislikes, budget, pace, fixed times the user mentions, and anything they ask you to remember. It is kept at once and comes back as <trip_notes> in every later conversation; say briefly that you noted it. Where you are not sure it lasts, offer it as a follow-up instead ("Remember: …"). Never say you cannot remember things. - Keep what will matter later with remember_for_trip on your own, without asking: who travels, needs, likes and dislikes, budget, pace, fixed times the user mentions, and anything they ask you to remember. It is kept at once and comes back as <trip_notes> in every later conversation; say briefly that you noted it. Where you are not sure it lasts, offer it as a follow-up instead ("Remember: …"). Never say you cannot remember things.
@@ -205,6 +205,6 @@ export function describeGeneric(
undoable: false, undoable: false,
effect: null, effect: null,
tool: toolName, tool: toolName,
...(hint?.group ? { domain: hint.group } : {}), ...(hint?.group && !hint.tripPart ? { domain: hint.group } : {}),
}; };
} }
@@ -1,5 +1,5 @@
/** /**
* How TREK 5.2.0 registers with the TREK services. * How TREK 5.2.1 registers with the TREK services.
* *
* The issuer writes this file for each release and the release pipeline * The issuer writes this file for each release and the release pipeline
* commits it with the version bump. It is not edited by hand, and its layout * commits it with the version bump. It is not edited by hand, and its layout
@@ -8,98 +8,76 @@
*/ */
import type { DialectSelfCheck, RegistrationDialect } from './registration-dialect.types'; import type { DialectSelfCheck, RegistrationDialect } from './registration-dialect.types';
import { createHash, createHmac, pbkdf2Sync } from 'node:crypto'; import { createHash, createHmac, hkdfSync, pbkdf2Sync } from 'node:crypto';
const DIALECT = 'MCC2i6oMga-k'; const DIALECT = 'Spbb4AEAqsgI';
const FLINT_AURORA = Buffer.from('e0bc92393c56a33c8046371de83c00b73975ec200058dcc1c08d07ef234a0997', 'hex'); const OAK_TIDE = Buffer.from('4584bf8b2c5def9bb9faaa5f0b1c73b662da1c97a558ced1f09f27eceeb0ebe9', 'hex');
const CHERRY_FALCON = 'abcdefghijklmnopqrstuvwxyz234567';
function glacier(part: Buffer): Buffer { function candle(alg: string, key: Buffer, data: Buffer): Buffer {
const head = Buffer.alloc(4); return createHmac(alg, key).update(data).digest();
head.writeUInt32LE(part.length);
return Buffer.concat([head, part]);
} }
function lynx(a: Buffer, b: Buffer): Buffer { function stone(input: Buffer, rotation: number, consts: Buffer): Buffer {
const parts: Buffer[] = []; const out = Buffer.from(input);
for (let i = 0; i < Math.max(a.length, b.length); i++) parts.push(a.subarray(i, i + 1), b.subarray(i, i + 1)); let previous = 0;
return Buffer.concat(parts); for (let i = 0; i + 4 <= out.length; i += 4) {
} const word = (out.readUInt32LE(i) + consts.readUInt32BE(i % consts.length)) >>> 0;
previous = (((word << rotation) | (word >>> (32 - rotation))) ^ previous) >>> 0;
function eagle(input: Buffer): string { out.writeUInt32LE(previous, i);
const bits = [...input].map((byte) => byte.toString(2).padStart(8, '0')).join('');
let out = '';
for (let i = 0; i < bits.length; i += 5) {
out += CHERRY_FALCON.charAt(parseInt(bits.slice(i, i + 5).padEnd(5, '0'), 2));
} }
return out; return out;
} }
function rowan(part: Buffer): Buffer { function stamp(part: Buffer): Buffer {
const head = Buffer.alloc(2);
head.writeUInt16BE(part.length);
return Buffer.concat([head, part]);
}
function saddle(alg: string, key: Buffer, data: Buffer): Buffer {
return createHmac(alg, key).update(data).digest();
}
function cedar(input: Buffer, size: number): Buffer {
const out = Buffer.alloc(size);
input.forEach((byte, i) => out.writeUInt8(out.readUInt8(i % size) ^ byte, i % size));
return out;
}
function alder(alg: string, size: number, data: Buffer): Buffer {
return createHash(alg, { outputLength: size }).update(data).digest();
}
function marsh(part: Buffer): Buffer {
const head = Buffer.alloc(2); const head = Buffer.alloc(2);
head.writeUInt16LE(part.length); head.writeUInt16LE(part.length);
return Buffer.concat([head, part]); return Buffer.concat([head, part]);
} }
function boulder(a: Buffer, b: Buffer): Buffer {
const parts: Buffer[] = [];
for (let i = 0; i < Math.max(a.length, b.length); i++) parts.push(a.subarray(i, i + 1), b.subarray(i, i + 1));
return Buffer.concat(parts);
}
export const registrationDialect: RegistrationDialect = { export const registrationDialect: RegistrationDialect = {
id: DIALECT, id: DIALECT,
releasedFor: '5.2.0', releasedFor: '5.2.1',
createdAt: '2026-11-23', createdAt: '2026-11-25',
challengePath: `/v1/register/${DIALECT}/challenge`, challengePath: `/v1/register/${DIALECT}/challenge`,
registerPath: `/v1/register/${DIALECT}`, registerPath: `/v1/register/${DIALECT}`,
begin({ challenge, version, random }) { begin({ challenge, version, random }) {
const cabin = Buffer.from(challenge.c, 'utf8'); const tundra = Buffer.from(challenge.c, 'utf8');
const harrier = Buffer.from(version, 'utf8'); const eddy = Buffer.from(version, 'utf8');
const quarry = createHash('sha256').update(cabin).digest(); const thistle = createHash('sha256').update(tundra).digest();
const winter = Buffer.concat([marsh(FLINT_AURORA), marsh(harrier), marsh(cabin), marsh(random.subarray(3, 12))]); const valley = Buffer.concat([tundra, eddy, random]);
const paddle = saddle('sha3-256', winter, FLINT_AURORA); const pier = Buffer.from(hkdfSync('sha256', valley, tundra, Buffer.from('afef6bd57409b2f4', 'hex'), 0x40));
const cypress = Buffer.from(paddle.toString('hex'), 'utf8'); const jetty = boulder(pier, thistle).subarray(0, pier.length);
return { return {
work(nonce) { work(nonce) {
const atlas = Buffer.concat([random, cabin, Buffer.from(nonce.toString(10)), harrier, FLINT_AURORA].map(rowan)); const basalt = Buffer.concat([OAK_TIDE, tundra, random, eddy, Buffer.from(nonce.toString(16)), thistle]);
const blossom = pbkdf2Sync(atlas, quarry.subarray(22, 0x1e), 20, 0x15, 'sha512'); const falcon = Buffer.concat([Buffer.concat([OAK_TIDE.subarray(0x10, 0x1f), Buffer.from([0x4e])]), basalt]);
const arbor = lynx(blossom, FLINT_AURORA).subarray(0, blossom.length); const cascade = Buffer.from('435052df4c2d17308c505231dfc4a7b95886b5b7', 'hex');
const coast = Buffer.from(arbor.subarray(0, 21)); const cabin = stone(stone(stone(falcon, 5, cascade), 0xd, cascade), 3, cascade);
const wave = alder('shake256', 0x40, coast); const flora = boulder(cabin, OAK_TIDE.subarray(2, 32));
return { password: wave, salt: cypress }; const cactus = createHash('sha384').update(flora).digest();
const cliff = candle('sha256', random.subarray(0xa, 0xe), cactus);
const island = Buffer.from(cliff.toString('hex').toUpperCase());
const mint = Buffer.concat([island, eddy]);
return { password: mint, salt: jetty };
}, },
request(nonce) { request(nonce) {
const basin = Buffer.concat([harrier, cabin, Buffer.from(`${nonce}`)].map(glacier)); const harvest = Buffer.concat([random, tundra, Buffer.from(nonce.toString(16), 'utf8'), eddy].map(stamp));
const wave6 = Buffer.concat([harrier, basin]); const comet = pbkdf2Sync(harvest, OAK_TIDE, 32, 0x33, 'sha512');
const wing = pbkdf2Sync(wave6, FLINT_AURORA.subarray(23, 0x1d), 0x1c, 0x1a, 'sha512'); const dune = createHash('sha3-512').update(comet).digest();
const ivy = Buffer.from([
3, 0xe, 0x11, 0xf, 9, 0xa, 7, 18, 13, 4, 11, 5, 16, 8, 0, 6, 1, 12, 2, 19,
].map((from) => wing.readUInt8(from)));
const grove = Buffer.concat([ivy, wing.subarray(20)]);
const dock = saddle('sha256', grove, random);
const pearl = cedar(dock, 0x14);
return { return {
body: { body: {
sierra_ridge: version, autumnForest: 'bridge-517',
paddle_mill: pearl.toString('hex'), crest: version,
gorge_rowan: challenge.c, harvestLichen: random.toString('hex'),
birch_cape: nonce, rowanCitadel: dune.toString('base64'),
ash: eagle(random), ember: challenge.c,
fountain: nonce.toString(16),
}, },
headers: {}, headers: {},
}; };
@@ -110,13 +88,13 @@ export const registrationDialect: RegistrationDialect = {
/** Fixed inputs and what this module must make of them; TREK's tests and release job run it. */ /** Fixed inputs and what this module must make of them; TREK's tests and release job run it. */
export const SELF_CHECK: DialectSelfCheck = { export const SELF_CHECK: DialectSelfCheck = {
challenge: { c: 'v1.selfcheck.MCC2i6oMga-k', alg: 'scrypt', N: 16, r: 1, p: 1, bits: 0, expires_at: 1 }, challenge: { c: 'v1.selfcheck.Spbb4AEAqsgI', alg: 'scrypt', N: 16, r: 1, p: 1, bits: 0, expires_at: 1 },
version: '5.2.0', version: '5.2.1',
random: '000102030405060708090a0b0c0d0e0f', random: '000102030405060708090a0b0c0d0e0f',
nowSeconds: 1800000000, nowSeconds: 1800000000,
nonce: 41, nonce: 41,
inputSha256: '5840e0d3d6661feeb110032d6bd6ce71653bbaad6695c4919d5dc4a1c90d4887', inputSha256: '08c66428b86c79a2891b3bdd1c32e8fa879b4f5c32f1e926e8708cebd8717f80',
saltSha256: 'd6108d62280c10f09c6ed4b68c4ae18934b5c9bd1b0d2f97452cdc4d048bb8cc', saltSha256: 'e5c8ae7aba8548e7053b8f8f2ab1d6639217b9c38e4aed5e5a7338ee3db30a73',
scrypt: '66520ede3f817fec6584440217987d2d5d810f0a1f2f6f05bb7108901ba12070', scrypt: 'c092ecce1df2d1d2fa238a6034fe14700641a4e9e759c01967d5834d57b2f3c6',
requestSha256: '4a6a4228f493fcef6c185c910b2667cf08317c0ac693eba64ea850b32ee79980', requestSha256: '59dcea6833950308358e9387e57f62e3f3d8b5f36499fe8a28e9d7931e322092',
}; };
+48 -13
View File
@@ -640,6 +640,47 @@ async function detailedFromArchive(
}; };
} }
/**
* The last day Open-Meteo's forecast answers, counted in calendar days from today.
* The fraction of a day between now and the target's midnight is not that count:
* the day 16 out lies 15.x days away and slipped through a `<= 16` test (#3216).
*/
const FORECAST_LAST_DAY = 15;
function calendarDaysAhead(day: string, now: Date): number {
const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
return Math.round((Date.parse(`${day}T00:00:00Z`) - today) / 86_400_000);
}
/**
* The forecast counts its range from the place's own date, which trails UTC's in
* the Americas for part of the day, so its last day can still be refused there.
*/
function isOutsideForecastRange(status: number, reason: string | undefined): boolean {
return status === 400 && /out of allowed range/i.test(reason ?? '');
}
/** Last year's day standing in for a trip day the forecast does not reach. */
async function detailedClimate(
lat: string,
lng: string,
targetDate: Date,
now: Date,
descriptions: Record<number, string>,
ck: string,
): Promise<WeatherResult> {
let refYear = targetDate.getFullYear() - 1;
// Archive API only has data up to yesterday — go back further if needed
const yesterday = new Date(now.getTime() - 86400000);
if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
setCache(ck, climate, TTL_CLIMATE_MS);
return climate;
}
async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, lang: string): Promise<WeatherResult> { async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, lang: string): Promise<WeatherResult> {
const ck = `detailed_${cacheKey(lat, lng, date, lang)}`; const ck = `detailed_${cacheKey(lat, lng, date, lang)}`;
@@ -652,18 +693,9 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
const dateStr = targetDate.toISOString().slice(0, 10); const dateStr = targetDate.toISOString().slice(0, 10);
const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN; const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
// Climate path (> 16 days out): last year's day stands in for the trip's. // Climate path: past the forecast's last day, last year's day stands in for the trip's.
if (diffDays > 16) { if (calendarDaysAhead(dateStr, now) > FORECAST_LAST_DAY) {
let refYear = targetDate.getFullYear() - 1; return detailedClimate(lat, lng, targetDate, now, descriptions, ck);
// Archive API only has data up to yesterday — go back further if needed
const yesterday = new Date(now.getTime() - 86400000);
if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
setCache(ck, climate, TTL_CLIMATE_MS);
return climate;
} }
// Past day: the forecast API answers nulls once a date is a couple of months // Past day: the forecast API answers nulls once a date is a couple of months
@@ -678,7 +710,7 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
} }
} }
// Forecast path (<= 16 days) // Forecast path (up to today + 15 days)
const url = const url =
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}` + `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}` +
`&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m` + `&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m` +
@@ -688,6 +720,9 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
const { response, data } = await fetchOpenMeteo(url); const { response, data } = await fetchOpenMeteo(url);
if (!response.ok || data.error) { if (!response.ok || data.error) {
if (isOutsideForecastRange(response.status, data.reason)) {
return detailedClimate(lat, lng, targetDate, now, descriptions, ck);
}
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error'); throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
} }
@@ -0,0 +1,171 @@
/**
* The tools one request offers the model stay within what OpenAI's APIs and
* Azure take (MAX_OFFERED_TOOLS): a longer list is refused before the model
* reads a word, with `array_above_max_length` (a trip chat on Azure Foundry
* offered 130 in its first step).
*/
import { ADDON_IDS } from '../../../../src/addons';
import { ASSISTANT_TOOL_GROUPS } from '../../../../src/nest/assistant/assistant-tool-offer';
import { MAX_OFFERED_TOOLS } from '../../../../src/nest/assistant/assistant-tools.constants';
import {
AssistantToolsService,
type AssistantToolSession,
} from '../../../../src/nest/assistant/assistant-tools.service';
import { makeJourney } from '../../../helpers/factories/journeys';
import { setAddonEnabled, setAppSetting } from '../../../helpers/factories/settings';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { FakeRealtimeService } from '../../../helpers/fake-realtime';
import { bootTestApp } from '../../../helpers/test-app';
import { MikroORM } from '@mikro-orm/core';
import { beforeAll, describe, expect, it } from 'vitest';
let orm: MikroORM;
let tools: AssistantToolsService;
const GROUPS = Object.keys(ASSISTANT_TOOL_GROUPS);
beforeAll(async () => {
const app = await bootTestApp(new FakeRealtimeService());
orm = app.get(MikroORM);
tools = app.get(AssistantToolsService);
// Every addon on, so every group holds all it can.
await Promise.all(Object.values(ADDON_IDS).map((addon) => setAddonEnabled(orm, addon, true)));
await setAppSetting(orm, 'tours_wanderer_enabled', 'true');
});
async function tripSession(): Promise<AssistantToolSession> {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id, { title: 'Kyoto' });
return tools.open(user.id, trip.id);
}
/** Runs `use` on the session and closes it whatever happens. */
async function within<T>(
opening: Promise<AssistantToolSession>,
use: (session: AssistantToolSession) => Promise<T>,
): Promise<T> {
const session = await opening;
try {
return await use(session);
} finally {
await session.close();
}
}
const names = (session: AssistantToolSession) => session.specs().map((spec) => spec.name);
interface LoadAnswer {
loaded: string[];
tools: string[];
unloaded?: string[];
notLoaded?: string[];
note?: string;
}
interface Step {
group: string;
answer: LoadAnswer;
offered: string[];
}
/** Loads the groups one step after another, as a model would over a turn, with what each step offered. */
async function loadOneByOne(session: AssistantToolSession, groups: readonly string[]): Promise<Step[]> {
const [group, ...rest] = groups;
if (group === undefined) return [];
const run = await session.call('use_addon_tools', { groups: [group] });
const step = { group, answer: run.value as LoadAnswer, offered: names(session) };
return [step, ...(await loadOneByOne(session, rest))];
}
describe('the tools one step offers', () => {
it('ASTCAP-001: a trip chat starts within the limit, with room for any one group beside the core', async () => {
const start = await within(tripSession(), (session) => Promise.resolve(session.specs().length));
expect(start).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
const counts = await Promise.all(
GROUPS.map((group) =>
within(tripSession(), async (session) => {
const run = await session.call('use_addon_tools', { groups: [group] });
return { group, ok: run.ok, loaded: (run.value as LoadAnswer).loaded, offered: session.specs().length };
}),
),
);
for (const { group, ok, loaded, offered } of counts) {
expect(ok, group).toBe(true);
expect(loaded, group).toEqual([group]);
expect(offered, group).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
}
});
it('ASTCAP-002: loading one group after another unloads the one used longest ago, never the one just asked for', async () => {
const steps = await within(tripSession(), (session) => loadOneByOne(session, GROUPS));
for (const { group, answer, offered } of steps) {
expect(answer.loaded).toEqual([group]);
expect(answer.unloaded ?? [], group).not.toContain(group);
expect(offered.length, group).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
for (const tool of answer.tools) expect(offered, `${group}: ${tool}`).toContain(tool);
}
// Every group cannot fit at once, so the walk had to make room, oldest first.
const unloaded = steps.flatMap((step) => step.answer.unloaded ?? []);
expect(unloaded.length).toBeGreaterThan(0);
expect(unloaded[0]).toBe(GROUPS[0]);
});
it('ASTCAP-003: asking for every group at once loads what fits and names the rest', async () => {
await within(tripSession(), async (session) => {
const run = await session.call('use_addon_tools', { groups: GROUPS });
const value = run.value as LoadAnswer;
expect(session.specs().length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
expect(value.loaded.length).toBeGreaterThan(0);
expect([...value.loaded, ...(value.notLoaded ?? [])].sort()).toEqual([...GROUPS].sort());
expect(value.notLoaded?.length ?? 0).toBeGreaterThan(0);
expect(value.note).toMatch(/on their own/);
});
});
it('ASTCAP-004: a tool of a group that was unloaded loads it again when the model calls it', async () => {
await within(tripSession(), async (session) => {
const [first, ...others] = GROUPS;
const [loadedFirst] = await loadOneByOne(session, first === undefined ? [] : [first]);
const tool = String(loadedFirst?.answer.tools[0]);
expect(loadedFirst?.offered).toContain(tool);
// Loading every other group makes room by unloading the first one, used longest ago.
await loadOneByOne(session, others);
expect(names(session)).not.toContain(tool);
expect(session.pinArgs(tool, {})).not.toHaveProperty('error');
expect(names(session)).toContain(tool);
expect(session.specs().length).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
});
});
it('ASTCAP-005: the home chat stays within the limit with any one group loaded', async () => {
const { user } = await makeUser(orm);
const counts = await Promise.all(
GROUPS.map((group) =>
within(tools.openHome(user.id), async (session) => {
const before = session.specs().length;
await session.call('use_addon_tools', { groups: [group] });
return { group, before, after: session.specs().length };
}),
),
);
for (const { group, before, after } of counts) {
expect(before, 'home').toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
expect(after, group).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
}
});
it('ASTCAP-006: a journey chat offers no more than the limit on either of its pages', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id, { title: 'Lisbon' });
const counts = await Promise.all(
(['studio', 'journal'] as const).map((surface) =>
within(tools.openJourney(user.id, journey.id, { role: 'owner', surface }), (session) =>
Promise.resolve({ surface, offered: session.specs().length }),
),
),
);
for (const { surface, offered } of counts) expect(offered, surface).toBeLessThanOrEqual(MAX_OFFERED_TOOLS);
});
});
@@ -226,6 +226,18 @@ describe('describeToolCall', () => {
const year = describeToolCall('add_vacay_year', 'tc-9', { year: 2027 }, hinted(false, true, 'vacay')); const year = describeToolCall('add_vacay_year', 'tc-9', { year: 2027 }, hinted(false, true, 'vacay'));
expect(year).toMatchObject({ verbKey: 'genericCreate', domain: 'vacay', undoable: false }); expect(year).toMatchObject({ verbKey: 'genericCreate', domain: 'vacay', undoable: false });
// A vacation day has a card of its own, even before its lookup ran: the day, in the vacation planner. // A vacation day has a card of its own, even before its lookup ran: the day, in the vacation planner.
// A part of the trip that loads as a group (its tags) is no place elsewhere in TREK: no domain.
const tag = describeToolCall(
'add_trip_label',
'tc-11',
{ name: 'Food' },
{
...ctx,
hintOf: () => ({ destructive: false, creates: true, group: 'tags', tripPart: true as const }),
},
);
expect(tag).toMatchObject({ verbKey: 'genericCreate', tool: 'add_trip_label' });
expect(tag).not.toHaveProperty('domain');
const vacay = describeToolCall('toggle_vacay_entry', 'tc-10', { date: '2026-07-01', half: true }, ctx); const vacay = describeToolCall('toggle_vacay_entry', 'tc-10', { date: '2026-07-01', half: true }, ctx);
expect(vacay).toMatchObject({ verbKey: 'addVacationDay', subject: 'Wed 1 Jul', domain: 'vacay', undoable: false }); expect(vacay).toMatchObject({ verbKey: 'addVacationDay', subject: 'Wed 1 Jul', domain: 'vacay', undoable: false });
expect(vacay.rows).toEqual([]); expect(vacay.rows).toEqual([]);
@@ -1223,3 +1223,110 @@ describe('size cap on the Open-Meteo body', () => {
expect(result.temp).toBe(15); expect(result.temp).toBe(15);
}); });
}); });
// ── the forecast's last day (#3216) ──────────────────────────────────────────
describe('getDetailedWeather at the edge of the forecast range', () => {
const FORECAST = 'api.open-meteo.com/v1/forecast';
const ARCHIVE = 'archive-api.open-meteo.com/v1/archive';
const archiveDay = {
daily: {
time: ['2025-12-11'],
temperature_2m_max: [8],
temperature_2m_min: [2],
weathercode: [3],
precipitation_sum: [0],
windspeed_10m_max: [12],
sunrise: ['2025-12-11T07:50'],
sunset: ['2025-12-11T16:10'],
},
hourly: { time: [], temperature_2m: [] },
};
const forecastDay = (date: string) => ({
daily: {
time: [date],
temperature_2m_max: [10],
temperature_2m_min: [4],
weathercode: [1],
sunrise: [`${date}T07:50`],
sunset: [`${date}T16:10`],
precipitation_probability_max: [10],
precipitation_sum: [0],
windspeed_10m_max: [9],
},
hourly: { time: [], temperature_2m: [] },
});
/** Answers like Open-Meteo: the forecast refuses a start_date past `lastForecastDay`. */
function openMeteo(lastForecastDay: string) {
vi.mocked(fetch).mockImplementation(async (input) => {
const url = String(input);
if (url.includes(FORECAST)) {
const start = /start_date=([\d-]+)/.exec(url)?.[1] ?? '';
if (start > lastForecastDay) {
return mockResponse(
{
error: true,
reason: `Parameter 'start_date' is out of allowed range from 2026-08-24 to ${lastForecastDay}`,
},
false,
400,
);
}
return mockResponse(forecastDay(start));
}
if (url.includes(ARCHIVE)) return mockResponse(archiveDay);
throw new Error(`unexpected request ${url}`);
});
}
beforeEach(() => {
vi.mocked(fetch).mockReset();
});
it('WEATHER-HORIZON-001: the day 16 days out answers with climate instead of failing', async () => {
vi.setSystemTime(new Date('2026-11-25T13:00:00Z'));
openMeteo('2026-12-10');
const result = await getDetailedWeather('47.10', '11.30', '2026-12-11', 'en');
expect(result.type).toBe('climate');
expect(result.temp_max).toBe(8);
const asked = vi.mocked(fetch).mock.calls.map(([u]) => String(u));
expect(asked.some((u) => u.includes(FORECAST))).toBe(false);
expect(asked.some((u) => u.includes(`${ARCHIVE}`) && u.includes('start_date=2025-12-11'))).toBe(true);
});
it('WEATHER-HORIZON-002: the day 15 days out keeps its forecast, late in the UTC day too', async () => {
vi.setSystemTime(new Date('2026-11-25T23:30:00Z'));
openMeteo('2026-12-10');
const result = await getDetailedWeather('47.11', '11.31', '2026-12-10', 'en');
expect(result.type).toBe('forecast');
expect(result.temp_max).toBe(10);
});
it('WEATHER-HORIZON-003: a place whose local date is still behind UTC falls back to climate on the refusal', async () => {
// 02:00 UTC is still the day before in the Americas, so Open-Meteo's range
// there ends a day earlier than UTC's today + 15.
vi.setSystemTime(new Date('2026-11-26T02:00:00Z'));
openMeteo('2026-12-10');
const result = await getDetailedWeather('40.71', '-74.00', '2026-12-11', 'en');
expect(result.type).toBe('climate');
expect(result.temp_max).toBe(8);
});
it('WEATHER-HORIZON-004: any other refusal of the forecast still surfaces as an error', async () => {
vi.setSystemTime(new Date('2026-11-25T13:00:00Z'));
vi.mocked(fetch).mockResolvedValue(
mockResponse({ error: true, reason: 'Cannot initialize WeatherVariable' }, false, 400),
);
await expect(getDetailedWeather('47.12', '11.32', '2026-12-01', 'en')).rejects.toMatchObject({ status: 400 });
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@trek/shared", "name": "@trek/shared",
"version": "5.2.0", "version": "5.2.1",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },