src/tools/time-tools.ts
2 KB - Ver el archivo original
// Two small, read-only tools for lab 01. A study coach needs both all the time ("how many days
// until my exam?"), and a model guessing today's date is a classic source of wrong answers.
import { z } from 'zod';
import { defineTool, type ToolContext } from './tool.ts';
/** Calendar date (YYYY-MM-DD) of an instant in a time zone. */
export function dateInZone(instant: Date, timezone: string): string {
// en-CA formats dates as YYYY-MM-DD.
return new Intl.DateTimeFormat('en-CA', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(instant);
}
/** Whole days from calendar date `from` to calendar date `to` (both YYYY-MM-DD). */
export function daysBetween(from: string, to: string): number {
const ms = Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`);
return Math.round(ms / 86_400_000);
}
export const currentTime = defineTool({
name: 'current_time',
description:
"Returns the current date, time, and weekday in the owner's time zone. Call it whenever the " +
'answer depends on today or now.',
input: z.object({}),
run: (_input, context: ToolContext) => {
const now = context.now();
const formatted = new Intl.DateTimeFormat('en-US', {
timeZone: context.timezone,
dateStyle: 'full',
timeStyle: 'short',
}).format(now);
return `${formatted} (${context.timezone}); date ${dateInZone(now, context.timezone)}`;
},
});
export const daysUntil = defineTool({
name: 'days_until',
description:
"Counts the calendar days from today (owner's time zone) until a date, for example an exam " +
'date. Negative when the date is in the past.',
input: z.object({
date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, 'use the YYYY-MM-DD format')
.describe('Target date, YYYY-MM-DD'),
}),
run: ({ date }, context: ToolContext) => {
// Round-trip check: rejects dates like 2026-02-30 that some parsers roll over to March.
const parsed = new Date(`${date}T00:00:00Z`);
if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
throw new Error(`not a real date: ${date}`);
}
const today = dateInZone(context.now(), context.timezone);
const days = daysBetween(today, date);
return `${days} day(s) from ${today} to ${date}`;
},
});
export const timeTools = [currentTime, daysUntil];