🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 style: add calculator builtin tool (#11715)
Zhijie Hec2483f97a077
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 3d48a2b0a9a..8c05734ac22 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -724,6 +724,9 @@"tools.builtins.lobe-artifacts.description": "Generate and preview interactive UI components and visualizations","tools.builtins.lobe-artifacts.readme": "Generate and live-preview interactive UI components, data visualizations, charts, SVG graphics, and web applications. Create rich visual content that users can interact with directly.","tools.builtins.lobe-artifacts.title": "Artifacts",+ "tools.builtins.lobe-calculator.description": "Perform mathematical calculations, solve equations, and work with symbolic expressions",+ "tools.builtins.lobe-calculator.readme": "Advanced mathematical calculator supporting basic arithmetic, algebraic equations, calculus operations, and symbolic math. Includes base conversion, equation solving, differentiation, integration, and more.",+ "tools.builtins.lobe-calculator.title": "Calculator","tools.builtins.lobe-cloud-sandbox.description": "Execute code, run commands, and manage files in a secure cloud environment","tools.builtins.lobe-cloud-sandbox.readme": "Execute Python, JavaScript, and TypeScript code in an isolated cloud environment. Run shell commands, manage files, search content with regex, and export results securely.","tools.builtins.lobe-cloud-sandbox.title": "Cloud Sandbox",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex fa8ac8b0527..2ee577af992 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -724,6 +724,9 @@"tools.builtins.lobe-artifacts.description": "生成并预览交互式 UI 组件和可视化内容","tools.builtins.lobe-artifacts.readme": "生成并实时预览交互式 UI 组件、数据可视化、图表、SVG 图形和 Web 应用。创建用户可直接交互的丰富可视化内容。","tools.builtins.lobe-artifacts.title": "Artifacts",+ "tools.builtins.lobe-calculator.description": "执行数学计算、解方程,并处理符号表达式",+ "tools.builtins.lobe-calculator.readme": "高级数学计算器,支持基础算术、代数方程、微积分运算和符号数学。包括进制转换、方程求解、微分、积分等更多功能。",+ "tools.builtins.lobe-calculator.title": "计算器","tools.builtins.lobe-cloud-sandbox.description": "在安全的云端环境中执行代码、运行命令和管理文件","tools.builtins.lobe-cloud-sandbox.readme": "在隔离的云端环境中执行 Python、JavaScript 和 TypeScript 代码。运行 Shell 命令、管理文件、使用正则搜索内容并安全导出结果。","tools.builtins.lobe-cloud-sandbox.title": "云沙盒",diff --git a/package.json b/package.jsonindex ded22f3a225..4603520657a 100644--- a/package.json+++ b/package.json@@ -188,6 +188,7 @@"@lobechat/builtin-agents": "workspace:*","@lobechat/builtin-skills": "workspace:*","@lobechat/builtin-tool-agent-builder": "workspace:*",+ "@lobechat/builtin-tool-calculator": "workspace:*","@lobechat/builtin-tool-cloud-sandbox": "workspace:*","@lobechat/builtin-tool-group-agent-builder": "workspace:*","@lobechat/builtin-tool-group-management": "workspace:*",diff --git a/packages/builtin-tool-calculator/package.json b/packages/builtin-tool-calculator/package.jsonnew file mode 100644index 00000000000..bbb64e95305--- /dev/null+++ b/packages/builtin-tool-calculator/package.json@@ -0,0 +1,27 @@+{+ "name": "@lobechat/builtin-tool-calculator",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executor": "./src/executor/index.ts"+ },+ "main": "./src/index.ts",+ "dependencies": {+ "@lobechat/prompts": "workspace:*",+ "@thi.ng/base-n": "^2.7.58",+ "mathjs": "^15.1.0",+ "nerdamer-prime": "^1.3.1"+ },+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "@lobehub/ui": "^4",+ "antd-style": "*",+ "lucide-react": "*",+ "react": "*",+ "react-i18next": "*"+ }+}diff --git a/packages/builtin-tool-calculator/src/ExecutionRuntime/index.ts b/packages/builtin-tool-calculator/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..3e8847dd617--- /dev/null+++ b/packages/builtin-tool-calculator/src/ExecutionRuntime/index.ts@@ -0,0 +1,293 @@+import { type BuiltinServerRuntimeOutput } from '@lobechat/types';++import { calculatorExecutor } from '../executor';+import {+ type BaseParams,+ type BaseState,+ type CalculateParams,+ type CalculateState,+ type DefintegrateParams,+ type DefintegrateState,+ type DifferentiateParams,+ type DifferentiateState,+ type EvaluateParams,+ type EvaluateState,+ type ExecuteParams,+ type ExecuteState,+ type IntegrateParams,+ type IntegrateState,+ type LimitParams,+ type LimitState,+ type SolveParams,+ type SolveState,+ type SortParams,+ type SortState,+} from '../types';++/**+ * Calculator Execution Runtime+ *+ * This runtime executes calculator tools using the same executor logic as frontend.+ * Since mathjs and nerdamer work in both browser and Node.js, we can reuse the executor.+ */+export class CalculatorExecutionRuntime {+ async calculate(args: CalculateParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.calculate(args);++ const state: CalculateState = {+ expression: result.state?.expression,+ precision: result.state?.precision,+ result: result.state?.result as number | string | undefined,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async evaluate(args: EvaluateParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.evaluate(args);++ const state: EvaluateState = {+ expression: result.state?.expression,+ precision: result.state?.precision,+ result: result.state?.result as number | string | undefined,+ variables: result.state?.variables,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async sort(args: SortParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.sort(args);++ const state: SortState = {+ largest: result.state?.largest as number | string | undefined,+ mode: result.state?.mode,+ originalNumbers: result.state?.originalNumbers,+ precision: result.state?.precision,+ result: result.state?.result,+ reverse: result.state?.reverse,+ smallest: result.state?.smallest as number | string | undefined,+ sorted: result.state?.sorted as (string | number)[] | undefined,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async base(args: BaseParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.base(args);++ const state: BaseState = {+ convertedNumber: result.state?.convertedNumber,+ decimalValue: result.state?.decimalValue,+ originalBase: result.state?.originalBase as string | undefined,+ originalNumber: result.state?.originalNumber as string | undefined,+ targetBase: result.state?.targetBase as string | undefined,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async solve(args: SolveParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.solve(args);++ const state: SolveState = {+ equation: result.state?.equation,+ result: result.state?.result as string | string[] | undefined,+ variable: result.state?.variable,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async differentiate(args: DifferentiateParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.differentiate(args);++ const state: DifferentiateState = {+ expression: result.state?.expression,+ result: result.state?.result as string | undefined,+ variable: result.state?.variable,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async execute(args: ExecuteParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.execute(args);++ const state: ExecuteState = {+ expression: result.state?.expression,+ result: result.state?.result as string | undefined,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async defintegrate(args: DefintegrateParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.defintegrate(args);++ const state: DefintegrateState = {+ expression: result.state?.expression,+ lowerBound: result.state?.lowerBound,+ result: result.state?.result as string | undefined,+ upperBound: result.state?.upperBound,+ variable: result.state?.variable,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async integrate(args: IntegrateParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.integrate(args);++ const state: IntegrateState = {+ expression: result.state?.expression,+ result: result.state?.result as string | undefined,+ variable: result.state?.variable,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }++ async limit(args: LimitParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await calculatorExecutor.limit(args);++ const state: LimitState = {+ expression: result.state?.expression,+ point: result.state?.point,+ result: result.state?.result as string | undefined,+ variable: result.state?.variable,+ };++ return {+ content: result.content || '',+ state,+ success: result.success,+ };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ return {+ content: errorMessage,+ error,+ success: false,+ };+ }+ }+}diff --git a/packages/builtin-tool-calculator/src/calculate.test.ts b/packages/builtin-tool-calculator/src/calculate.test.tsnew file mode 100644index 00000000000..09315393c01--- /dev/null+++ b/packages/builtin-tool-calculator/src/calculate.test.ts@@ -0,0 +1,1371 @@+import { describe, expect, it } from 'vitest';++import { calculatorExecutor } from '../src/executor';++describe('Unit Conversion', () => {+ it('should handle temperature conversion with mathjs syntax', async () => {+ const result = await calculatorExecutor.calculate({ expression: '25 degC to degF' });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(77, 0);+ });++ it('should handle various temperature formats', async () => {+ const fahrenheit = await calculatorExecutor.calculate({ expression: '100 degC to degF' });+ expect(fahrenheit.success).toBe(true);+ expect(parseFloat(fahrenheit.content || '0')).toBeCloseTo(212, 0);++ const celsius = await calculatorExecutor.calculate({ expression: '32 degF to degC' });+ expect(celsius.success).toBe(true);+ expect(parseFloat(celsius.content || '0')).toBeCloseTo(0, 0);+ });++ it('should handle length conversions with mathjs syntax', async () => {+ const result = await calculatorExecutor.calculate({ expression: '5 cm to inch' });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(1.9685, 3);+ });++ it('should handle weight conversions', async () => {+ const result = await calculatorExecutor.calculate({ expression: '1 kg to lb' });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(2.2046, 3);+ });++ it('should handle speed conversions', async () => {+ const result = await calculatorExecutor.calculate({ expression: '100 km/h to mph' });+ // Note: This might fail depending on mathjs unit support+ console.log('Speed result:', result.content, result.success);+ if (result.success) {+ expect(parseFloat(result.content || '0')).toBeCloseTo(62.137, 2);+ } else {+ // Some unit combinations might not be supported+ expect(result.success).toBe(false);+ }+ });++ it('should handle invalid temperature syntax gracefully', async () => {+ const result = await calculatorExecutor.calculate({ expression: '25 °C to °F' });+ // This might fail due to Unicode degree symbol+ console.log('Unicode result:', result.content, result.success);+ });+ describe('Calculator Calculus', () => {+ describe('differentiate', () => {+ it('should differentiate polynomial expressions', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'x^3',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('3*x');+ });++ it('should differentiate quadratic expressions', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'x^2',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('2*x');+ });++ it('should differentiate trigonometric functions', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'sin(x)',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('cos(x)');+ });++ it('should differentiate exponential functions', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'exp(x)',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('e^x');+ });++ it('should handle chain rule', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'sin(x^2)',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('cos');+ expect(result.content).toContain('x');+ });++ it('should differentiate with respect to custom variable', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'y^2 + 2*y',+ variable: 'y',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('2*y');+ });++ it('should handle invalid expressions gracefully', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'invalid',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('0');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.differentiate({+ expression: 'x^2 + 3*x + 2',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.state?.expression).toBe('x^2 + 3*x + 2');+ expect(result.state?.variable).toBe('x');+ expect(result.state?.result).toBeDefined();+ });+ });++ describe('integrate', () => {+ it('should integrate polynomial expressions', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'x^2',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('(1/3)');+ expect(result.content).toContain('x^3');+ });++ it('should integrate cubic expressions', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'x^3',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('(1/4)');+ expect(result.content).toContain('x^4');+ });++ it('should integrate trigonometric functions', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'sin(x)',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('-cos');+ });++ it('should integrate exponential functions', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'exp(x)',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('e^x');+ });++ it('should integrate linear expressions', async () => {+ const result = await calculatorExecutor.integrate({+ expression: '3*x',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('(3/2)');+ expect(result.content).toContain('x^2');+ });++ it('should integrate with respect to custom variable', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'y^2',+ variable: 'y',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('y^3');+ });++ it('should handle invalid expressions gracefully', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'invalid',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('invalid*x');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.integrate({+ expression: 'x^2 + 2*x',+ variable: 'x',+ });++ expect(result.success).toBe(true);+ expect(result.state?.expression).toBe('x^2 + 2*x');+ expect(result.state?.variable).toBe('x');+ expect(result.state?.result).toBeDefined();+ });+ });++ describe('limit', () => {+ it('should compute finite limit at a point', async () => {+ const result = await calculatorExecutor.limit({+ expression: 'sin(x)/x',+ variable: 'x',+ point: 0,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('1');+ expect(result.state?.point).toBe(0);+ });++ it('should compute limit at infinity', async () => {+ const result = await calculatorExecutor.limit({+ expression: '1/x',+ variable: 'x',+ point: 'infinity',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('infinity^(-1)');+ expect(result.state?.point).toBe('infinity');+ });++ it('should require a point parameter', async () => {+ const result = await calculatorExecutor.limit({+ expression: '(x^2-1)/(x-1)',+ variable: 'x',+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('LimitError');+ expect(result.content).toContain('Limit computation error');+ });++ it('should compute limit approaching from left', async () => {+ const result = await calculatorExecutor.limit({+ expression: '(1+1/x)^x',+ variable: 'x',+ point: 'infinity',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('infinity');+ });++ it('should compute limit with trigonometric function', async () => {+ const result = await calculatorExecutor.limit({+ expression: '(1-cos(x))/x',+ variable: 'x',+ point: 0,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('0');+ });++ it('should handle invalid expressions gracefully', async () => {+ const result = await calculatorExecutor.limit({+ expression: 'invalid',+ variable: 'x',+ point: 0,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('invalid');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.limit({+ expression: 'sin(x)/x',+ variable: 'x',+ point: 0,+ });++ expect(result.success).toBe(true);+ expect(result.state?.expression).toBe('sin(x)/x');+ expect(result.state?.variable).toBe('x');+ expect(result.state?.point).toBe(0);+ expect(result.state?.result).toBeDefined();+ });+ });+ });++ it('should handle uppercase PI', async () => {+ const PI = await calculatorExecutor.calculate({ expression: 'PI' });+ expect(PI.success).toBe(true);+ expect(parseFloat(PI.content || '0')).toBeCloseTo(3.14159, 5);+ });++ it('should handle PI in expressions', async () => {+ const result = await calculatorExecutor.calculate({ expression: '2 * pi' });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(6.28318, 4);+ });++ it('should handle PI in trigonometric functions', async () => {+ const result = await calculatorExecutor.calculate({ expression: 'sin(pi/2)' });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(1, 5);+ });++ it('should handle PI in evaluate', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: 'x * pi',+ variables: { x: 3 },+ });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(9.42477, 4);+ });++ it('should handle other constants like E', async () => {+ const e = await calculatorExecutor.calculate({ expression: 'e' });+ expect(e.success).toBe(true);+ expect(parseFloat(e.content || '0')).toBeCloseTo(2.71828, 5);+ });++ it('should handle constants in scientific notation', async () => {+ const result = await calculatorExecutor.calculate({ expression: 'pi * 1e3' });+ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(3141.59, 2);+ });+});++describe('Calculator Definite Integration', () => {+ describe('defintegrate', () => {+ it('should compute definite integral of polynomial', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'x^2',+ variable: 'x',+ lowerBound: 0,+ upperBound: 1,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('1/3');+ expect(result.state?.expression).toBe('x^2');+ expect(result.state?.variable).toBe('x');+ expect(result.state?.lowerBound).toBe(0);+ expect(result.state?.upperBound).toBe(1);+ });++ it('should compute definite integral of trigonometric function', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'sin(x)',+ variable: 'x',+ lowerBound: 0,+ upperBound: 'pi',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('2');+ });++ it('should compute definite integral of exponential function', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'exp(x)',+ variable: 'x',+ lowerBound: 0,+ upperBound: 1,+ });++ expect(result.success).toBe(true);+ expect(result.content).toMatch(/e|205671881\/119696244/); // Either 'e' or fraction form+ });++ it('should compute definite integral with negative bounds', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'x^3',+ variable: 'x',+ lowerBound: -1,+ upperBound: 1,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('0');+ });++ it('should compute definite integral to infinity', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: '1/x^2',+ variable: 'x',+ lowerBound: 1,+ upperBound: 'infinity',+ });++ expect(result.success).toBe(true);+ expect(result.content).toMatch(/1|infinity/); // Either '1' or symbolic infinity form+ });++ it('should handle definite integral with fractional bounds', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'x',+ variable: 'x',+ lowerBound: 0.5,+ upperBound: 1.5,+ });++ expect(result.success).toBe(true);+ });++ it('should handle definite integral with string bounds', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'cos(x)',+ variable: 'x',+ lowerBound: '0',+ upperBound: 'pi/2',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('1');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: '2*x',+ variable: 'x',+ lowerBound: 0,+ upperBound: 5,+ });++ expect(result.success).toBe(true);+ expect(result.state?.expression).toBe('2*x');+ expect(result.state?.variable).toBe('x');+ expect(result.state?.lowerBound).toBe(0);+ expect(result.state?.upperBound).toBe(5);+ expect(result.state?.result).toBeDefined();+ });++ it('should handle invalid expressions gracefully', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'invalid',+ variable: 'x',+ lowerBound: 0,+ upperBound: 1,+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('invalid');+ });++ it('should handle complex expressions', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'x^2 + 2*x + 1',+ variable: 'x',+ lowerBound: 0,+ upperBound: 2,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBeDefined();+ });++ it('should handle zero-width interval', async () => {+ const result = await calculatorExecutor.defintegrate({+ expression: 'x^2',+ variable: 'x',+ lowerBound: 1,+ upperBound: 1,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('0');+ });+ });+});++describe('Calculator Nerdamer Execute', () => {+ describe('execute', () => {+ it('should execute expand expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'expand((x+1)^2)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('1+2*x+x^2');+ expect(result.state?.expression).toBe('expand((x+1)^2)');+ expect(result.state?.result).toBeDefined();+ });++ it('should execute factor expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'factor(x^2-1)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('(-1+x)*(1+x)');+ });++ it('should execute partfrac expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'partfrac(1/(x^2-1))',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('1/2');+ });++ it('should execute simplify expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'simplify(x^2+2*x-x)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('(1+x)*x');+ });++ it('should execute toTeX expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'toTeX(x^2+2*x+1)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('(1+2*x+x^2)*toTeX');+ });++ it('should execute coefficients expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'coeffs(x^3+2*x^2+3*x+4)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('[4,3,2,1]');+ });++ it('should execute roots expression', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'roots(x^2-4)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('[2,-2]');+ });++ it('should handle invalid expressions gracefully', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'invalid_function(x)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('invalid_function');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.execute({+ expression: 'expand(x*y)',+ });++ expect(result.success).toBe(true);+ expect(result.state?.expression).toBe('expand(x*y)');+ expect(result.state?.result).toBeDefined();+ });+ });+});++describe('Calculator Base Conversion', () => {+ it('should base binary to decimal', async () => {+ const result = await calculatorExecutor.base({+ number: '1010',+ fromBase: 2,+ toBase: 10,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('10');+ expect(result.state?.decimalValue).toBe(10);+ });++ it('should base decimal to binary', async () => {+ const result = await calculatorExecutor.base({+ number: '255',+ fromBase: 10,+ toBase: 2,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('11111111');+ expect(result.state?.decimalValue).toBe(255);+ });++ it('should base hexadecimal to octal', async () => {+ const result = await calculatorExecutor.base({+ number: 'FF',+ fromBase: 16,+ toBase: 8,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('377');+ expect(result.state?.decimalValue).toBe(255);+ });++ it('should base octal to hexadecimal', async () => {+ const result = await calculatorExecutor.base({+ number: '77',+ fromBase: 8,+ toBase: 16,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('3F');+ expect(result.state?.decimalValue).toBe(63);+ });++ it('should handle hexadecimal input', async () => {+ const result = await calculatorExecutor.base({+ number: 'FF',+ fromBase: 16,+ toBase: 10,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('255');+ expect(result.state?.decimalValue).toBe(255);+ });++ it('should handle invalid numbers', async () => {+ const result = await calculatorExecutor.base({+ number: '2AB',+ fromBase: 2,+ toBase: 10,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ConversionError');+ });++ it('should support bases 2-36 with numeric input', async () => {+ const result = await calculatorExecutor.base({+ number: 'Z',+ fromBase: 36,+ toBase: 10,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('35');+ expect(result.state?.decimalValue).toBe(35);+ });++ it('should base decimal to base 32', async () => {+ const result = await calculatorExecutor.base({+ number: '1000',+ fromBase: 10,+ toBase: 32,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('V8');+ expect(result.state?.decimalValue).toBe(1000);+ });++ it('should handle invalid base numbers', async () => {+ const result = await calculatorExecutor.base({+ number: '123',+ fromBase: 1,+ toBase: 10,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ConversionError');+ });++ it('should handle invalid base 37', async () => {+ const result = await calculatorExecutor.base({+ number: '123',+ fromBase: 10,+ toBase: 37,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ConversionError');+ });++ it('should validate digit characters for base', async () => {+ const result = await calculatorExecutor.base({+ number: 'G',+ fromBase: 16,+ toBase: 10,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ConversionError');+ });+});++describe('Calculator Core Functions', () => {+ describe('calculate', () => {+ it('should handle basic arithmetic', async () => {+ const result = await calculatorExecutor.calculate({+ expression: '2 + 3 * 4',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('14');+ expect(result.state?.result).toBe('14');+ });++ it('should handle unit conversions (cm to inch)', async () => {+ const result = await calculatorExecutor.calculate({+ expression: '5 cm to inch',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('1.968503937 inch');+ });++ it('should handle unit conversions (kg to lb)', async () => {+ const result = await calculatorExecutor.calculate({+ expression: '1 kg to lb',+ });++ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(2.20462, 5);+ });++ it('should handle scientific functions', async () => {+ const result = await calculatorExecutor.calculate({+ expression: 'sin(30 deg)',+ });++ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(0.5, 5);+ });++ it('should handle matrix operations', async () => {+ const result = await calculatorExecutor.calculate({+ expression: 'det([[1,2],[3,4]])',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('-2');+ });++ it('should handle complex numbers', async () => {+ const result = await calculatorExecutor.calculate({+ expression: 'sqrt(-1)',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('i');+ });++ it('should handle precision formatting', async () => {+ const result = await calculatorExecutor.calculate({+ expression: '10 / 3',+ precision: 2,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('3.33');+ });++ it('should handle zero precision (default)', async () => {+ const result = await calculatorExecutor.calculate({+ expression: '10 / 3',+ precision: 0,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('3');+ });++ it('should handle undefined expression', async () => {+ const result = await calculatorExecutor.calculate({+ expression: 'invalid_syntax_*(',+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('CalculationError');+ });+ });++ describe('evaluate', () => {+ it('should handle variable substitution', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: 'x^2 + 2*x + 1',+ variables: { x: 5 },+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('36');+ expect(result.state?.result).toBe('36');+ expect(result.state?.variables).toEqual({ x: 5 });+ });++ it('should handle multiple variables', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: 'a*x + b',+ variables: { a: 2, x: 3, b: 1 },+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('7');+ });++ it('should handle no variables', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: '2 + 2',+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('4');+ });++ it('should handle missing variables gracefully', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: 'x + y',+ variables: { x: 1 }, // y is missing+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('CalculationError');+ });++ it('should handle complex expressions with variables', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: 'sin(x) * cos(y)',+ variables: { x: 1.5708, y: 0 }, // Approximate pi/2+ });++ expect(result.success).toBe(true);+ expect(parseFloat(result.content || '0')).toBeCloseTo(1, 5);+ });+ });++ describe('base', () => {+ it('should handle number input in base conversion', async () => {+ const result = await calculatorExecutor.base({+ number: 255,+ fromBase: 10,+ toBase: 2,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('11111111');+ });++ it('should handle string input in base conversion', async () => {+ const result = await calculatorExecutor.base({+ number: '255',+ fromBase: 10,+ toBase: 2,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('11111111');+ });++ it('should handle zero in base conversion', async () => {+ const result = await calculatorExecutor.base({+ number: '0',+ fromBase: 10,+ toBase: 16,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('0');+ });++ it('should handle large numbers', async () => {+ const result = await calculatorExecutor.base({+ number: '4294967295',+ fromBase: 10,+ toBase: 16,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('FFFFFFFF');+ });++ it('should handle base 36 conversion', async () => {+ const result = await calculatorExecutor.base({+ number: '123456789',+ fromBase: 10,+ toBase: 36,+ });++ expect(result.success).toBe(true);+ expect(result.content).toBe('21I3V9');+ });++ it('should handle invalid base error', async () => {+ const result = await calculatorExecutor.base({+ number: '123',+ fromBase: 1, // Invalid base+ toBase: 10,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ConversionError');+ expect(result.error?.message).toContain('Base must be between 2 and 36');+ });++ it('should handle invalid digit error', async () => {+ const result = await calculatorExecutor.base({+ number: 'G', // Invalid digit for hex+ fromBase: 16,+ toBase: 10,+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ConversionError');+ expect(result.error?.message).toContain('Invalid digit');+ });++ it('should handle decimal input with parseInt behavior', async () => {+ const result = await calculatorExecutor.base({+ number: '15.5',+ fromBase: 10,+ toBase: 2,+ });++ // parseInt will only handle integer part, decimal part is ignored+ expect(result.success).toBe(true);+ expect(result.content).toBe('1111');+ });+ });++ describe('error handling', () => {+ it('should handle division by zero', async () => {+ const result = await calculatorExecutor.calculate({+ expression: '1 / 0',+ });++ // mathjs handles division by zero as Infinity+ expect(result.success).toBe(true);+ expect(result.content).toBe('Infinity');+ });++ it('should handle expression evaluation errors gracefully', async () => {+ const result = await calculatorExecutor.evaluate({+ expression: 'x ^^^^^ y',+ variables: { x: 1, y: 2 },+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('CalculationError');+ });++ it('should preserve state information on errors', async () => {+ const result = await calculatorExecutor.calculate({+ expression: 'invalid',+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('Calculation error');+ expect(result.error?.message).toBeDefined();+ });+ });+});++describe('Calculator Sorting', () => {+ describe('sort', () => {+ it('should default to sorted array when no mode provided', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['2.718', '3.14']);+ });++ it('should return sorted array when no mode provided', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['1.618', '2.718', '3.14', '4.669']);+ });++ it('should return largest value only in largest mode', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ mode: 'largest',+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('4.669');+ });++ it('should return smallest value only in smallest mode', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ mode: 'smallest',+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('1.618');+ });++ it('should compare string numbers', async () => {+ const result = await calculatorExecutor.sort({+ numbers: ['3.14', '2.718', '1.618'],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['1.618', '2.718', '3.14']);+ });++ it('should compare mixed string and number inputs', async () => {+ const result = await calculatorExecutor.sort({+ numbers: ['3.14', 2.718, '1.618'],+ mode: 'largest',+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('3.14');+ });++ it('should handle precision formatting', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.1415926535, 2.7182818284, 1.6180339887],+ precision: 3,+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['1.618', '2.718', '3.142']);+ });++ it('should handle zero precision', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618],+ mode: 'largest',+ precision: 0,+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('3');+ });++ it('should handle duplicate values', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [5, 3, 5, 2],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['2', '3', '5', '5']);+ });++ it('should require at least 2 numbers', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14],+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ValidationError');+ expect(result.content).toContain('At least 2 numbers are required');+ });++ it('should handle invalid number strings', async () => {+ const result = await calculatorExecutor.sort({+ numbers: ['3.14', 'invalid', '2.718'],+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ComparisonError');+ expect(result.content).toContain('Invalid number: invalid');+ });++ it('should handle negative numbers', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [-3.14, -2.718, -1.618],+ mode: 'smallest',+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('-3.14');+ });++ it('should handle zero values', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [0, -1, 1],+ mode: 'largest',+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('1');+ });++ it('should handle very large numbers', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [1e10, 1e9, 1e11],+ mode: 'smallest',+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('1000000000');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718],+ mode: 'largest',+ precision: 2,+ });++ expect(result.success).toBe(true);+ expect(result.state?.originalNumbers).toEqual([3.14, 2.718]);+ expect(result.state?.mode).toBe('largest');+ expect(result.state?.precision).toBe(2);+ expect(result.state?.largest).toBe('3.14');+ expect(result.state?.smallest).toBe('2.72');+ expect(result.state?.sorted).toEqual(['2.72', '3.14']);+ });++ it('should sort in descending order when reverse is true', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ reverse: true,+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['4.669', '3.14', '2.718', '1.618']);+ });++ it('should sort in ascending order when reverse is false', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ reverse: false,+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['1.618', '2.718', '3.14', '4.669']);+ });++ it('should default to ascending order when reverse is not specified', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(Array.isArray(parsed)).toBe(true);+ expect(parsed).toEqual(['1.618', '2.718', '3.14', '4.669']);+ });++ it('should work with reverse parameter in largest mode', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ mode: 'largest',+ reverse: true,+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('4.669');+ });++ it('should work with reverse parameter in smallest mode', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718, 1.618, 4.669],+ mode: 'smallest',+ reverse: true,+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed).toBe('1.618');+ });++ it('should preserve reverse parameter in state', async () => {+ const result = await calculatorExecutor.sort({+ numbers: [3.14, 2.718],+ reverse: true,+ precision: 2,+ });++ expect(result.success).toBe(true);+ expect(result.state?.reverse).toBe(true);+ expect(result.state?.sorted).toEqual(['3.14', '2.72']);+ });+ });+});++describe('Calculator Equation Solver', () => {+ describe('solve', () => {+ it('should solve linear equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['3*x + 5 = 20'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('5');+ expect(result.state?.equation).toEqual(['3*x + 5 = 20']);+ });++ it('should solve quadratic equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x^2 - 5*x + 6 = 0'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('2');+ expect(result.content).toContain('3');+ expect(result.state?.equation).toEqual(['x^2 - 5*x + 6 = 0']);+ });++ it('should solve perfect square equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x^2 + 2*x + 1 = 0'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('-1');+ expect(result.state?.equation).toEqual(['x^2 + 2*x + 1 = 0']);+ });++ it('should solve equations with custom variable', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['y^2 - 9 = 0'],+ variable: ['y'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('3');+ expect(result.content).toContain('-3');+ expect(result.state?.variable).toEqual(['y']);+ });++ it('should solve simple equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x - 5 = 0'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('5');+ });++ it('should handle equations with fractions', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['2*x = 10'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('5');+ });++ it('should handle cubic equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x^3 - 8 = 0'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('2');+ });++ it('should handle invalid equations gracefully', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['invalid equation'],+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('SolveError');+ });++ it('should preserve state information', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x^2 - 4 = 0'],+ variable: ['x'],+ });++ expect(result.success).toBe(true);+ expect(result.state?.equation).toEqual(['x^2 - 4 = 0']);+ expect(result.state?.variable).toEqual(['x']);+ expect(result.state?.result).toBeDefined();+ });++ it('should solve system of two equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['2*x+y=5', 'x-y=1'],+ variable: ['x', 'y'],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed.x).toBe('2');+ expect(parsed.y).toBe('1');+ });++ it('should solve system of two equations with default variables', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['3*x+2*y=7', 'x-y=1'],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parseFloat(parsed.x)).toBeCloseTo(1.8, 1);+ expect(parseFloat(parsed.y)).toBeCloseTo(0.8, 1);+ });++ it('should solve system of three equations', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x+y+z=6', '2*x-y+z=3', 'x+2*y-z=2'],+ variable: ['x', 'y', 'z'],+ });++ expect(result.success).toBe(true);+ const parsed = JSON.parse(result.content || '{}');+ expect(parsed.x).toBe('1');+ expect(parsed.y).toBe('2');+ expect(parsed.z).toBe('3');+ });++ it('should handle system with no solution', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x+y=5', 'x+y=7'],+ variable: ['x', 'y'],+ });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('SolveError');+ expect(result.content).toContain('distinct solution');+ });++ it('should handle single equation with extra variables in array', async () => {+ const result = await calculatorExecutor.solve({+ equation: ['x+y=5'],+ variable: ['x', 'y'],+ });++ expect(result.success).toBe(true);+ expect(result.content).toBeDefined();+ });+ });+});diff --git a/packages/builtin-tool-calculator/src/client/index.ts b/packages/builtin-tool-calculator/src/client/index.tsnew file mode 100644index 00000000000..7dbe0f19cfc--- /dev/null+++ b/packages/builtin-tool-calculator/src/client/index.ts@@ -0,0 +1,5 @@+// Client-side exports for the Calculator tool++export { calculatorExecutor } from '../executor';+export { CalculatorManifest } from '../manifest';+export * from '../types';diff --git a/packages/builtin-tool-calculator/src/executor/index.ts b/packages/builtin-tool-calculator/src/executor/index.tsnew file mode 100644index 00000000000..aa6a4962ac8--- /dev/null+++ b/packages/builtin-tool-calculator/src/executor/index.ts@@ -0,0 +1,595 @@+import { BaseExecutor, type BuiltinToolResult, type IBuiltinToolExecutor } from '@lobechat/types';+import { defBase } from '@thi.ng/base-n/base';+import { all, create } from 'mathjs';+// @ts-ignore - nerdamer doesn't have TypeScript definitions+import nerdamer from 'nerdamer-prime/all';++import {+ type BaseParams,+ type CalculateParams,+ CalculatorApiName,+ CalculatorIdentifier,+ type DefintegrateParams,+ type DifferentiateParams,+ type EvaluateParams,+ type ExecuteParams,+ type IntegrateParams,+ type LimitParams,+ type SolveParams,+ type SortParams,+} from '../types';++// Create a mathjs instance with all functions+const math = create(all);++/**+ * Calculator Tool Executor+ *+ * Handles mathematical calculations and expression evaluations using mathjs library.+ */+class CalculatorExecutor+ extends BaseExecutor<typeof CalculatorApiName>+ implements IBuiltinToolExecutor+{+ readonly identifier = CalculatorIdentifier;+ protected readonly apiEnum = CalculatorApiName;++ /**+ * Safely evaluate a mathematical expression using mathjs+ */+ private evaluateMathExpression(expression: string, variables: Record<string, number> = {}): any {+ try {+ // Parse the expression with mathjs+ const node = math.parse(expression);++ // Compile and evaluate with variables+ const compiled = node.compile();+ const result = compiled.evaluate(variables);++ return result;+ } catch (error) {+ throw new Error(+ `Failed to evaluate expression: ${error instanceof Error ? error.message : 'Unknown error'}`,+ );+ }+ }++ /**+ * Format result based on type and precision+ */+ private formatResult(result: any, precision?: number): string {+ if (typeof result === 'number') {+ if (precision !== undefined) {+ return result.toFixed(precision);+ }+ return result.toString();+ }++ if (typeof result === 'bigint') {+ return result.toString();+ }++ if (typeof result === 'string') {+ return result;+ }++ // Handle complex numbers, matrices, etc.+ return math.format(result, { precision: precision || 10 });+ }++ /**+ * Convert number between bases using @thi.ng/base-n+ */+ private convertNumber(number: string | number, fromBase: number, toBase: number): string {+ // Define character set for source and target bases+ const sourceChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.slice(0, fromBase);+ const targetChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.slice(0, toBase);++ // Create converters+ const sourceConverter = defBase(sourceChars);+ const targetConverter = defBase(targetChars);++ // Convert input number to string+ let numStr = String(number).trim().toUpperCase();++ // Handle decimal input like parseInt - take only integer part+ const decimalIndex = numStr.indexOf('.');+ if (decimalIndex !== -1) {+ numStr = numStr.slice(0, Math.max(0, decimalIndex));+ }++ // Convert from source base to decimal (as bigint)+ const decimal = sourceConverter.decodeBigInt(numStr);++ // Convert decimal to target base+ return targetConverter.encodeBigInt(decimal);+ }++ /**+ * Calculate a mathematical expression+ */+ calculate = async (params: CalculateParams): Promise<BuiltinToolResult> => {+ try {+ const result = this.evaluateMathExpression(params.expression);++ if (result === undefined) {+ return {+ content: `Cannot evaluate expression: "${params.expression}"`,+ error: {+ message: 'Expression resulted in undefined',+ type: 'ValidationError',+ },+ success: false,+ };+ }++ const formattedResult = this.formatResult(result, params.precision);++ return {+ content: formattedResult,+ state: {+ expression: params.expression,+ precision: params.precision,+ result: formattedResult,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Calculation error: ${err.message}`,+ error: {+ message: err.message,+ type: 'CalculationError',+ },+ success: false,+ };+ }+ };++ /**+ * Evaluate a complex mathematical expression with variables+ */+ evaluate = async (params: EvaluateParams): Promise<BuiltinToolResult> => {+ try {+ const variables = params.variables || {};+ const result = this.evaluateMathExpression(params.expression, variables);++ if (result === undefined) {+ return {+ content: `Cannot evaluate expression: "${params.expression}"`,+ error: {+ message: 'Expression resulted in undefined',+ type: 'ValidationError',+ },+ success: false,+ };+ }++ const formattedResult = this.formatResult(result, params.precision);++ return {+ content: formattedResult,+ state: {+ expression: params.expression,+ precision: params.precision,+ result: formattedResult,+ variables,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Expression evaluation error: ${err.message}`,+ error: {+ message: err.message,+ type: 'CalculationError',+ },+ success: false,+ };+ }+ };++ /**+ * Sort multiple numbers with flexible output options+ */+ sort = async (params: SortParams): Promise<BuiltinToolResult> => {+ try {+ const { numbers, mode, precision, reverse } = params;++ if (numbers.length < 2) {+ return {+ content: 'At least 2 numbers are required for comparison',+ error: {+ message: 'Insufficient numbers for comparison',+ type: 'ValidationError',+ },+ success: false,+ };+ }++ // Convert all numbers to actual numbers for comparison+ const parsedNumbers = numbers.map((num) => {+ const parsed = typeof num === 'string' ? parseFloat(num) : num;+ if (isNaN(parsed)) {+ throw new Error(`Invalid number: ${num}`);+ }+ return parsed;+ });++ // Sort numbers (ascending by default, reverse if specified)+ const sortedParsed = [...parsedNumbers].sort((a, b) => (reverse ? b - a : a - b));++ // Format numbers for output+ const formatNumber = (num: number): string => {+ if (precision !== undefined) {+ return num.toFixed(precision);+ }+ return num.toString();+ };++ const sorted = sortedParsed.map(formatNumber);+ const largest = formatNumber(Math.max(...parsedNumbers));+ const smallest = formatNumber(Math.min(...parsedNumbers));++ let result: any;++ switch (mode) {+ case 'largest': {+ result = largest;+ break;+ }+ case 'smallest': {+ result = smallest;+ break;+ }+ default: {+ result = sorted;+ }+ }++ return {+ content: JSON.stringify(result),+ state: {+ largest,+ mode,+ originalNumbers: numbers,+ precision,+ result,+ reverse,+ smallest,+ sorted,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Comparison error: ${err.message}`,+ error: {+ message: err.message,+ type: 'ComparisonError',+ },+ success: false,+ };+ }+ };++ /**+ * Convert numbers between different bases (supports bases 2-36)+ */+ base = async (params: BaseParams): Promise<BuiltinToolResult> => {+ try {+ const { number, fromBase, toBase } = params;++ // Validate base range+ if (fromBase < 2 || fromBase > 36 || toBase < 2 || toBase > 36) {+ throw new Error('Base must be between 2 and 36');+ }++ // Convert using @thi.ng/base-n+ const convertedNumber = this.convertNumber(number, fromBase, toBase);++ // Get decimal value for state+ const decimalValue = parseInt(String(number), fromBase);++ return {+ content: convertedNumber,+ state: {+ convertedNumber,+ decimalValue,+ originalBase: fromBase,+ originalNumber: number,+ targetBase: toBase,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;++ // Check for digit validation error+ let errorMessage = err.message;+ if (err.message?.includes('Cannot convert') || err.message?.includes('Invalid digit')) {+ errorMessage = 'Invalid digit';+ }++ return {+ content: `Base conversion error: ${errorMessage}`,+ error: {+ message: errorMessage,+ type: 'ConversionError',+ },+ success: false,+ };+ }+ };++ /**+ * Solve equation or system of equations using nerdamer+ */+ solve = async (params: SolveParams): Promise<BuiltinToolResult> => {+ try {+ const { equation, variable } = params;++ let resultText: string;++ if (equation.length === 1) {+ const solveVariable = variable && variable.length > 0 ? variable[0] : 'x';+ const result = nerdamer.solve(equation[0], solveVariable);+ const rawResult = result.toString();++ if (rawResult === '[]') {+ return {+ content: 'No solution found for the given equation',+ error: {+ message: 'No solution found',+ type: 'SolveError',+ },+ success: false,+ };+ }+ resultText = rawResult;+ } else {+ let solveVariables: string[];++ if (variable && variable.length > 0) {+ solveVariables = variable;+ } else {+ const allVars = new Set<string>();+ for (const eq of equation) {+ const nerdamerEq = nerdamer(eq);+ const vars = nerdamerEq.variables() as string[];+ for (const v of vars) {+ if (v !== '') {+ allVars.add(v);+ }+ }+ }+ solveVariables = Array.from(allVars);+ if (solveVariables.length === 0) {+ solveVariables = ['x'];+ }+ }++ const result = nerdamer.solveEquations(equation, solveVariables);+ const rawResult = result.toString();++ const pairs = rawResult.split(',');+ const solution: Record<string, string> = {};+ for (let i = 0; i < pairs.length; i += 2) {+ if (i + 1 < pairs.length) {+ solution[pairs[i]] = pairs[i + 1];+ }+ }+ resultText = JSON.stringify(solution, null, 2);+ }++ return {+ content: resultText,+ state: {+ equation,+ result: resultText,+ variable,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Equation solver error: ${err.message}`,+ error: {+ message: err.message,+ type: 'SolveError',+ },+ success: false,+ };+ }+ };++ /**+ * Differentiate an expression using nerdamer+ */+ differentiate = async (params: DifferentiateParams): Promise<BuiltinToolResult> => {+ try {+ const { expression, variable } = params;+ const result = nerdamer(`diff(${expression}, ${variable})`);+ const resultText = result.toString();++ return {+ content: resultText,+ state: {+ expression,+ result: resultText,+ variable,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Differentiation error: ${err.message}`,+ error: {+ message: err.message,+ type: 'DifferentiationError',+ },+ success: false,+ };+ }+ };++ /**+ * Integrate an expression using nerdamer+ */+ integrate = async (params: IntegrateParams): Promise<BuiltinToolResult> => {+ try {+ const { expression, variable } = params;+ const result = nerdamer(`integrate(${expression}, ${variable})`);+ const resultText = result.toString();++ return {+ content: resultText,+ state: {+ expression,+ result: resultText,+ variable,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Integration error: ${err.message}`,+ error: {+ message: err.message,+ type: 'IntegrationError',+ },+ success: false,+ };+ }+ };++ /**+ * Compute the definite integral of a mathematical expression using nerdamer+ */+ defintegrate = async (params: DefintegrateParams): Promise<BuiltinToolResult> => {+ try {+ const { expression, variable, lowerBound, upperBound } = params;++ // First compute the indefinite integral+ const indefiniteIntegral = nerdamer(`integrate(${expression}, ${variable})`);++ // Then evaluate at bounds using the fundamental theorem of calculus+ const upperResult = indefiniteIntegral.evaluate({ [variable]: upperBound });+ const lowerResult = indefiniteIntegral.evaluate({ [variable]: lowerBound });++ // Compute the difference+ const finalResult = nerdamer(`${upperResult} - ${lowerResult}`);+ const resultText = finalResult.toString();++ return {+ content: resultText,+ state: {+ expression,+ lowerBound,+ result: resultText,+ upperBound,+ variable,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Definite integration error: ${err.message}`,+ error: {+ message: err.message,+ type: 'DefintegrationError',+ },+ success: false,+ };+ }+ };++ /**+ * Execute a generic nerdamer expression+ */+ execute = async (params: ExecuteParams): Promise<BuiltinToolResult> => {+ try {+ const { expression } = params;+ const result = nerdamer(expression);+ const resultText = result.toString();++ return {+ content: resultText,+ state: {+ expression,+ result: resultText,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Nerdamer execution error: ${err.message}`,+ error: {+ message: err.message,+ type: 'NerdamerError',+ },+ success: false,+ };+ }+ };++ /**+ * Compute the limit of a mathematical expression using nerdamer+ */+ limit = async (params: LimitParams): Promise<BuiltinToolResult> => {+ try {+ const { expression, variable, point } = params;+ let limitExpr: string;++ if (point !== undefined) {+ limitExpr = `limit(${expression}, ${variable}, ${point})`;+ } else {+ limitExpr = `limit(${expression}, ${variable})`;+ }++ const result = nerdamer(limitExpr);+ const resultText = result.toString();++ return {+ content: resultText,+ state: {+ expression,+ point,+ result: resultText,+ variable,+ },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ content: `Limit computation error: ${err.message}`,+ error: {+ message: err.message,+ type: 'LimitError',+ },+ success: false,+ };+ }+ };++ // Implement required interface methods+ getApiNames(): string[] {+ return Object.values(this.apiEnum) as string[];+ }++ hasApi(apiName: string): boolean {+ return (Object.values(this.apiEnum) as string[]).includes(apiName);+ }+}++// Export the executor instance for registration+export const calculatorExecutor = new CalculatorExecutor();diff --git a/packages/builtin-tool-calculator/src/index.ts b/packages/builtin-tool-calculator/src/index.tsnew file mode 100644index 00000000000..47986dd2595--- /dev/null+++ b/packages/builtin-tool-calculator/src/index.ts@@ -0,0 +1,14 @@+export * from './ExecutionRuntime';+export { CalculatorManifest } from './manifest';+export { systemPrompt } from './systemRole';+export {+ type BaseParams,+ type BaseState,+ type CalculateParams,+ type CalculateState,+ CalculatorApiName,+ type CalculatorApiNameType,+ CalculatorIdentifier,+ type EvaluateParams,+ type EvaluateState,+} from './types';diff --git a/packages/builtin-tool-calculator/src/manifest.ts b/packages/builtin-tool-calculator/src/manifest.tsnew file mode 100644index 00000000000..99a4e102f79--- /dev/null+++ b/packages/builtin-tool-calculator/src/manifest.ts@@ -0,0 +1,272 @@+import { type BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { CalculatorApiName, CalculatorIdentifier } from './types';++export const CalculatorManifest: BuiltinToolManifest = {+ api: [+ {+ description: 'Calculate result of a mathematical expression.',+ name: CalculatorApiName.calculate,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description:+ 'Mathematical expression to calculate (e.g., "2 + 3 * 4", "sqrt(16)", "sin(30 deg)", "det([[1,2],[3,4]])", "5 cm to inch")',+ type: 'string',+ },+ precision: {+ description: 'Number of decimal places for result (optional, defaults to 10)',+ maximum: 20,+ minimum: 0,+ type: 'number',+ },+ },+ required: ['expression'],+ type: 'object',+ },+ },+ {+ description: 'Evaluate a complex mathematical expression with variable support.',+ name: CalculatorApiName.evaluate,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description:+ 'Mathematical expression to evaluate (e.g., "x^2 + 2*x + 1", "det([[a,b],[c,d]])", "sqrt(a^2 + b^2)")',+ type: 'string',+ },+ precision: {+ description: 'Number of decimal places for result (optional, defaults to 10)',+ maximum: 20,+ minimum: 0,+ type: 'number',+ },+ variables: {+ description:+ 'Key-value pairs of variables to substitute in expression (e.g., {"x": 5, "r": 3})',+ type: 'object',+ },+ },+ required: ['expression'],+ type: 'object',+ },+ },+ {+ description:+ 'Sort multiple numbers with flexible output options (sorted array, largest value, or smallest value).',+ name: CalculatorApiName.sort,+ parameters: {+ additionalProperties: false,+ properties: {+ mode: {+ description:+ 'Optional mode: "largest" returns only largest value; "smallest" returns only smallest value; if not specified, returns sorted array',+ enum: ['largest', 'smallest'],+ type: 'string',+ },+ numbers: {+ description:+ 'Array of numbers to compare (e.g., ["3.14", "2.718", "1.618"] or [3.14, 2.718, 1.618])',+ items: {+ type: ['string', 'number'],+ },+ minItems: 2,+ type: 'array',+ },+ precision: {+ description:+ 'Number of decimal places for comparison results (optional, defaults to 10)',+ maximum: 20,+ minimum: 0,+ type: 'number',+ },+ reverse: {+ description:+ 'Sort order: false (default) sorts ascending (smallest to largest); true sorts descending (largest to smallest)',+ type: 'boolean',+ },+ },+ required: ['numbers'],+ type: 'object',+ },+ },+ {+ description: 'Convert numbers between different number bases.',+ name: CalculatorApiName.base,+ parameters: {+ additionalProperties: false,+ properties: {+ fromBase: {+ description: 'Source base of the input number (numeric value between 2-36)',+ maximum: 36,+ minimum: 2,+ type: 'number',+ },+ number: {+ description:+ 'The number to convert (string or number, e.g., "1010", 1010, "77", "255", "FF", "Z")',+ type: ['string', 'number'],+ },+ toBase: {+ description: 'Target base for conversion (numeric value between 2-36)',+ maximum: 36,+ minimum: 2,+ type: 'number',+ },+ },+ required: ['number', 'fromBase', 'toBase'],+ type: 'object',+ },+ },+ {+ description: 'Differentiate a mathematical expression with respect to a variable.',+ name: CalculatorApiName.differentiate,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description:+ 'Mathematical expression to differentiate (e.g., "x^2", "sin(x)", "x^3 + 2*x + 1")',+ type: 'string',+ },+ variable: {+ description: 'Variable to differentiate with respect to (e.g., "x", "y", "t")',+ type: 'string',+ },+ },+ required: ['expression', 'variable'],+ type: 'object',+ },+ },+ {+ description:+ 'Compute definite integral of a mathematical expression with respect to a variable over a given interval.',+ name: CalculatorApiName.defintegrate,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description: 'Mathematical expression to integrate (e.g., "x^2", "sin(x)", "exp(x)")',+ type: 'string',+ },+ lowerBound: {+ description: 'Lower bound of integration (can be number, "0", "-infinity", etc.)',+ oneOf: [{ type: 'string' }, { type: 'number' }],+ },+ upperBound: {+ description: 'Upper bound of integration (can be number, "pi", "infinity", etc.)',+ oneOf: [{ type: 'string' }, { type: 'number' }],+ },+ variable: {+ description: 'Variable to integrate with respect to (e.g., "x", "y", "t")',+ type: 'string',+ },+ },+ required: ['expression', 'variable', 'lowerBound', 'upperBound'],+ type: 'object',+ },+ },+ {+ description:+ 'Integrate a mathematical expression with respect to a variable (indefinite integral).',+ name: CalculatorApiName.integrate,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description: 'Mathematical expression to integrate (e.g., "x^2", "sin(x)", "exp(x)")',+ type: 'string',+ },+ variable: {+ description: 'Variable to integrate with respect to (e.g., "x", "y", "t")',+ type: 'string',+ },+ },+ required: ['expression', 'variable'],+ type: 'object',+ },+ },+ {+ description: 'Execute a generic nerdamer expression for symbolic math computations.',+ name: CalculatorApiName.execute,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description:+ 'Nerdamer expression to execute (e.g., "expand((x+1)^2)", "factor(x^2-1)", "partfrac(1/(x^2-1))")',+ type: 'string',+ },+ },+ required: ['expression'],+ type: 'object',+ },+ },+ {+ description: 'Compute the limit of a mathematical expression.',+ name: CalculatorApiName.limit,+ parameters: {+ additionalProperties: false,+ properties: {+ expression: {+ description:+ 'Mathematical expression to compute limit for (e.g., "sin(x)/x", "x^2", "exp(-x)")',+ type: 'string',+ },+ point: {+ description:+ 'Point at which to evaluate the limit (optional). If not specified, computes the limit as variable approaches the expression. Can be a specific value or "infinity" (e.g., "0", "1", "infinity")',+ oneOf: [{ type: 'string' }, { type: 'number' }],+ },+ variable: {+ description: 'Variable to compute limit with respect to (e.g., "x", "y", "t")',+ type: 'string',+ },+ },+ required: ['expression', 'variable'],+ type: 'object',+ },+ },+ {+ description: 'Solve algebraic equations or systems of equations symbolically.',+ name: CalculatorApiName.solve,+ parameters: {+ additionalProperties: false,+ properties: {+ equation: {+ description:+ 'The equation(s) to solve. Single equation (e.g., ["x^2 + 2*x + 1 = 0"]) or system of equations (e.g., ["2*x+y=5", "x-y=1"])',+ items: {+ type: 'string',+ },+ type: 'array',+ },+ variable: {+ description:+ 'Variable(s) to solve for. For single equation: array with one variable (optional, defaults to ["x"], e.g., ["x"]). For system of equations: array of variables (e.g., ["x", "y"])',+ items: {+ type: 'string',+ },+ type: 'array',+ },+ },+ required: ['equation'],+ type: 'object',+ },+ },+ ],+ identifier: CalculatorIdentifier,+ meta: {+ avatar: '🧮',+ description:+ 'Perform mathematical calculations, solve equations, and work with symbolic expressions',+ readme:+ 'Advanced mathematical calculator supporting basic arithmetic, algebraic equations, calculus operations, and symbolic math. Includes base conversion, equation solving, differentiation, integration, and more.',+ title: 'Calculator',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/packages/builtin-tool-calculator/src/systemRole.ts b/packages/builtin-tool-calculator/src/systemRole.tsnew file mode 100644index 00000000000..31b61ea5624--- /dev/null+++ b/packages/builtin-tool-calculator/src/systemRole.ts@@ -0,0 +1,115 @@+export const systemPrompt = `You have access to a Calculator tool powered by mathjs and nerdamer, capable of comprehensive mathematical computations, base conversions, and symbolic equation solving.++<core_capabilities>+1. **calculate**: Direct math expressions and unit conversions+2. **evaluate**: Complex expressions with variable substitution+3. **sort**: Sort numbers (ascending/descending/largest/smallest)+4. **base**: Convert between number bases (2-36)+5. **solve**: Algebraic equations and systems of equations+6. **differentiate**: Derivatives of mathematical expressions+7. **integrate**: Indefinite integrals+8. **defintegrate**: Definite integrals over specified intervals+9. **execute**: Generic nerdamer expressions for symbolic math+10. **limit**: Limits of expressions+</core_capabilities>++<tool_selection>+- **calculate**: Best for simple calculations, functions, matrices, complex numbers, unit conversions+ - Examples: "2 + 3 * 4", "sqrt(16)", "sin(30 deg)", "5 cm to inch", "25 degC to degF"+ - Uses mathjs syntax exclusively++- **evaluate**: Best for expressions with variables+ - Provide variables object: {"x": 5, "y": 3}+ - Example: Expression "x^2 + 2*x + 1" with x=5++- **base**: Best for base conversions+ - Requires numeric bases (2-36)+ - Supports string or number inputs+ - Example: Convert "1010" from base 2 to base 10++- **sort**: Best for sorting numbers+ - Parameters: numbers (array), mode (optional: "largest"|"smallest"|default), reverse (optional)+ - Returns sorted array or single value if mode specified+ - Example: sort({"numbers": [3.14, 2.718, 1.618], "mode": "largest"}) → "3.14"++- **solve**: Best for equations and systems+ - CRITICAL: equation MUST be array (even for single)+ - variable is optional - auto-detects if omitted+ - Single: {"equation": ["x^2 - 5*x + 6 = 0"], "variable": ["x"]} → [2, 3]+ - System: {"equation": ["2*x+y=5", "x-y=1"], "variable": ["x", "y"]} → {"x": "2", "y": "1"}+ - Supports: linear, quadratic, cubic, polynomial, systems++- **differentiate**: Best for computing derivatives+ - Parameters: expression, variable+ - Example: {"expression": "x^3", "variable": "x"} → "3*x^2"++- **integrate**: Best for computing indefinite integrals+ - Parameters: expression, variable+ - Example: {"expression": "x^3", "variable": "x"} → "(1/4)*x^4"++- **defintegrate**: Best for computing definite integrals over intervals+ - Parameters: expression, variable, lowerBound, upperBound+ - Example: {"expression": "x^2", "variable": "x", "lowerBound": 0, "upperBound": 1} → "1/3"+ - Supports numeric bounds and special values like "infinity", "-infinity", "pi"++- **execute**: Best for generic nerdamer symbolic math expressions+ - Parameters: expression (any valid nerdamer expression)+ - Examples: {"expression": "expand((x+1)^2)"} → "x^2+2*x+1"+ {"expression": "factor(x^2-1)"} → "(x-1)*(x+1)"+ {"expression": "partfrac(1/(x^2-1))"} → "1/2/(x-1)-1/2/(x+1)"+ {"expression": "toTeX(x^2+2*x+1)"} → "x^{2}+2x+1"+ {"expression": "simplify(x^2+2*x-x)"} → "x^2+x"++- **limit**: Best for computing limits+ - Parameters: expression, variable, point (optional: value or "infinity")+ - Example: {"expression": "sin(x)/x", "variable": "x", "point": "0"} → "1"+</tool_selection>++<mathjs_syntax>+**Units** - Use these formats:+- Temperature: "25 degC to degF" (NOT °C/°F)+- Length: "5 cm to inch"+- Weight: "1 kg to lb"+- Speed: "100 km/h to mph"+- Volume: "1 liter to gallon"++**Functions** - Follow mathjs names:+- Trig: sin(x), cos(x), tan(x) - use "deg" for degrees: sin(30 deg)+- Constants: pi, e, tau, phi+- Logs: log(x), log10(x), log2(x)+- Exp: exp(x), pow(x,y), sqrt(x)++**Complex Numbers**:+- Imaginary unit: i+- Examples: sqrt(-1), 3+4i, complex(3,4)++**Equations**:+- Power: x^2, x^3+- Multiplication: 2*x (explicit * required)+- Equality: x^2 - 5*x + 6 = 0+</mathjs_syntax>++<response_format>+- Return results directly, no original input+- Unit conversions: include units+- Equations: array (single) or object (systems)+- Calculus: symbolic expression result+</response_format>++<critical_rules>+1. Use mathjs syntax for ALL calculations+2. For solve: equation MUST be array (even for single)+3. Temperature: use "degC"/"degF", not °C/°F+4. Angles: use "deg" suffix for degrees+5. Base conversions: use numeric bases (2, not "binary")+6. For limits at specific values, specify point parameter+</critical_rules>++<error_handling>+- Invalid expressions: explain specific error+- Missing variables: operation fails+- Base errors: verify bases 2-36 and valid digits+- Equation errors: may have no/infinite solutions or need more equations+- Calculus errors: expression too complex or unsupported+</error_handling>+`;diff --git a/packages/builtin-tool-calculator/src/types.ts b/packages/builtin-tool-calculator/src/types.tsnew file mode 100644index 00000000000..f02cd61fc09--- /dev/null+++ b/packages/builtin-tool-calculator/src/types.ts@@ -0,0 +1,153 @@+export const CalculatorIdentifier = 'lobe-calculator';++export const CalculatorApiName = {+ base: 'base',+ calculate: 'calculate',+ defintegrate: 'defintegrate',+ differentiate: 'differentiate',+ evaluate: 'evaluate',+ execute: 'execute',+ integrate: 'integrate',+ limit: 'limit',+ solve: 'solve',+ sort: 'sort',+} as const;++export type CalculatorApiNameType = (typeof CalculatorApiName)[keyof typeof CalculatorApiName];++// Calculate API+export interface CalculateParams {+ expression: string;+ precision?: number;+}++export interface CalculateState {+ expression?: string;+ precision?: number;+ result?: number | string;+}++// Evaluate API (for more complex mathematical expressions with variables)+export interface EvaluateParams {+ expression: string;+ precision?: number;+ variables?: Record<string, number>;+}++export interface EvaluateState {+ expression?: string;+ precision?: number;+ result?: number | string;+ variables?: Record<string, number>;+}++// Base Conversion API+export interface BaseParams {+ fromBase: number;+ number: string | number;+ toBase: number;+}++export interface BaseState {+ convertedNumber?: string;+ decimalValue?: number;+ originalBase?: string;+ originalNumber?: string;+ targetBase?: string;+}++// Sort API+export interface SortParams {+ mode?: 'largest' | 'smallest';+ numbers: (string | number)[];+ precision?: number;+ reverse?: boolean;+}++export interface SortState {+ // Can be array, string, or object based on mode+ largest?: number | string;+ mode?: string;+ originalNumbers?: (string | number)[];+ precision?: number;+ result?: any;+ reverse?: boolean;+ smallest?: number | string;+ sorted?: (string | number)[];+}++// Nerdamer Equation Solver API+export interface SolveParams {+ equation: string[];+ variable?: string[];+}++export interface SolveState {+ equation?: string[];+ result?: string | string[];+ variable?: string[];+}++// Nerdamer Differentiate API+export interface DifferentiateParams {+ expression: string;+ variable: string;+}++export interface DifferentiateState {+ expression?: string;+ result?: string;+ variable?: string;+}++// Nerdamer Integrate API+export interface IntegrateParams {+ expression: string;+ variable: string;+}++export interface IntegrateState {+ expression?: string;+ result?: string;+ variable?: string;+}++// Nerdamer Definite Integral API+export interface DefintegrateParams {+ expression: string;+ lowerBound: number | string;+ upperBound: number | string;+ variable: string;+}++export interface DefintegrateState {+ expression?: string;+ lowerBound?: number | string;+ result?: string;+ upperBound?: number | string;+ variable?: string;+}++// Nerdamer Limit API+export interface LimitParams {+ expression: string;+ point?: string | number;+ variable: string;+}++export interface LimitState {+ expression?: string;+ point?: string | number;+ result?: string;+ variable?: string;+}++// Generic Nerdamer Execute API+export interface ExecuteParams {+ expression: string;+}++export interface ExecuteState {+ expression?: string;+ result?: string;+}diff --git a/packages/builtin-tool-calculator/tsconfig.json b/packages/builtin-tool-calculator/tsconfig.jsonnew file mode 100644index 00000000000..cf07830f64d--- /dev/null+++ b/packages/builtin-tool-calculator/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "node",+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src",+ "strict": true,+ "skipLibCheck": true,+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true+ },+ "exclude": ["node_modules"],+ "include": ["src/**/*"]+}diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex bb1238c7d73..155b2549234 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -1,4 +1,5 @@import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';+import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';@@ -14,6 +15,7 @@ import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';export const builtinToolIdentifiers: string[] = [AgentBuilderManifest.identifier,+ CalculatorManifest.identifier,LocalSystemManifest.identifier,WebBrowsingManifest.identifier,KnowledgeBaseManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 40be56c5e7b..a0882b9d9ea 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -1,4 +1,5 @@import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';+import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';@@ -116,4 +117,9 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: NotebookManifest,type: 'builtin',},+ {+ identifier: CalculatorManifest.identifier,+ manifest: CalculatorManifest,+ type: 'builtin',+ },];diff --git a/packages/const/src/recommendedSkill.ts b/packages/const/src/recommendedSkill.tsindex 3f930e8b2a2..be511142518 100644--- a/packages/const/src/recommendedSkill.ts+++ b/packages/const/src/recommendedSkill.ts@@ -16,6 +16,7 @@ export const RECOMMENDED_SKILLS: RecommendedSkillItem[] = [{ id: 'lobe-cloud-sandbox', type: RecommendedSkillType.Builtin },{ id: 'lobe-gtd', type: RecommendedSkillType.Builtin },{ id: 'lobe-notebook', type: RecommendedSkillType.Builtin },+ { id: 'lobe-calculator', type: RecommendedSkillType.Builtin },// Klavis skills{ id: 'gmail', type: RecommendedSkillType.Klavis },{ id: 'notion', type: RecommendedSkillType.Klavis },diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex aa9e49d8e5c..476b777ec64 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -832,6 +832,11 @@ When I am ___, I need ___'tools.builtins.lobe-artifacts.readme':'Generate and live-preview interactive UI components, data visualizations, charts, SVG graphics, and web applications. Create rich visual content that users can interact with directly.','tools.builtins.lobe-artifacts.title': 'Artifacts',+ 'tools.builtins.lobe-calculator.title': 'Calculator',+ 'tools.builtins.lobe-calculator.description':+ 'Perform mathematical calculations, solve equations, and work with symbolic expressions',+ 'tools.builtins.lobe-calculator.readme':+ 'Advanced mathematical calculator supporting basic arithmetic, algebraic equations, calculus operations, and symbolic math. Includes base conversion, equation solving, differentiation, integration, and more.','tools.builtins.lobe-cloud-sandbox.description':'Execute code, run commands, and manage files in a secure cloud environment','tools.builtins.lobe-cloud-sandbox.readme':diff --git a/src/server/services/toolExecution/serverRuntimes/calculator.ts b/src/server/services/toolExecution/serverRuntimes/calculator.tsnew file mode 100644index 00000000000..e1dd3ae2539--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/calculator.ts@@ -0,0 +1,14 @@+import { CalculatorExecutionRuntime, CalculatorManifest } from '@lobechat/builtin-tool-calculator';++import { type ServerRuntimeRegistration } from './types';++/**+ * Calculator Server Runtime+ * Pre-instantiated runtime (no per-request context needed)+ */+const runtime = new CalculatorExecutionRuntime();++export const calculatorRuntime: ServerRuntimeRegistration = {+ factory: () => runtime,+ identifier: CalculatorManifest.identifier,+};diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex 7bc9da954be..545a091863e 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -7,6 +7,7 @@* - Per-request runtimes (e.g., CloudSandbox - needs topicId, userId)*/import { type ToolExecutionContext } from '../types';+import { calculatorRuntime } from './calculator';import { cloudSandboxRuntime } from './cloudSandbox';import { memoryRuntime } from './memory';import { notebookRuntime } from './notebook';@@ -34,6 +35,7 @@ const registerRuntimes = (runtimes: ServerRuntimeRegistration[]) => {registerRuntimes([webBrowsingRuntime,cloudSandboxRuntime,+ calculatorRuntime,notebookRuntime,skillStoreRuntime,skillsRuntime,diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex 3ea53c9297c..18d1f77c45e 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -5,6 +5,7 @@* Executors are registered as class instances by identifier.*/import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';+import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-builder/executor';import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';@@ -124,6 +125,7 @@ const registerExecutors = (executors: IBuiltinToolExecutor[]): void => {// Register all executor instancesregisterExecutors([agentBuilderExecutor,+ calculatorExecutor,cloudSandboxExecutor,groupAgentBuilderExecutor,groupManagementExecutor,