Compare commits

..

4 Commits

Author SHA1 Message Date
javis-bot
c3d1b6a794 chore(app): version 0.1.55
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:52:41 +09:00
javis-bot
4cdfecee82 fix(tools): calculator reads each written number from its text
The float ast had already rounded each literal, so ceil(1.0000000000000001)
gave 1, 1e-400/1e-400 was refused as a division by zero and 1e400-1e400
as out of range. Float literals are now read from the expression text with
Decimal (written numbers past 1e4000 are refused unparsed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:52:41 +09:00
javis-bot
c35737e33f chore(app): version 0.1.54
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:45:54 +09:00
javis-bot
fc4b77f826 fix(tools): calculator keeps decimals exact as written
Numbers were binary floats, so ceil(1.1*100) gave 111 and
floor(0.3/0.1) gave 2. Literals are now exact fractions as written
(1.1 is 11/10): + - * / // % and whole-number powers have no rounding
error; only math functions and fractional powers use floats. The power
size guard covers exact fractions too (2^-100000 is refused, not 0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:45:54 +09:00
7 changed files with 72 additions and 25 deletions

2
app/Cargo.lock generated
View File

@@ -1520,7 +1520,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jarvis-app"
version = "0.1.53"
version = "0.1.55"
dependencies = [
"async-trait",
"base64 0.22.1",

View File

@@ -1,6 +1,6 @@
[package]
name = "jarvis-app"
version = "0.1.53"
version = "0.1.55"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 Windows app core: Discord voice, voice worker supervisor, chat channels"

4
app/shell/Cargo.lock generated
View File

@@ -2637,7 +2637,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jarvis-app"
version = "0.1.53"
version = "0.1.55"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2666,7 +2666,7 @@ dependencies = [
[[package]]
name = "jarvis-shell"
version = "0.1.53"
version = "0.1.55"
dependencies = [
"jarvis-app",
"serde_json",

View File

@@ -1,6 +1,6 @@
[package]
name = "jarvis-shell"
version = "0.1.53"
version = "0.1.55"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"

View File

@@ -1,12 +1,16 @@
"""calculator tool: exact arithmetic for the reply model (calculator.spec.md).
The expression is parsed with ``ast`` and only numbers, + - * / // % **, a few math functions and
pi/e are evaluated; anything else is refused, never run as code.
pi/e are evaluated; anything else is refused, never run as code. Numbers are exact fractions as
written (1.1 is 11/10), so + - * / // % and whole-number powers have no binary rounding; only the
math functions and fractional powers work in floats.
"""
import ast
import math
import operator
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from typing import Any, Dict, Optional
from ...debug import debug_log
@@ -14,8 +18,10 @@ from ..base import Tool, ToolContext
from ..types import ToolExecutionResult
MAX_EXPRESSION_CHARS = 200
# Largest whole-number power worked out exactly (about 3000 digits); bigger ones are refused.
# Largest exact power worked out (about 3000 digits); bigger ones are refused.
_MAX_POWER_BITS = 10_000
# Largest power of ten a written number may carry (1e4000); bigger ones are refused unparsed.
_MAX_LITERAL_EXPONENT = 4000
_BINARY = {
ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
@@ -37,9 +43,11 @@ class _Refused(ValueError):
def _power(base, exponent):
if isinstance(base, int) and isinstance(exponent, int) and exponent >= 0:
if abs(base) > 1 and abs(base).bit_length() * exponent > _MAX_POWER_BITS:
raise _Refused("the result is too large")
if isinstance(base, (int, Fraction)) and isinstance(exponent, (int, Fraction)) and exponent == int(exponent):
base, exponent = Fraction(base), int(exponent)
size = max(abs(base.numerator).bit_length(), base.denominator.bit_length())
if size > 1 and size * abs(exponent) > _MAX_POWER_BITS:
raise _Refused("the result has too many digits")
return base ** exponent
result = float(base) ** float(exponent)
if isinstance(result, complex):
@@ -47,30 +55,45 @@ def _power(base, exponent):
return result
def _eval(node):
def _number(node, text):
if type(node.value) is int:
return Fraction(node.value)
# A float as written in the expression, not the float ast already rounded it to: 1.1 is 11/10,
# 1.0000000000000001 stays above 1, and 1e-400 is not 0.
try:
written = Decimal(ast.get_source_segment(text, node) or "")
except InvalidOperation:
return Fraction(repr(node.value))
if not written.is_finite() or abs(written.adjusted()) > _MAX_LITERAL_EXPONENT:
raise _Refused("a number has too many digits")
return Fraction(written)
def _eval(node, text):
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
return node.value
return _number(node, text)
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
return _power(_eval(node.left), _eval(node.right))
return _power(_eval(node.left, text), _eval(node.right, text))
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
return _BINARY[type(node.op)](_eval(node.left), _eval(node.right))
return _BINARY[type(node.op)](_eval(node.left, text), _eval(node.right, text))
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
return _UNARY[type(node.op)](_eval(node.operand))
return _UNARY[type(node.op)](_eval(node.operand, text))
if isinstance(node, ast.Name) and node.id in _CONSTANTS:
return _CONSTANTS[node.id]
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCTIONS
and not node.keywords):
return _FUNCTIONS[node.func.id](*[_eval(a) for a in node.args])
return _FUNCTIONS[node.func.id](*[_eval(a, text) for a in node.args])
raise _Refused("only numbers, + - * / ^ %, parentheses, "
+ ", ".join([*_FUNCTIONS, *_CONSTANTS]) + " are allowed")
def _readable(value) -> str:
if isinstance(value, int):
if isinstance(value, (int, Fraction)) and value == int(value):
try:
return str(value)
return str(int(value))
except ValueError: # more digits than Python turns into text
raise _Refused("the result is too large")
raise _Refused("the result has too many digits")
value = float(value)
if not math.isfinite(value):
raise _Refused("the result is not a finite number")
if value.is_integer() and abs(value) < 1e15:
@@ -92,7 +115,7 @@ def calculate(expression: str) -> str:
except (SyntaxError, ValueError, RecursionError, MemoryError):
raise _Refused("the expression is not valid math")
try:
return _readable(_eval(tree.body))
return _readable(_eval(tree.body, text))
except ZeroDivisionError:
raise _Refused("it divides by zero")
except OverflowError:

View File

@@ -11,12 +11,19 @@ idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis,
float numbers, `+ - * / // % **`, unary `+ -`, parentheses, the functions `abs round min max sqrt
exp log ln log10 log2 sin cos tan ceil floor` (positional values only) and the constants `pi e`.
Names, attributes, strings, lists, keyword values and anything else are refused.
- **Bounded.** At most 200 characters. A whole-number power whose result would be over about
10,000 bits (about 3000 digits) is refused before it is worked out, and a float that overflows
- **Bounded.** At most 200 characters. An exact power whose result would be over about 10,000
bits (about 3000 digits, also tiny ones such as `2^-100000`) is refused before it is worked out, and a float that overflows
or is not finite is refused, so no expression can hang the worker.
- **Exact as written.** Numbers are exact fractions as written (`1.1` is 11/10, not the nearest
binary float), so `+ - * / // %` and whole-number powers have no rounding error: `ceil(1.1*100)`
is 110 and `floor(0.3/0.1)` is 3. Only the math functions, `pi`, `e` and fractional powers work
in floats.
A number is read from its written text, so decimals longer than 17 digits and exponents beyond
the float range stay as written too (`ceil(1.0000000000000001)` is 2, `1e-400/1e-400` is 1); a
written number past 1e4000 (or below 1e-4000) is refused.
- **Signs people write.** `^` is a power, `×` multiplies, `÷` divides, `−` is a minus.
- **Raw data.** No LLM call. The answer is `<expression as given> = <value>`: whole numbers exact,
a float that is a whole number below 10^15 as that whole number, other floats to 10 significant
a float that is a whole number below 10^15 as that whole number, other values to 10 significant
digits. The reply model says it in the user's language.
- **Errors the model can act on.** A refused or failed expression (division by zero, a function
outside its range, not valid math, too long, too large) comes back as `success=False` with the
@@ -34,7 +41,7 @@ idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis,
## Tests
- `tests/test_calculator_tool.py`: exact values, readable fractions, refused code and non-math,
- `tests/test_calculator_tool.py`: exact values, decimals exact as written, readable fractions, refused code and non-math,
huge powers failing fast, bad expressions, offered and run through the registry.
- `evals/test_calculator_tool.py`: a four-digit product and a fractional power use the tool and
the answer carries the exact value; an unrelated question does not use it (qwen3:8b, v2 setup:

View File

@@ -34,6 +34,23 @@ def test_it_gives_the_exact_value(expression, expected):
assert value_of(run(expression)) == expected
@pytest.mark.unit
@pytest.mark.parametrize("expression, expected", [
("ceil(1.1*100)", "110"),
("floor(0.3/0.1)", "3"),
("0.1+0.2", "0.3"),
("1.1*3 - 3.3", "0"),
("10.5 % 0.1", "0"),
("2.675*100 // 1", "267"),
("0.5^-2", "4"),
("ceil(1.0000000000000001)", "2"),
("1e-400/1e-400", "1"),
("1e400-1e400", "0"),
])
def test_decimals_are_exact_as_written(expression, expected):
assert value_of(run(expression)) == expected
@pytest.mark.unit
def test_fractions_are_rounded_to_a_readable_length():
got = float(value_of(run("1.07^12")))
@@ -61,7 +78,7 @@ def test_anything_but_arithmetic_is_refused(expression):
@pytest.mark.unit
@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300"])
@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300", "1.5**100000", "2**-100000", "1e99999999", "1e-99999999*2"])
def test_a_huge_power_fails_fast_instead_of_hanging(expression):
start = time.monotonic()
r = run(expression)