@mcoda/codali 0.1.135-codali.18 → 0.1.135-codali.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/ORCHESTRATION.md +182 -4
- package/README.md +134 -5
- package/config/AGENTS.md +11 -0
- package/config/deterministic/install-python.mjs +16 -0
- package/config/deterministic/node-worker.mjs +77 -0
- package/config/deterministic/python-worker.py +222 -0
- package/config/deterministic/requirements.txt +6 -0
- package/config/docdex-tools-0.2.99.json +3977 -0
- package/config/documents/install-python.mjs +16 -0
- package/config/documents/requirements.txt +10 -0
- package/config/documents/worker.py +267 -0
- package/config/orchestration.schema.json +38 -3
- package/config/skills/planning/SKILL.md +13 -0
- package/dist/cli/TerminalCommand.d.ts.map +1 -1
- package/dist/cli/TerminalCommand.js +53 -20
- package/dist/cli/TerminalInput.d.ts +6 -0
- package/dist/cli/TerminalInput.d.ts.map +1 -1
- package/dist/cli/TerminalInput.js +3 -1
- package/dist/cli/ToolsCommand.d.ts.map +1 -1
- package/dist/cli/ToolsCommand.js +8 -1
- package/dist/cli/tui/TerminalLogo.d.ts +6 -0
- package/dist/cli/tui/TerminalLogo.d.ts.map +1 -0
- package/dist/cli/tui/TerminalLogo.js +26 -0
- package/dist/cli/tui/TerminalMarkdown.d.ts +5 -0
- package/dist/cli/tui/TerminalMarkdown.d.ts.map +1 -0
- package/dist/cli/tui/TerminalMarkdown.js +118 -0
- package/dist/cli/tui/TerminalPresentation.d.ts.map +1 -1
- package/dist/cli/tui/TerminalPresentation.js +12 -3
- package/dist/cli/tui/TerminalScreen.d.ts +1 -0
- package/dist/cli/tui/TerminalScreen.d.ts.map +1 -1
- package/dist/cli/tui/TerminalScreen.js +13 -6
- package/dist/cli/tui/TerminalSelection.d.ts +15 -0
- package/dist/cli/tui/TerminalSelection.d.ts.map +1 -0
- package/dist/cli/tui/TerminalSelection.js +38 -0
- package/dist/cli/tui/TerminalTui.d.ts +4 -0
- package/dist/cli/tui/TerminalTui.d.ts.map +1 -1
- package/dist/cli/tui/TerminalTui.js +96 -12
- package/dist/cli.js +1 -1
- package/dist/config/OrchestrationConfig.d.ts +18 -0
- package/dist/config/OrchestrationConfig.d.ts.map +1 -1
- package/dist/config/OrchestrationConfig.js +42 -2
- package/dist/docdex/DocdexCatalog.d.ts +12 -0
- package/dist/docdex/DocdexCatalog.d.ts.map +1 -0
- package/dist/docdex/DocdexCatalog.js +30 -0
- package/dist/docdex/DocdexClient.d.ts +8 -2
- package/dist/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/docdex/DocdexClient.js +86 -11
- package/dist/docdex/ManagedDocdex.d.ts +1 -0
- package/dist/docdex/ManagedDocdex.d.ts.map +1 -1
- package/dist/docdex/ManagedDocdex.js +25 -4
- package/dist/eval/TrustBenchmark.d.ts +94 -0
- package/dist/eval/TrustBenchmark.d.ts.map +1 -0
- package/dist/eval/TrustBenchmark.js +199 -0
- package/dist/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
- package/dist/eval/fixtures/TerminalRecoveryJourney.js +10 -1
- package/dist/permissions/PermissionGate.d.ts +1 -1
- package/dist/permissions/PermissionGate.d.ts.map +1 -1
- package/dist/permissions/PermissionGate.js +40 -2
- package/dist/permissions/WorkspacePermissions.d.ts +11 -0
- package/dist/permissions/WorkspacePermissions.d.ts.map +1 -0
- package/dist/permissions/WorkspacePermissions.js +42 -0
- package/dist/providers/ModelServiceError.js +1 -1
- package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/providers/OpenAiCompatibleProvider.js +3 -1
- package/dist/runtime/ComputedAnswer.d.ts +13 -0
- package/dist/runtime/ComputedAnswer.d.ts.map +1 -0
- package/dist/runtime/ComputedAnswer.js +75 -0
- package/dist/runtime/ContextCompression.d.ts +22 -0
- package/dist/runtime/ContextCompression.d.ts.map +1 -0
- package/dist/runtime/ContextCompression.js +53 -0
- package/dist/runtime/InspectionBudget.d.ts +8 -0
- package/dist/runtime/InspectionBudget.d.ts.map +1 -0
- package/dist/runtime/InspectionBudget.js +25 -0
- package/dist/runtime/InteractionContract.d.ts +42 -0
- package/dist/runtime/InteractionContract.d.ts.map +1 -0
- package/dist/runtime/InteractionContract.js +50 -0
- package/dist/runtime/InteractionRouter.d.ts +46 -5
- package/dist/runtime/InteractionRouter.d.ts.map +1 -1
- package/dist/runtime/InteractionRouter.js +108 -27
- package/dist/runtime/PreparedDocdex.d.ts +4 -0
- package/dist/runtime/PreparedDocdex.d.ts.map +1 -0
- package/dist/runtime/PreparedDocdex.js +55 -0
- package/dist/runtime/SessionController.d.ts +22 -0
- package/dist/runtime/SessionController.d.ts.map +1 -1
- package/dist/runtime/SessionController.js +721 -61
- package/dist/session/InstructionLoader.d.ts +5 -1
- package/dist/session/InstructionLoader.d.ts.map +1 -1
- package/dist/session/InstructionLoader.js +65 -19
- package/dist/session/SkillCatalog.d.ts +33 -0
- package/dist/session/SkillCatalog.d.ts.map +1 -0
- package/dist/session/SkillCatalog.js +194 -0
- package/dist/tools/SemanticToolRetrieval.d.ts +19 -0
- package/dist/tools/SemanticToolRetrieval.d.ts.map +1 -0
- package/dist/tools/SemanticToolRetrieval.js +52 -0
- package/dist/tools/ToolRetrieval.d.ts +7 -0
- package/dist/tools/ToolRetrieval.d.ts.map +1 -0
- package/dist/tools/ToolRetrieval.js +25 -0
- package/dist/tools/browser/BrowserTool.d.ts +9 -0
- package/dist/tools/browser/BrowserTool.d.ts.map +1 -0
- package/dist/tools/browser/BrowserTool.js +152 -0
- package/dist/tools/browser/BrowserWorker.d.ts +2 -0
- package/dist/tools/browser/BrowserWorker.d.ts.map +1 -0
- package/dist/tools/browser/BrowserWorker.js +51 -0
- package/dist/tools/calculation/CalculatorTool.d.ts +5 -0
- package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -0
- package/dist/tools/calculation/CalculatorTool.js +137 -0
- package/dist/tools/deterministic/DeterministicRuntime.d.ts +39 -0
- package/dist/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
- package/dist/tools/deterministic/DeterministicRuntime.js +98 -0
- package/dist/tools/deterministic/DeterministicTools.d.ts +8 -0
- package/dist/tools/deterministic/DeterministicTools.d.ts.map +1 -0
- package/dist/tools/deterministic/DeterministicTools.js +86 -0
- package/dist/tools/deterministic/node-worker.cjs +38 -0
- package/dist/tools/deterministic/python-worker.py +222 -0
- package/dist/tools/docdex/DocdexCatalogTools.d.ts +4 -0
- package/dist/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
- package/dist/tools/docdex/DocdexCatalogTools.js +58 -0
- package/dist/tools/docdex/DocdexTools.d.ts +2 -0
- package/dist/tools/docdex/DocdexTools.d.ts.map +1 -1
- package/dist/tools/docdex/DocdexTools.js +72 -105
- package/dist/tools/documents/DocumentRuntime.d.ts +12 -0
- package/dist/tools/documents/DocumentRuntime.d.ts.map +1 -0
- package/dist/tools/documents/DocumentRuntime.js +59 -0
- package/dist/tools/documents/DocumentTools.d.ts +19 -0
- package/dist/tools/documents/DocumentTools.d.ts.map +1 -0
- package/dist/tools/documents/DocumentTools.js +150 -0
- package/dist/tools/documents/worker.py +267 -0
- package/dist/tools/entities/AdesTool.d.ts +7 -0
- package/dist/tools/entities/AdesTool.d.ts.map +1 -0
- package/dist/tools/entities/AdesTool.js +59 -0
- package/dist/tools/research/TnlTool.d.ts +22 -0
- package/dist/tools/research/TnlTool.d.ts.map +1 -0
- package/dist/tools/research/TnlTool.js +246 -0
- package/dist/tools/shell/HostToolchain.d.ts.map +1 -1
- package/dist/tools/shell/HostToolchain.js +14 -2
- package/dist/tools/shell/IsolatedExecutor.d.ts +3 -2
- package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/tools/shell/IsolatedExecutor.js +34 -4
- package/dist/tools/system/TimeTool.d.ts +4 -0
- package/dist/tools/system/TimeTool.d.ts.map +1 -0
- package/dist/tools/system/TimeTool.js +22 -0
- package/dist/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
- package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
- package/dist/tools/verification/JavaScriptVerificationTool.js +71 -0
- package/dist/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
- package/dist/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
- package/dist/tools/verification/JavaScriptVerificationWorker.js +91 -0
- package/dist/tools/verification/VitestTool.d.ts +3 -0
- package/dist/tools/verification/VitestTool.d.ts.map +1 -0
- package/dist/tools/verification/VitestTool.js +128 -0
- package/package.json +15 -5
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Typed deterministic operations. Launched by Codali in an offline OS sandbox."""
|
|
2
|
+
import ast
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import decimal
|
|
9
|
+
import importlib.metadata
|
|
10
|
+
|
|
11
|
+
if sys.platform == "linux":
|
|
12
|
+
import resource
|
|
13
|
+
resource.setrlimit(resource.RLIMIT_AS, (2 * 1024**3, 2 * 1024**3))
|
|
14
|
+
resource.setrlimit(resource.RLIMIT_CPU, (6, 6))
|
|
15
|
+
|
|
16
|
+
os.environ["POLARS_MAX_THREADS"] = "2"
|
|
17
|
+
os.environ["OMP_NUM_THREADS"] = "2"
|
|
18
|
+
os.environ["OPENBLAS_NUM_THREADS"] = "1"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def require(condition, message):
|
|
22
|
+
if not condition:
|
|
23
|
+
raise ValueError(message)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def name(value):
|
|
27
|
+
require(isinstance(value, str) and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", value), "Invalid identifier")
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def expression(text, symbols, kind):
|
|
32
|
+
# Construct library nodes directly. SymPy parse_expr/sympify and Python eval
|
|
33
|
+
# are deliberately never used on model-supplied strings.
|
|
34
|
+
require(isinstance(text, str) and 0 < len(text) <= 4000, "Expression length out of range")
|
|
35
|
+
tree = ast.parse(text, mode="eval")
|
|
36
|
+
require(sum(1 for _ in ast.walk(tree)) <= 256, "Expression exceeds node limit")
|
|
37
|
+
if kind == "sympy":
|
|
38
|
+
import sympy as lib
|
|
39
|
+
functions = {n: getattr(lib, n) for n in ["sin", "cos", "tan", "exp", "log", "sqrt", "Abs"]}
|
|
40
|
+
constants = {"pi": lib.pi, "E": lib.E}
|
|
41
|
+
else:
|
|
42
|
+
import z3 as lib
|
|
43
|
+
functions = {"And": lib.And, "Or": lib.Or, "Not": lib.Not, "Implies": lib.Implies, "If": lib.If, "Distinct": lib.Distinct}
|
|
44
|
+
constants = {}
|
|
45
|
+
|
|
46
|
+
def visit(node, depth=0):
|
|
47
|
+
require(depth < 32, "Expression depth exceeded")
|
|
48
|
+
recur = lambda n: visit(n, depth + 1)
|
|
49
|
+
if isinstance(node, ast.Constant):
|
|
50
|
+
if type(node.value) is bool and kind == "z3":
|
|
51
|
+
return lib.BoolVal(node.value)
|
|
52
|
+
require(type(node.value) in (int, float) and math.isfinite(node.value) and abs(node.value) <= 10**100, "Only finite numeric literals are supported")
|
|
53
|
+
literal = ast.get_source_segment(text, node).replace("_", "")
|
|
54
|
+
return lib.Rational(literal) if kind == "sympy" else (lib.IntVal(literal) if type(node.value) is int else lib.RealVal(literal))
|
|
55
|
+
if isinstance(node, ast.Name):
|
|
56
|
+
require(node.id in symbols or node.id in constants, "Undeclared symbol: " + node.id)
|
|
57
|
+
return symbols[node.id] if node.id in symbols else constants[node.id]
|
|
58
|
+
if isinstance(node, ast.UnaryOp):
|
|
59
|
+
val = recur(node.operand)
|
|
60
|
+
if isinstance(node.op, ast.USub): return -val
|
|
61
|
+
if isinstance(node.op, ast.UAdd): return val
|
|
62
|
+
if isinstance(node.op, ast.Not) and kind == "z3": return lib.Not(val)
|
|
63
|
+
if isinstance(node, ast.BinOp):
|
|
64
|
+
left, right = recur(node.left), recur(node.right)
|
|
65
|
+
if isinstance(node.op, ast.Add): return left + right
|
|
66
|
+
if isinstance(node.op, ast.Sub): return left - right
|
|
67
|
+
if isinstance(node.op, ast.Mult): return left * right
|
|
68
|
+
if isinstance(node.op, ast.Div): return left / right
|
|
69
|
+
if isinstance(node.op, ast.Mod) and kind == "z3": return left % right
|
|
70
|
+
if isinstance(node.op, ast.Pow):
|
|
71
|
+
require(isinstance(node.right, ast.Constant) and type(node.right.value) is int and 0 <= node.right.value <= 100, "Power requires a literal integer 0..100")
|
|
72
|
+
return left ** right
|
|
73
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
|
|
74
|
+
require(node.func.id in functions and not node.keywords and 1 <= len(node.args) <= 32, "Unsupported function or arguments")
|
|
75
|
+
return functions[node.func.id](*[recur(arg) for arg in node.args])
|
|
76
|
+
if isinstance(node, ast.BoolOp) and kind == "z3":
|
|
77
|
+
return (lib.And if isinstance(node.op, ast.And) else lib.Or)(*[recur(v) for v in node.values])
|
|
78
|
+
if isinstance(node, ast.Compare) and kind == "z3":
|
|
79
|
+
values = [recur(node.left)] + [recur(v) for v in node.comparators]
|
|
80
|
+
comparisons = []
|
|
81
|
+
for op, left, right in zip(node.ops, values, values[1:]):
|
|
82
|
+
if isinstance(op, ast.Eq): comparisons.append(left == right)
|
|
83
|
+
elif isinstance(op, ast.NotEq): comparisons.append(left != right)
|
|
84
|
+
elif isinstance(op, ast.Lt): comparisons.append(left < right)
|
|
85
|
+
elif isinstance(op, ast.LtE): comparisons.append(left <= right)
|
|
86
|
+
elif isinstance(op, ast.Gt): comparisons.append(left > right)
|
|
87
|
+
elif isinstance(op, ast.GtE): comparisons.append(left >= right)
|
|
88
|
+
else: raise ValueError("Unsupported comparison")
|
|
89
|
+
return lib.And(*comparisons)
|
|
90
|
+
raise ValueError("Unsupported expression syntax: " + type(node).__name__)
|
|
91
|
+
return visit(tree.body)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def symbolic(a):
|
|
95
|
+
import sympy as s
|
|
96
|
+
declared = a.get("symbols", [])
|
|
97
|
+
require(isinstance(declared, list) and len(declared) <= 16, "Declare up to 16 symbols")
|
|
98
|
+
symbols = {name(v): s.Symbol(v) for v in declared}
|
|
99
|
+
expr = expression(a["expression"], symbols, "sympy")
|
|
100
|
+
op = a["operation"]
|
|
101
|
+
if op in ("simplify", "factor", "expand"):
|
|
102
|
+
result = {"simplify": s.simplify, "factor": s.factor, "expand": s.expand}[op](expr)
|
|
103
|
+
elif op in ("differentiate", "integrate", "solve"):
|
|
104
|
+
require(a.get("variable") in symbols, "Variable must be declared")
|
|
105
|
+
variable = symbols[a["variable"]]
|
|
106
|
+
if op == "differentiate": result = s.diff(expr, variable)
|
|
107
|
+
elif op == "integrate": result = s.integrate(expr, variable)
|
|
108
|
+
else:
|
|
109
|
+
roots = s.solve(expr, variable)
|
|
110
|
+
return {"solutions": [str(v) for v in roots], "substitutionResiduals": [str(s.simplify(expr.subs(variable, v))) for v in roots], "equation": str(expr) + " = 0", "scope": "Complex solutions under SymPy assumptions; singularities and conditional branches may need additional analysis"}
|
|
111
|
+
else: raise ValueError("Unsupported symbolic operation")
|
|
112
|
+
return {"result": str(result), "unevaluated": bool(result.has(s.Integral, s.Derivative)), "scope": "Exact symbolic expression; an indefinite integral omits the arbitrary additive constant"}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def constraints(a):
|
|
116
|
+
import z3 as z
|
|
117
|
+
require(isinstance(a["variables"], dict) and 1 <= len(a["variables"]) <= 32, "Declare 1..32 variables")
|
|
118
|
+
constructors = {"Int": z.Int, "Real": z.Real, "Bool": z.Bool}
|
|
119
|
+
variables = {}
|
|
120
|
+
for key, value in a["variables"].items():
|
|
121
|
+
require(value in constructors, "Unknown variable sort")
|
|
122
|
+
variables[name(key)] = constructors[value](key)
|
|
123
|
+
require(isinstance(a["constraints"], list) and 1 <= len(a["constraints"]) <= 64, "Use 1..64 constraints")
|
|
124
|
+
clauses = [expression(v, variables, "z3") for v in a["constraints"]]
|
|
125
|
+
require(all(z.is_bool(v) for v in clauses), "Constraints must be Boolean")
|
|
126
|
+
solver = z.Solver()
|
|
127
|
+
solver.set(timeout=2000, random_seed=0)
|
|
128
|
+
solver.add(*clauses)
|
|
129
|
+
status = solver.check()
|
|
130
|
+
if status == z.unknown: return {"status": "unknown", "reason": solver.reason_unknown()}
|
|
131
|
+
if status == z.unsat: return {"status": "unsat"}
|
|
132
|
+
model = solver.model()
|
|
133
|
+
return {"status": "sat", "model": {key: str(model.eval(v, model_completion=True)) for key, v in variables.items()},
|
|
134
|
+
"constraintsVerified": all(z.is_true(model.eval(v, model_completion=True)) for v in clauses)}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def query(a):
|
|
138
|
+
import duckdb as d
|
|
139
|
+
# DuckDB 2 has a separate asynchronous pool; threads alone does not bound it.
|
|
140
|
+
# Cap both pools before connection startup so the address-space limit holds.
|
|
141
|
+
connection = d.connect(":memory:", config={"enable_external_access": "false", "autoload_known_extensions": "false", "autoinstall_known_extensions": "false", "memory_limit": "128MB", "threads": "1", "async_threads": "1", "max_temp_directory_size": "0B"})
|
|
142
|
+
try:
|
|
143
|
+
tables = a.get("tables", [])
|
|
144
|
+
require(isinstance(tables, list) and len(tables) <= 8, "Use at most 8 input tables")
|
|
145
|
+
for table in tables:
|
|
146
|
+
table_name = name(table["name"])
|
|
147
|
+
columns = table["columns"]
|
|
148
|
+
require(isinstance(columns, dict) and 1 <= len(columns) <= 32, "Use 1..32 typed columns")
|
|
149
|
+
definitions = []
|
|
150
|
+
for key, value in columns.items():
|
|
151
|
+
name(key)
|
|
152
|
+
require(isinstance(value, str) and re.fullmatch(r"(?:VARCHAR|BIGINT|DOUBLE|BOOLEAN|DECIMAL\((?:[1-9]|[12][0-9]|3[0-8]),(?:[0-9]|[12][0-9]|3[0-8])\))", value), "Unsupported column type")
|
|
153
|
+
definitions.append('"' + key + '" ' + value)
|
|
154
|
+
connection.execute('CREATE TABLE "' + table_name + '" (' + ','.join(definitions) + ')')
|
|
155
|
+
rows = table["rows"]
|
|
156
|
+
require(isinstance(rows, list) and len(rows) <= 2000 and all(isinstance(row, list) and len(row) == len(columns) for row in rows), "Invalid table rows")
|
|
157
|
+
if rows: connection.executemany('INSERT INTO "' + table_name + '" VALUES (' + ','.join('?' for _ in columns) + ')', rows)
|
|
158
|
+
sql = a["sql"]
|
|
159
|
+
require(isinstance(sql, str) and 0 < len(sql) <= 8000, "SQL length out of range")
|
|
160
|
+
# Blocking volatile sources prevents accidental claims of reproducibility.
|
|
161
|
+
require(not re.search(r"\b(random|uuid|uuidv4|uuidv7|nextval|currval|now|today|current_date|current_time|current_timestamp|transaction_timestamp|setseed|query|query_table|read_blob|read_text|glob|getenv)\b", sql, re.I), "Volatile and external sources are unavailable")
|
|
162
|
+
statements = connection.extract_statements(sql)
|
|
163
|
+
require(len(statements) == 1 and statements[0].type == d.StatementType.SELECT, "Exactly one SELECT statement is allowed")
|
|
164
|
+
cursor = connection.execute(sql)
|
|
165
|
+
columns = [{"name": item[0], "type": str(item[1])} for item in cursor.description]
|
|
166
|
+
rows = cursor.fetchmany(1001)
|
|
167
|
+
return {"columns": columns, "rows": rows[:1000], "truncated": len(rows) > 1000, "ordering": "Only ORDER BY establishes row order"}
|
|
168
|
+
finally:
|
|
169
|
+
connection.close()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def dataframe(a):
|
|
173
|
+
import polars as p
|
|
174
|
+
require(isinstance(a["rows"], list) and len(a["rows"]) <= 2000, "Use at most 2000 rows")
|
|
175
|
+
frame = p.DataFrame(a["rows"], strict=True, infer_schema_length=None)
|
|
176
|
+
require(frame.width <= 32, "Use at most 32 columns")
|
|
177
|
+
steps = a["steps"]
|
|
178
|
+
require(isinstance(steps, list) and len(steps) <= 16, "Use at most 16 steps")
|
|
179
|
+
for step in steps:
|
|
180
|
+
op = step["operation"]
|
|
181
|
+
if op == "select": frame = frame.select(step["columns"])
|
|
182
|
+
elif op == "sort": frame = frame.sort(step["columns"], descending=step.get("descending", False), maintain_order=True)
|
|
183
|
+
elif op == "head":
|
|
184
|
+
require(type(step["count"]) is int and 0 <= step["count"] <= 1000, "Head count out of range")
|
|
185
|
+
frame = frame.head(step["count"])
|
|
186
|
+
elif op == "filter":
|
|
187
|
+
col, val = p.col(step["column"]), p.lit(step["value"])
|
|
188
|
+
comparisons = {"eq": lambda: col == val, "ne": lambda: col != val, "gt": lambda: col > val, "ge": lambda: col >= val, "lt": lambda: col < val, "le": lambda: col <= val}
|
|
189
|
+
require(step["comparison"] in comparisons, "Unknown comparison")
|
|
190
|
+
frame = frame.filter(comparisons[step["comparison"]]())
|
|
191
|
+
elif op == "aggregate":
|
|
192
|
+
aggregations = step["aggregations"]
|
|
193
|
+
require(isinstance(aggregations, list) and 1 <= len(aggregations) <= 16, "Use 1..16 aggregations")
|
|
194
|
+
expressions = []
|
|
195
|
+
for item in aggregations:
|
|
196
|
+
require(item["function"] in ("sum", "mean", "min", "max", "count", "n_unique", "median", "std"), "Unsupported aggregation")
|
|
197
|
+
expressions.append(getattr(p.col(item["column"]), item["function"])().alias(name(item["alias"])))
|
|
198
|
+
frame = frame.group_by(step["by"], maintain_order=True).agg(expressions) if step.get("by") else frame.select(expressions)
|
|
199
|
+
else: raise ValueError("Unsupported dataframe step")
|
|
200
|
+
return {"rows": frame.head(1000).to_dicts(), "schema": {key: str(value) for key, value in frame.schema.items()}, "rowCount": frame.height, "truncated": frame.height > 1000}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def clean(value):
|
|
204
|
+
if isinstance(value, decimal.Decimal): return str(value)
|
|
205
|
+
if type(value) is int and abs(value) > 9007199254740991: return str(value)
|
|
206
|
+
if isinstance(value, (list, tuple)): return [clean(v) for v in value]
|
|
207
|
+
if isinstance(value, dict): return {k: clean(v) for k, v in value.items()}
|
|
208
|
+
return value
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
with open("input.json", encoding="utf-8") as file:
|
|
213
|
+
request = json.load(file)
|
|
214
|
+
handlers = {"symbolic_math": (symbolic, "sympy"), "solve_constraints": (constraints, "z3-solver"), "query_data": (query, "duckdb"), "transform_data": (dataframe, "polars")}
|
|
215
|
+
handler, package = handlers[request["tool"]]
|
|
216
|
+
result = handler(request["args"])
|
|
217
|
+
result.update(library=package, version=importlib.metadata.version(package))
|
|
218
|
+
encoded = json.dumps(clean(result), allow_nan=False, separators=(",", ":"))
|
|
219
|
+
require(len(encoded) <= 96000, "Result exceeds output limit")
|
|
220
|
+
sys.stdout.write(encoded)
|
|
221
|
+
except Exception as error:
|
|
222
|
+
sys.stdout.write(json.dumps({"error": str(error)[:1000]}))
|