From bd6e1ed38734cbfb37b09ffeb64fb0e75443dd5a Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 16 Oct 2026 02:57:29 +0800 Subject: [PATCH] tools-calc 0.1.0: exact arithmetic, unit conversion and date math for every agent A new kind of package: an OpenCode plugin whose only hook is `tool`, which magpie serves to every agent on /mcp/magpie/tools. Three tools: eval (exact rational arithmetic in BigInt fractions), convert (data, time, length, CSS, mass, angle, temperature) and date (calendar-aware add, between, weekday/ISO week, IANA zones through Intl, DST included). No network, no key, no dependency. Run: - bun test packages/calc: 8 tests, 73 expects, pass with TZ=UTC and TZ=Pacific/Kiritimati. - A sandbox magpie built from yetone/magpie origin/main b03031738 (nogui, HOME in a scratch dir, gateway on 127.0.0.1:3591): `magpie plugin add `; `magpie plugin` lists "tools calc_convert, calc_date, calc_eval". Over /mcp/magpie/tools: initialize, tools/list (3 tools with their schemas), tools/call calc_eval 0.1+0.2 -> {"exact":"3/10","decimal":"0.3"}, 1/0 -> isError "division by zero", calc_convert 1 GiB->MB -> 16777216/15625 (1073.741824), calc_date across New York's DST with `to` -> between. Not tried: an npm install. From npm the tools are named tools-calc_*, since magpie's ShortName doesn't strip "tools-". --- packages/calc/README.md | 58 +++++ packages/calc/calc.mjs | 469 ++++++++++++++++++++++++++++++++++++ packages/calc/calc.test.mjs | 110 +++++++++ packages/calc/index.mjs | 81 +++++++ packages/calc/package.json | 11 + 5 files changed, 729 insertions(+) create mode 100644 packages/calc/README.md create mode 100644 packages/calc/calc.mjs create mode 100644 packages/calc/calc.test.mjs create mode 100644 packages/calc/index.mjs create mode 100644 packages/calc/package.json diff --git a/packages/calc/README.md b/packages/calc/README.md new file mode 100644 index 0000000..a726a3d --- /dev/null +++ b/packages/calc/README.md @@ -0,0 +1,58 @@ +# @magpie-community/tools-calc + +Exact arithmetic, unit conversion and date math, as tools [magpie](https://usemagpie.ai) offers every agent it connects. Models get arithmetic wrong (`0.1 + 0.2`, big powers, days between two dates across a DST change), so this gives them a calculator. It needs no network, no key and no dependency. + +Install it from magpie's **Plugins › Discover**, or with: + +```sh +magpie plugin add @magpie-community/tools-calc +magpie plugin # lists its tools +``` + +magpie serves the tools on its MCP server, `/mcp/magpie/tools`, to every agent it has connected. Each tool's name starts with the plugin's: `tools-calc_eval` when installed from npm, `calc_eval` from a folder (`magpie plugin add ./packages/calc`). + +## Tools + +**`eval`** `{expression, places?}` evaluates an expression exactly, in fractions, with no floating point. + +- Operators: `+ - * / % ^` (or `**`), parentheses, and unary minus. +- Numbers: decimals, `1e9`, `0x`/`0b`/`0o` literals, and `1_000`. +- Functions: `abs floor ceil round trunc min max gcd lcm fact`. +- It answers `{exact, decimal}`, plus `rounded: true` when the decimal was cut at `places` (20 by default). + +``` +0.1+0.2 → {"exact":"3/10","decimal":"0.3"} +2^128/3 → every digit, exact +1/0 → an error: division by zero +``` + +**`convert`** `{value, from, to, places?}` converts a quantity exactly. `value` can be an expression, such as `3*1024`. + +| Kind | Units | +|---|---| +| Data | `bit B kB MB GB TB` (1000s), `KiB MiB GiB TiB` (1024s), `kb Mb Gb` | +| Time | `ns us ms s min h d wk` | +| Length | `nm um mm cm m km in ft yd mi nmi` | +| CSS | `px pt pc` | +| Mass | `mg g kg t oz lb` | +| Angle | `deg turn grad` | +| Temperature | `C F K` | + +``` +1 GiB → MB → {"exact":"16777216/15625","decimal":"1073.741824","unit":"MB"} +``` + +**`date`** `{date?, add?, to?, timeZone?}` does date math on the real calendar. + +- `date` is ISO 8601, unix seconds or milliseconds, or `now` (the default). It answers the ISO time, weekday, ISO week, day of year and unix time. +- `add` is a duration, such as `3d 4h`, `-90m`, `1y2mo` or ISO `P1DT2H`. Years, months and days count on the calendar, so Jan 31 + 1mo is the last day of February, and a day across a DST change is still a day. +- `to` is a second date. The answer then also has `between`, the time from `date` (after `add`) to `to`, in days, hours, minutes, seconds and calendar years, months and days. +- `timeZone` is an IANA zone, such as `Asia/Shanghai`. Dates with no offset are read as that zone's wall time, and the answer shows the local time. Without it, they are UTC. + +## Test + +```sh +bun test packages/calc +``` + +中文:给 magpie 连接的每个 agent 提供精确计算工具:`eval` 用分数精确计算表达式,`convert` 换算数据、时间、长度、质量、角度和温度单位,`date` 按真实日历做日期加减和间隔(支持时区与夏令时)。不联网,不需要 key。 diff --git a/packages/calc/calc.mjs b/packages/calc/calc.mjs new file mode 100644 index 0000000..ef39d50 --- /dev/null +++ b/packages/calc/calc.mjs @@ -0,0 +1,469 @@ +// Exact arithmetic, unit conversion and date math for coding agents. A +// model guesses at 0.1 + 0.2, at 2^64, at how many days lie between two +// dates; these answer exactly. Numbers are fractions of BigInts, so nothing +// is rounded until the answer is written out. Nothing here reaches the +// network or reads a file. + +// ---- exact numbers ----------------------------------------------------------- + +const abs = (a) => (a < 0n ? -a : a) +const gcd = (a, b) => { + a = abs(a) + b = abs(b) + while (b) [a, b] = [b, a % b] + return a +} + +// Q is a fraction n/d in lowest terms, d > 0. +class Q { + constructor(n, d = 1n) { + if (d === 0n) throw new Error("division by zero") + if (d < 0n) [n, d] = [-n, -d] + const g = gcd(n, d) || 1n + this.n = n / g + this.d = d / g + } + add(b) { return new Q(this.n * b.d + b.n * this.d, this.d * b.d) } + sub(b) { return new Q(this.n * b.d - b.n * this.d, this.d * b.d) } + mul(b) { return new Q(this.n * b.n, this.d * b.d) } + div(b) { + if (b.n === 0n) throw new Error("division by zero") + return new Q(this.n * b.d, this.d * b.n) + } + // the remainder of a truncated division, as JavaScript's % + mod(b) { + if (b.n === 0n) throw new Error("division by zero") + const q = (this.n * b.d) / (this.d * b.n) + return this.sub(b.mul(new Q(q))) + } + pow(e) { + if (e.d !== 1n) throw new Error("a power must be a whole number: this answers exactly, and x^(1/2) mostly isn't") + if (abs(e.n) > 100000n) throw new Error("a power past 100000 is too big to write out") + let n = this.n ** abs(e.n) + let d = this.d ** abs(e.n) + if (e.n < 0n) [n, d] = [d, n] + return new Q(n, d) + } + cmp(b) { + const x = this.n * b.d - b.n * this.d + return x < 0n ? -1 : x > 0n ? 1 : 0 + } + floor() { + const q = this.n / this.d + return new Q(this.n < 0n && q * this.d !== this.n ? q - 1n : q) + } + ceil() { return this.neg().floor().neg() } + neg() { return new Q(-this.n, this.d) } + int() { return this.d === 1n } + // the fraction as "n" or "n/d" + exact() { return this.d === 1n ? String(this.n) : `${this.n}/${this.d}` } + // the decimal, rounded half away from zero at places digits; exact says + // whether nothing was rounded + decimal(places = 20) { + const neg = this.n < 0n + const n = abs(this.n) + const scale = 10n ** BigInt(places) + let q = (n * scale) / this.d + const r = (n * scale) % this.d + if (r * 2n >= this.d) q++ + const digits = q.toString().padStart(places + 1, "0") + const whole = places > 0 ? digits.slice(0, -places) : digits + const frac = places > 0 ? digits.slice(-places).replace(/0+$/, "") : "" + const s = frac ? `${whole}.${frac}` : whole + const exact = r === 0n + return { text: (neg && q !== 0n ? "-" : "") + s, exact } + } +} + +// parseNumber reads a literal: 12, -3.5, 1_000, 6.02e23, 0x1F, 0b101, 0o17. +export function parseNumber(src) { + const s = String(src).trim().replace(/_/g, "") + let m + if ((m = /^([+-]?)0x([0-9a-f]+)$/i.exec(s))) return new Q((m[1] === "-" ? -1n : 1n) * BigInt("0x" + m[2])) + if ((m = /^([+-]?)0b([01]+)$/i.exec(s))) return new Q((m[1] === "-" ? -1n : 1n) * BigInt("0b" + m[2])) + if ((m = /^([+-]?)0o([0-7]+)$/i.exec(s))) return new Q((m[1] === "-" ? -1n : 1n) * BigInt("0o" + m[2])) + m = /^([+-]?)(\d*)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(s) + if (!m || (m[2] === "" && (m[3] ?? "") === "")) throw new Error(`not a number: ${src}`) + const frac = m[3] ?? "" + let n = BigInt((m[2] || "0") + frac) + let d = 10n ** BigInt(frac.length) + const e = Number(m[4] ?? 0) + if (Math.abs(e) > 10000) throw new Error(`exponent too big: ${src}`) + if (e > 0) n *= 10n ** BigInt(e) + else if (e < 0) d *= 10n ** BigInt(-e) + return new Q(m[1] === "-" ? -n : n, d) +} + +// ---- expressions ------------------------------------------------------------- + +const FUNCS = { + abs: (a) => (a.n < 0n ? a.neg() : a), + floor: (a) => a.floor(), + ceil: (a) => a.ceil(), + round: (a) => (a.n < 0n ? a.neg().add(new Q(1n, 2n)).floor().neg() : a.add(new Q(1n, 2n)).floor()), + trunc: (a) => (a.n < 0n ? a.ceil() : a.floor()), + min: (...xs) => xs.reduce((a, b) => (b.cmp(a) < 0 ? b : a)), + max: (...xs) => xs.reduce((a, b) => (b.cmp(a) > 0 ? b : a)), + gcd: (...xs) => { + if (!xs.every((x) => x.int())) throw new Error("gcd takes whole numbers") + return new Q(xs.reduce((a, b) => gcd(a, b.n), 0n)) + }, + lcm: (...xs) => { + if (!xs.every((x) => x.int())) throw new Error("lcm takes whole numbers") + return new Q(xs.reduce((a, b) => (a === 0n || b.n === 0n ? 0n : abs(a * b.n) / gcd(a, b.n)), 1n)) + }, + fact: (a) => { + if (!a.int() || a.n < 0n || a.n > 5000n) throw new Error("fact takes a whole number from 0 to 5000") + let r = 1n + for (let i = 2n; i <= a.n; i++) r *= i + return new Q(r) + }, +} + +function tokens(src) { + const out = [] + const re = /\s*(?:(0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|(?:\d[\d_]*)?\.?\d[\d_]*(?:e[+-]?\d+)?)|(\*\*|[-+*/%^(),])|([a-z]+))/giy + let i = 0 + while (i < src.length) { + if (/^\s*$/.test(src.slice(i))) break + re.lastIndex = i + const m = re.exec(src) + if (!m) throw new Error(`can't read "${src.slice(i).trim().slice(0, 12)}" at ${i}`) + out.push(m[1] ? { num: m[1] } : m[2] ? { op: m[2] } : { name: m[3].toLowerCase() }) + i = re.lastIndex + } + return out +} + +// evaluate is the exact value of an arithmetic expression: + - * / % ^ (or +// **), parentheses, and abs floor ceil round trunc min max gcd lcm fact. +export function evaluate(src) { + const t = tokens(String(src)) + let p = 0 + const peek = () => t[p] + const op = (o) => peek()?.op === o && ++p + const expect = (o) => { + if (!op(o)) throw new Error(`expected "${o}"${peek() ? "" : " before the end"}`) + } + function expr() { + let a = term() + for (;;) { + if (op("+")) a = a.add(term()) + else if (op("-")) a = a.sub(term()) + else return a + } + } + function term() { + let a = unary() + for (;;) { + if (op("*")) a = a.mul(unary()) + else if (op("/")) a = a.div(unary()) + else if (op("%")) a = a.mod(unary()) + else return a + } + } + function unary() { + if (op("-")) return unary().neg() + if (op("+")) return unary() + return power() + } + function power() { + const a = atom() + if (op("^") || op("**")) return a.pow(unary()) // right-assoc: 2^3^2 = 2^9 + return a + } + function atom() { + const x = t[p++] + if (!x) throw new Error("the expression ends too soon") + if (x.num) return parseNumber(x.num) + if (x.op === "(") { + const a = expr() + expect(")") + return a + } + if (x.name) { + const f = FUNCS[x.name] + if (!f) throw new Error(`no function ${x.name}: ${Object.keys(FUNCS).join(", ")}`) + expect("(") + const args = [expr()] + while (op(",")) args.push(expr()) + expect(")") + if (["abs", "floor", "ceil", "round", "trunc", "fact"].includes(x.name) && args.length !== 1) throw new Error(`${x.name} takes one number`) + return f(...args) + } + throw new Error(`unexpected "${x.op}"`) + } + if (!t.length) throw new Error("no expression") + const v = expr() + if (p < t.length) throw new Error(`unexpected "${t[p].op ?? t[p].num ?? t[p].name}"`) + return v +} + +// answer is what a tool says of a value: the exact fraction, and the +// decimal to places (marked when it was rounded). +export function answer(v, places = 20) { + places = Math.max(0, Math.min(1000, Math.floor(places))) + const dec = v.decimal(places) + const out = { exact: v.exact(), decimal: dec.text } + if (!dec.exact) out.rounded = `to ${places} places` + return out +} + +// ---- units ------------------------------------------------------------------- + +// each unit's size in its kind's base unit, as an exact fraction +const UNITS = {} +const unit = (kind, factor, ...names) => { + for (const n of names) UNITS[n] = { kind, f: typeof factor === "string" ? parseNumber(factor) : factor } +} +// data, in bytes; a lowercase b is bits +unit("data", "0.125", "bit", "bits") +unit("data", "1", "B", "byte", "bytes") +for (const [i, p] of ["k", "M", "G", "T", "P", "E"].entries()) { + unit("data", new Q(1000n ** BigInt(i + 1)), `${p === "k" ? "kB" : p + "B"}`, `${p === "k" ? "KB" : p + "B"}`) + unit("data", new Q(1024n ** BigInt(i + 1)), `${p === "k" ? "K" : p}iB`) + unit("data", new Q(1000n ** BigInt(i + 1), 8n), `${p === "k" ? "kb" : p + "b"}`, `${p === "k" ? "Kb" : p + "b"}`, `${p === "k" ? "k" : p}bit`) +} +// time, in seconds +unit("time", "1e-9", "ns") +unit("time", "1e-6", "us", "µs") +unit("time", "1e-3", "ms") +unit("time", "1", "s", "sec", "second", "seconds") +unit("time", "60", "min", "minute", "minutes") +unit("time", "3600", "h", "hr", "hour", "hours") +unit("time", "86400", "d", "day", "days") +unit("time", "604800", "wk", "week", "weeks") +// length, in metres +unit("length", "1e-9", "nm") +unit("length", "1e-6", "um", "µm") +unit("length", "1e-3", "mm") +unit("length", "1e-2", "cm") +unit("length", "1", "m") +unit("length", "1e3", "km") +unit("length", "0.0254", "in", "inch") +unit("length", "0.3048", "ft", "foot", "feet") +unit("length", "0.9144", "yd") +unit("length", "1609.344", "mi", "mile") +unit("length", "1852", "nmi") +// typographic, in CSS pixels at 96 per inch +unit("css", "1", "px") +unit("css", new Q(4n, 3n), "pt") +unit("css", "16", "pc") +unit("css", "96", "in-css") +// mass, in grams +unit("mass", "1e-3", "mg") +unit("mass", "1", "g") +unit("mass", "1e3", "kg") +unit("mass", "1e6", "t") +unit("mass", "28.349523125", "oz") +unit("mass", "453.59237", "lb") +// angles, in turns: degrees and turns are exact, radians are not +unit("angle", new Q(1n, 360n), "deg") +unit("angle", "1", "turn") +unit("angle", new Q(1n, 400n), "grad") + +// temperatures are offsets, so each is a pair: to kelvin and back +const TEMPS = { + C: { to: (v) => v.add(new Q(27315n, 100n)), from: (k) => k.sub(new Q(27315n, 100n)) }, + F: { to: (v) => v.sub(new Q(32n)).mul(new Q(5n, 9n)).add(new Q(27315n, 100n)), from: (k) => k.sub(new Q(27315n, 100n)).mul(new Q(9n, 5n)).add(new Q(32n)) }, + K: { to: (v) => v, from: (k) => k }, +} + +// convert is value in from, in to. +export function convert(value, from, to) { + const v = typeof value === "string" ? evaluate(value) : parseNumber(String(value)) + const tf = from.replace(/^°/, "") + const tt = to.replace(/^°/, "") + if (TEMPS[tf] || TEMPS[tt]) { + if (!TEMPS[tf] || !TEMPS[tt]) throw new Error(`can't convert ${from} to ${to}`) + return TEMPS[tt].from(TEMPS[tf].to(v)) + } + const a = UNITS[from] + const b = UNITS[to] + if (!a) throw new Error(`no unit ${from}: ${Object.keys(UNITS).concat("C", "F", "K").join(" ")}`) + if (!b) throw new Error(`no unit ${to}: ${Object.keys(UNITS).concat("C", "F", "K").join(" ")}`) + if (a.kind !== b.kind) throw new Error(`${from} is ${a.kind} and ${to} is ${b.kind}`) + return v.mul(a.f).div(b.f) +} + +// ---- dates ------------------------------------------------------------------- + +const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + +// offsetMs is tz's offset from UTC at instant ms. +function offsetMs(ms, tz) { + const f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }) + const p = Object.fromEntries(f.formatToParts(new Date(ms)).map((x) => [x.type, x.value])) + const wall = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second) + return wall - Math.floor(ms / 1000) * 1000 +} + +// wallParts is the calendar date and time at ms in tz ("UTC" when none). +function wallParts(ms, tz) { + const d = new Date(ms + (tz ? offsetMs(ms, tz) : 0)) + return { y: d.getUTCFullYear(), mo: d.getUTCMonth(), d: d.getUTCDate(), h: d.getUTCHours(), mi: d.getUTCMinutes(), s: d.getUTCSeconds(), ms: d.getUTCMilliseconds() } +} + +// fromWall is the instant a wall time in tz names. +function fromWall(w, tz) { + const wall = Date.UTC(w.y, w.mo, w.d, w.h, w.mi, w.s, w.ms) + if (!tz) return wall + let t = wall - offsetMs(wall, tz) + t = wall - offsetMs(t, tz) + return t +} + +// parseDate is an instant: "now", unix seconds or milliseconds, or an ISO +// 8601 date or date-time. One with no offset is a wall time in tz (UTC +// when tz is ""). +export function parseDate(src, tz, now = Date.now()) { + const s = String(src ?? "now").trim() + if (s === "" || s.toLowerCase() === "now") return now + if (/^-?\d+(\.\d+)?$/.test(s)) { + const n = Number(s) + return Math.abs(n) < 1e11 ? Math.round(n * 1000) : Math.round(n) + } + const m = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?)?\s*(Z|[+-]\d{2}:?\d{2})?$/i.exec(s) + if (!m) throw new Error(`not a date: ${src} (ISO 8601, unix seconds or ms, or "now")`) + const w = { y: +m[1], mo: +m[2] - 1, d: +m[3], h: +(m[4] ?? 0), mi: +(m[5] ?? 0), s: +(m[6] ?? 0), ms: Math.floor(+((m[7] ?? "0") + "00").slice(0, 3)) } + const check = new Date(Date.UTC(w.y, w.mo, w.d)) + if (check.getUTCMonth() !== w.mo || check.getUTCDate() !== w.d || w.h > 23 || w.mi > 59 || w.s > 60) throw new Error(`no such date: ${src}`) + if (!m[8]) return fromWall(w, tz) + const z = m[8].toUpperCase() + if (z === "Z") return fromWall(w, "") + const sign = z[0] === "-" ? -1 : 1 + const [, hh, mm] = /^[+-](\d{2}):?(\d{2})$/.exec(z) + return fromWall(w, "") - sign * (+hh * 3600000 + +mm * 60000) +} + +const DUR = { y: "y", yr: "y", year: "y", years: "y", mo: "mo", month: "mo", months: "mo", w: "w", wk: "w", week: "w", weeks: "w", d: "d", day: "d", days: "d", h: "h", hr: "h", hour: "h", hours: "h", m: "m", min: "m", minute: "m", minutes: "m", s: "s", sec: "s", second: "s", seconds: "s", ms: "ms" } + +// parseDuration reads "3d 4h", "-90m", "1y2mo", "2 weeks" or ISO 8601's +// "P1Y2M3DT4H5M6S" into its parts. +export function parseDuration(src) { + let s = String(src).trim() + const out = { y: 0, mo: 0, w: 0, d: 0, h: 0, m: 0, s: 0, ms: 0 } + const iso = /^([+-])?P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/i.exec(s) + if (iso && s.length > 1 + (iso[1] ? 1 : 0)) { + const k = iso[1] === "-" ? -1 : 1 + ;[out.y, out.mo, out.w, out.d, out.h, out.m] = [2, 3, 4, 5, 6, 7].map((i) => k * +(iso[i] ?? 0)) + const sec = +(iso[8] ?? 0) + out.s = k * Math.trunc(sec) + out.ms = k * Math.round((sec % 1) * 1000) + return out + } + let sign = 1 + if (/^[+-]/.test(s)) { + sign = s[0] === "-" ? -1 : 1 + s = s.slice(1) + } + const re = /\s*(\d+(?:\.\d+)?)\s*([a-z]+)\s*,?/giy + let i = 0 + let any = false + while (i < s.length) { + re.lastIndex = i + const m = re.exec(s) + if (!m) throw new Error(`not a duration: ${src} (like "3d 4h", "-90m", "1y2mo" or "P1DT2H")`) + const u = DUR[m[2].toLowerCase()] ?? (m[2] === "M" ? "mo" : undefined) + if (!u) throw new Error(`no duration unit ${m[2]}: y mo w d h m s ms`) + const n = Number(m[1]) + if (["y", "mo"].includes(u) && !Number.isInteger(n)) throw new Error(`${m[0].trim()}: years and months are whole`) + out[u] += sign * n + any = true + i = re.lastIndex + } + if (!any) throw new Error(`not a duration: ${src}`) + return out +} + +// addDuration is ms plus dur, years, months, weeks and days on tz's +// calendar (a month on from Jan 31 is the last of February), the rest +// in elapsed time. +export function addDuration(ms, dur, tz) { + const w = wallParts(ms, tz) + const months = w.mo + dur.y * 12 + dur.mo + const y = w.y + Math.floor(months / 12) + const mo = ((months % 12) + 12) % 12 + const last = new Date(Date.UTC(y, mo + 1, 0)).getUTCDate() + const day = Math.min(w.d, last) + // whole days, as the calendar's days, then fractions of one as time + const days = dur.w * 7 + dur.d + const wholeDays = Math.trunc(days) + const base = fromWall({ ...w, y, mo, d: day + wholeDays }, tz) + return base + Math.round((days - wholeDays) * 86400000 + dur.h * 3600000 + dur.m * 60000 + dur.s * 1000 + dur.ms) +} + +const pad = (n, l = 2) => String(n).padStart(l, "0") + +// describe is what the date tool says of an instant in tz. +export function describe(ms, tz) { + if (!Number.isFinite(ms) || Math.abs(ms) > 8.64e15) throw new Error("the date is out of range") + const w = wallParts(ms, tz) + const off = tz ? offsetMs(ms, tz) / 60000 : 0 + const offText = off === 0 && !tz ? "Z" : `${off < 0 ? "-" : "+"}${pad(Math.floor(Math.abs(off) / 60))}:${pad(Math.abs(off) % 60)}` + const local = `${pad(w.y, 4)}-${pad(w.mo + 1)}-${pad(w.d)}T${pad(w.h)}:${pad(w.mi)}:${pad(w.s)}${w.ms ? "." + pad(w.ms, 3) : ""}${offText}` + const day0 = Date.UTC(w.y, w.mo, w.d) + const dayOfYear = Math.round((day0 - Date.UTC(w.y, 0, 1)) / 86400000) + 1 + // ISO week: the week with the year's first Thursday is week 1 + const wd = (new Date(day0).getUTCDay() + 6) % 7 + const thu = new Date(day0 + (3 - wd) * 86400000) + const isoWeek = Math.floor((thu - Date.UTC(thu.getUTCFullYear(), 0, 1)) / (7 * 86400000)) + 1 + const out = { iso: new Date(ms).toISOString() } + if (tz) out.local = local + if (tz) out.timeZone = tz + Object.assign(out, { weekday: WEEKDAYS[new Date(day0).getUTCDay()], unix: Math.floor(ms / 1000), unixMs: ms, dayOfYear, isoWeek: `${thu.getUTCFullYear()}-W${pad(isoWeek)}` }) + return out +} + +// between is the time from a to b: in elapsed units, and as calendar +// years, months and days in tz. +export function between(a, b, tz) { + const sign = b < a ? -1 : 1 + const [lo, hi] = sign < 0 ? [b, a] : [a, b] + const ms = hi - lo + // the calendar count: the most whole months that fit, then days + const wl = wallParts(lo, tz) + const wh = wallParts(hi, tz) + let months = (wh.y - wl.y) * 12 + (wh.mo - wl.mo) + while (months > 0 && addDuration(lo, { y: 0, mo: months, w: 0, d: 0, h: 0, m: 0, s: 0, ms: 0 }, tz) > hi) months-- + let at = addDuration(lo, { y: 0, mo: months, w: 0, d: 0, h: 0, m: 0, s: 0, ms: 0 }, tz) + let days = 0 + while (addDuration(at, { y: 0, mo: 0, w: 0, d: 1, h: 0, m: 0, s: 0, ms: 0 }, tz) <= hi) { + at = addDuration(at, { y: 0, mo: 0, w: 0, d: 1, h: 0, m: 0, s: 0, ms: 0 }, tz) + days++ + } + const rest = hi - at + const parts = [] + const y = Math.floor(months / 12) + if (y) parts.push(`${y}y`) + if (months % 12) parts.push(`${months % 12}mo`) + if (days) parts.push(`${days}d`) + const h = Math.floor(rest / 3600000) + const m = Math.floor((rest % 3600000) / 60000) + const s = Math.floor((rest % 60000) / 1000) + const r = rest % 1000 + if (h) parts.push(`${h}h`) + if (m) parts.push(`${m}m`) + if (s) parts.push(`${s}s`) + if (r) parts.push(`${r}ms`) + const k = (x) => sign * x + return { + calendar: (sign < 0 ? "-" : "") + (parts.join(" ") || "0s"), + days: k(ms / 86400000), + hours: k(ms / 3600000), + minutes: k(ms / 60000), + seconds: k(ms / 1000), + ms: k(ms), + } +} + +// checkZone is tz if the system knows it. +export function checkZone(tz) { + if (!tz) return "" + try { + new Intl.DateTimeFormat("en-US", { timeZone: tz }) + } catch { + throw new Error(`no time zone ${tz}: an IANA name such as Europe/Berlin or Asia/Shanghai`) + } + return tz +} diff --git a/packages/calc/calc.test.mjs b/packages/calc/calc.test.mjs new file mode 100644 index 0000000..86fd7ed --- /dev/null +++ b/packages/calc/calc.test.mjs @@ -0,0 +1,110 @@ +import { expect, test } from "bun:test" +import { CalcTools } from "./index.mjs" + +const { tool } = await CalcTools({}) +// the host calls execute(args, ctx); these tools need nothing from ctx +const call = (name, args) => tool[name].execute(args, { agent: "test", abort: AbortSignal.timeout(5000) }) + +test("gives three tools, each with a JSON Schema and an execute", () => { + expect(Object.keys(tool).sort()).toEqual(["convert", "date", "eval"]) + for (const [name, t] of Object.entries(tool)) { + expect(name).toMatch(/^[A-Za-z0-9_-]{1,48}$/) + expect(t.description.length).toBeGreaterThan(40) + expect(t.args.type).toBe("object") + expect(typeof t.execute).toBe("function") + } +}) + +test("eval answers exactly where floating point doesn't", async () => { + expect(await call("eval", { expression: "0.1 + 0.2" })).toEqual({ exact: "3/10", decimal: "0.3" }) + expect(await call("eval", { expression: "2^64" })).toEqual({ exact: "18446744073709551616", decimal: "18446744073709551616" }) + expect(await call("eval", { expression: "1/3", places: 5 })).toEqual({ exact: "1/3", decimal: "0.33333", rounded: "to 5 places" }) + expect(await call("eval", { expression: "2/3", places: 3 })).toMatchObject({ decimal: "0.667" }) + expect(await call("eval", { expression: "-2^2" })).toMatchObject({ exact: "-4" }) + expect(await call("eval", { expression: "2^3^2" })).toMatchObject({ exact: "512" }) + expect(await call("eval", { expression: "2 ** -2" })).toMatchObject({ exact: "1/4", decimal: "0.25" }) + expect(await call("eval", { expression: "(17.5 * 3 - 2) / 7" })).toMatchObject({ exact: "101/14" }) + expect(await call("eval", { expression: "-7 % 3" })).toMatchObject({ exact: "-1" }) + expect(await call("eval", { expression: "0xff + 0b11 + 0o10 + 1_000" })).toMatchObject({ exact: "1266" }) + expect(await call("eval", { expression: "6.02e23 / 1e-3" })).toMatchObject({ exact: "602000000000000000000000000" }) + expect(await call("eval", { expression: "gcd(1071, 462) + lcm(4, 6) + max(1, 7/2) + round(-2.5) + floor(-0.5)" })).toMatchObject({ exact: "65/2" }) + expect(await call("eval", { expression: "fact(20)" })).toMatchObject({ exact: "2432902008176640000" }) +}) + +test("eval says what is wrong instead of guessing", async () => { + await expect(call("eval", { expression: "1/0" })).rejects.toThrow("division by zero") + await expect(call("eval", { expression: "2^(1/2)" })).rejects.toThrow("whole number") + await expect(call("eval", { expression: "(1 + 2" })).rejects.toThrow('expected ")"') + await expect(call("eval", { expression: "sqrt(2)" })).rejects.toThrow("no function sqrt") + await expect(call("eval", { expression: "1 +" })).rejects.toThrow("ends too soon") + await expect(call("eval", { expression: "2 $ 3" })).rejects.toThrow("can't read") + await expect(call("eval", { expression: "2^1000000" })).rejects.toThrow("too big") + await expect(call("eval", {})).rejects.toThrow("expression is a string") +}) + +test("convert is exact across data, time, length, CSS, mass, angle and temperature", async () => { + expect(await call("convert", { value: "1", from: "GiB", to: "MB" })).toEqual({ exact: "16777216/15625", decimal: "1073.741824", unit: "MB" }) + expect(await call("convert", { value: "100", from: "Mb", to: "MB" })).toMatchObject({ exact: "25/2" }) + expect(await call("convert", { value: "3*1024", from: "KiB", to: "MiB" })).toMatchObject({ exact: "3" }) + expect(await call("convert", { value: "90", from: "min", to: "h" })).toMatchObject({ exact: "3/2" }) + expect(await call("convert", { value: "1", from: "mi", to: "km" })).toMatchObject({ decimal: "1.609344" }) + expect(await call("convert", { value: "12", from: "pt", to: "px" })).toMatchObject({ exact: "16" }) + expect(await call("convert", { value: "1", from: "lb", to: "kg" })).toMatchObject({ decimal: "0.45359237" }) + expect(await call("convert", { value: "90", from: "deg", to: "turn" })).toMatchObject({ exact: "1/4" }) + expect(await call("convert", { value: "98.6", from: "F", to: "C" })).toMatchObject({ exact: "37" }) + expect(await call("convert", { value: "-40", from: "°C", to: "°F" })).toMatchObject({ exact: "-40" }) + expect(await call("convert", { value: "0", from: "K", to: "C" })).toMatchObject({ decimal: "-273.15" }) + await expect(call("convert", { value: "1", from: "kg", to: "m" })).rejects.toThrow("kg is mass and m is length") + await expect(call("convert", { value: "1", from: "furlong", to: "m" })).rejects.toThrow("no unit furlong") + await expect(call("convert", { value: "1", from: "C", to: "m" })).rejects.toThrow("can't convert") +}) + +test("date describes a date in UTC, or in a time zone", async () => { + expect(await call("date", { date: "2026-10-16" })).toEqual({ + iso: "2026-10-16T00:00:00.000Z", weekday: "Friday", unix: 1792108800, unixMs: 1792108800000, dayOfYear: 289, isoWeek: "2026-W42", + }) + // a wall time in a zone, and an offset given in the date itself + expect(await call("date", { date: "2026-10-16T09:30", timeZone: "Asia/Shanghai" })).toMatchObject({ iso: "2026-10-16T01:30:00.000Z", local: "2026-10-16T09:30:00+08:00" }) + expect(await call("date", { date: "2026-10-16T09:30+08:00" })).toMatchObject({ iso: "2026-10-16T01:30:00.000Z" }) + // unix seconds and milliseconds + expect(await call("date", { date: "1792108800" })).toMatchObject({ iso: "2026-10-16T00:00:00.000Z" }) + expect(await call("date", { date: "1792108800000" })).toMatchObject({ iso: "2026-10-16T00:00:00.000Z" }) + // ISO weeks at a year's edge: 2027-01-01 is a Friday, in 2026's week 53 + expect(await call("date", { date: "2027-01-01" })).toMatchObject({ isoWeek: "2026-W53", weekday: "Friday" }) + expect(await call("date", { date: "2024-12-30" })).toMatchObject({ isoWeek: "2025-W01" }) + // now is the default + const before = Date.now() + const now = await call("date", {}) + expect(now.unixMs).toBeGreaterThanOrEqual(before) + expect(now.unixMs - before).toBeLessThan(60_000) +}) + +test("date adds on the calendar: month ends and a DST change", async () => { + expect(await call("date", { date: "2026-01-31", add: "1mo" })).toMatchObject({ iso: "2026-02-28T00:00:00.000Z" }) + expect(await call("date", { date: "2024-02-29", add: "1y" })).toMatchObject({ iso: "2025-02-28T00:00:00.000Z" }) + expect(await call("date", { date: "2026-10-16T12:00Z", add: "-90m" })).toMatchObject({ iso: "2026-10-16T10:30:00.000Z" }) + expect(await call("date", { date: "2026-10-16", add: "P1DT2H" })).toMatchObject({ iso: "2026-10-17T02:00:00.000Z" }) + expect(await call("date", { date: "2026-10-16", add: "2 weeks 1d" })).toMatchObject({ iso: "2026-10-31T00:00:00.000Z" }) + // New York springs forward on 2026-03-08: a day later is noon again, 23 hours on + const r = await call("date", { date: "2026-03-07T12:00", add: "1d", timeZone: "America/New_York" }) + expect(r).toMatchObject({ local: "2026-03-08T12:00:00-04:00", iso: "2026-03-08T16:00:00.000Z" }) + const d = await call("date", { date: "2026-03-07T12:00", add: "24h", timeZone: "America/New_York" }) + expect(d.local).toBe("2026-03-08T13:00:00-04:00") +}) + +test("date counts the time between two dates", async () => { + const r = await call("date", { date: "2024-02-29", to: "2026-10-16T10:30Z" }) + expect(r.between).toEqual({ calendar: "2y 7mo 17d 10h 30m", days: 960.4375, hours: 23050.5, minutes: 1383030, seconds: 82981800, ms: 82981800000 }) + expect(r.to.weekday).toBe("Friday") + const back = await call("date", { date: "2026-10-16", to: "2026-01-01" }) + expect(back.between).toMatchObject({ calendar: "-9mo 15d", days: -288 }) + expect((await call("date", { date: "2026-10-16", to: "2026-10-16" })).between.calendar).toBe("0s") +}) + +test("date says what is wrong", async () => { + await expect(call("date", { date: "2026-02-30" })).rejects.toThrow("no such date") + await expect(call("date", { date: "next tuesday" })).rejects.toThrow("not a date") + await expect(call("date", { date: "2026-10-16", add: "3 fortnights" })).rejects.toThrow("no duration unit") + await expect(call("date", { date: "2026-10-16", add: "1.5mo" })).rejects.toThrow("whole") + await expect(call("date", { timeZone: "Mars/Olympus" })).rejects.toThrow("no time zone") +}) diff --git a/packages/calc/index.mjs b/packages/calc/index.mjs new file mode 100644 index 0000000..b0ce7c7 --- /dev/null +++ b/packages/calc/index.mjs @@ -0,0 +1,81 @@ +// Exact arithmetic, unit conversion and date math, as tools magpie offers +// every agent (its MCP server /mcp/magpie/tools). The arguments are JSON +// Schema, so the package needs no zod and no other dependency. +import { addDuration, answer, between, checkZone, convert, describe, evaluate, parseDate, parseDuration } from "./calc.mjs" + +const str = (v, name) => { + if (typeof v !== "string" && typeof v !== "number") throw new Error(`${name} is a string`) + return String(v) +} +const places = (v) => (v === undefined ? 20 : Number.isFinite(+v) ? +v : 20) + +export const CalcTools = async () => ({ + tool: { + eval: { + description: + "Evaluates an arithmetic expression exactly, with no floating point: 0.1+0.2 is 3/10, 2^64 is every digit. " + + "Takes + - * / % ^ (or **), parentheses, decimals, 1e9, 0x/0b/0o literals, 1_000, and abs floor ceil round trunc min max gcd lcm fact. " + + "Answers the exact fraction and the decimal; `rounded` says when the decimal was cut. Use it instead of doing arithmetic in your head.", + args: { + type: "object", + properties: { + expression: { type: "string", description: "e.g. (17.5 * 3 - 2) / 7, 2^100, gcd(1071, 462)" }, + places: { type: "number", description: "decimal places to write (default 20, at most 1000)" }, + }, + required: ["expression"], + }, + async execute(args) { + return answer(evaluate(str(args.expression, "expression")), places(args.places)) + }, + }, + convert: { + description: + "Converts a quantity between units exactly. Data: bit B kB MB GB TB (1000s), KiB MiB GiB TiB (1024s), kb Mb Gb (bits). " + + "Time: ns us ms s min h d wk. Length: nm um mm cm m km in ft yd mi nmi. CSS: px pt pc. Mass: mg g kg t oz lb. " + + "Angle: deg turn grad. Temperature: C F K. The value can be an expression (e.g. 3*1024).", + args: { + type: "object", + properties: { + value: { type: "string", description: "the amount, e.g. 1.5 or 3*1024" }, + from: { type: "string", description: "its unit, e.g. GiB" }, + to: { type: "string", description: "the unit wanted, e.g. MB" }, + places: { type: "number", description: "decimal places to write (default 20)" }, + }, + required: ["value", "from", "to"], + }, + async execute(args) { + const v = convert(str(args.value, "value"), str(args.from, "from").trim(), str(args.to, "to").trim()) + return { ...answer(v, places(args.places)), unit: String(args.to).trim() } + }, + }, + date: { + description: + "Date and time math on the real calendar. Give `date` (ISO 8601, unix seconds or ms, or now) and get its weekday, ISO week, day of year and unix time; " + + "add `add` (e.g. \"3d 4h\", \"-90m\", \"1y2mo\", \"P1DT2H\": years, months and days on the calendar, Jan 31 + 1mo is the last of February); " + + "give `to` for the time between the two, in days, hours, seconds and calendar years/months/days. " + + "`timeZone` (IANA, e.g. Asia/Shanghai) reads dates with no offset as that zone's wall time and shows the local time; without it they are UTC.", + args: { + type: "object", + properties: { + date: { type: "string", description: "the date: 2026-10-16, 2026-10-16T09:30, 2026-10-16T09:30+08:00, 1760000000, or now (the default)" }, + add: { type: "string", description: "a duration to add to date, e.g. 3d 4h, -2w, 1y2mo, P1M" }, + to: { type: "string", description: "a second date: answers the time from date (after add) to it" }, + timeZone: { type: "string", description: "an IANA time zone, e.g. Europe/Berlin" }, + }, + }, + async execute(args) { + const tz = checkZone(args.timeZone === undefined ? "" : str(args.timeZone, "timeZone").trim()) + const now = Date.now() + let t = parseDate(args.date === undefined ? "now" : str(args.date, "date"), tz, now) + if (args.add !== undefined && args.add !== "") t = addDuration(t, parseDuration(str(args.add, "add")), tz) + const out = describe(t, tz) + if (args.to !== undefined && args.to !== "") { + const u = parseDate(str(args.to, "to"), tz, now) + out.to = describe(u, tz) + out.between = between(t, u, tz) + } + return out + }, + }, + }, +}) diff --git a/packages/calc/package.json b/packages/calc/package.json new file mode 100644 index 0000000..dda9f37 --- /dev/null +++ b/packages/calc/package.json @@ -0,0 +1,11 @@ +{ + "name": "@magpie-community/tools-calc", + "version": "0.1.0", + "description": "Exact arithmetic, unit conversion and calendar date math as tools for every coding agent, through magpie's MCP server", + "type": "module", + "main": "./index.mjs", + "files": ["index.mjs", "calc.mjs", "README.md"], + "keywords": ["magpie", "magpie-tools", "mcp", "opencode", "opencode-plugin", "calculator", "units", "dates"], + "license": "MIT", + "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/calc" } +}