@mcoda/mswarm 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/README.md +5 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -2
- package/dist/runtime.js.map +1 -1
- package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/TerminalCommand.js +53 -20
- package/dist/vendor/codali/cli/TerminalInput.d.ts +6 -0
- package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -1
- package/dist/vendor/codali/cli/TerminalInput.js +3 -1
- package/dist/vendor/codali/cli/ToolsCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/ToolsCommand.js +8 -1
- package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts +6 -0
- package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts.map +1 -0
- package/dist/vendor/codali/cli/tui/TerminalLogo.js +26 -0
- package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts +5 -0
- package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts.map +1 -0
- package/dist/vendor/codali/cli/tui/TerminalMarkdown.js +118 -0
- package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalPresentation.js +12 -3
- package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts +1 -0
- package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalScreen.js +13 -6
- package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts +15 -0
- package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts.map +1 -0
- package/dist/vendor/codali/cli/tui/TerminalSelection.js +38 -0
- package/dist/vendor/codali/cli/tui/TerminalTui.d.ts +4 -0
- package/dist/vendor/codali/cli/tui/TerminalTui.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalTui.js +96 -12
- package/dist/vendor/codali/cli.js +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts +18 -0
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.js +42 -2
- package/dist/vendor/codali/docdex/DocdexCatalog.d.ts +12 -0
- package/dist/vendor/codali/docdex/DocdexCatalog.d.ts.map +1 -0
- package/dist/vendor/codali/docdex/DocdexCatalog.js +30 -0
- package/dist/vendor/codali/docdex/DocdexClient.d.ts +8 -2
- package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/DocdexClient.js +86 -11
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +1 -0
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/ManagedDocdex.js +25 -4
- package/dist/vendor/codali/eval/TrustBenchmark.d.ts +94 -0
- package/dist/vendor/codali/eval/TrustBenchmark.d.ts.map +1 -0
- package/dist/vendor/codali/eval/TrustBenchmark.js +199 -0
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +10 -1
- package/dist/vendor/codali/permissions/PermissionGate.d.ts +1 -1
- package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
- package/dist/vendor/codali/permissions/PermissionGate.js +40 -2
- package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts +11 -0
- package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts.map +1 -0
- package/dist/vendor/codali/permissions/WorkspacePermissions.js +42 -0
- package/dist/vendor/codali/providers/ModelServiceError.js +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +3 -1
- package/dist/vendor/codali/runtime/ComputedAnswer.d.ts +13 -0
- package/dist/vendor/codali/runtime/ComputedAnswer.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ComputedAnswer.js +75 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts +22 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ContextCompression.js +53 -0
- package/dist/vendor/codali/runtime/InspectionBudget.d.ts +8 -0
- package/dist/vendor/codali/runtime/InspectionBudget.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/InspectionBudget.js +25 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts +42 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/InteractionContract.js +50 -0
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts +46 -5
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InteractionRouter.js +108 -27
- package/dist/vendor/codali/runtime/PreparedDocdex.d.ts +4 -0
- package/dist/vendor/codali/runtime/PreparedDocdex.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/PreparedDocdex.js +55 -0
- package/dist/vendor/codali/runtime/SessionController.d.ts +22 -0
- package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/SessionController.js +721 -61
- package/dist/vendor/codali/session/InstructionLoader.d.ts +5 -1
- package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -1
- package/dist/vendor/codali/session/InstructionLoader.js +65 -19
- package/dist/vendor/codali/session/SkillCatalog.d.ts +33 -0
- package/dist/vendor/codali/session/SkillCatalog.d.ts.map +1 -0
- package/dist/vendor/codali/session/SkillCatalog.js +194 -0
- package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts +19 -0
- package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts.map +1 -0
- package/dist/vendor/codali/tools/SemanticToolRetrieval.js +52 -0
- package/dist/vendor/codali/tools/ToolRetrieval.d.ts +7 -0
- package/dist/vendor/codali/tools/ToolRetrieval.d.ts.map +1 -0
- package/dist/vendor/codali/tools/ToolRetrieval.js +25 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +9 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.js +152 -0
- package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts +2 -0
- package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts.map +1 -0
- package/dist/vendor/codali/tools/browser/BrowserWorker.js +51 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +5 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.js +137 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts +39 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.js +98 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts +8 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts.map +1 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +86 -0
- package/dist/vendor/codali/tools/deterministic/node-worker.cjs +38 -0
- package/dist/vendor/codali/tools/deterministic/python-worker.py +222 -0
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts +4 -0
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.js +58 -0
- package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
- package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/docdex/DocdexTools.js +72 -105
- package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts +12 -0
- package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts.map +1 -0
- package/dist/vendor/codali/tools/documents/DocumentRuntime.js +59 -0
- package/dist/vendor/codali/tools/documents/DocumentTools.d.ts +19 -0
- package/dist/vendor/codali/tools/documents/DocumentTools.d.ts.map +1 -0
- package/dist/vendor/codali/tools/documents/DocumentTools.js +150 -0
- package/dist/vendor/codali/tools/documents/worker.py +267 -0
- package/dist/vendor/codali/tools/entities/AdesTool.d.ts +7 -0
- package/dist/vendor/codali/tools/entities/AdesTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/entities/AdesTool.js +59 -0
- package/dist/vendor/codali/tools/research/TnlTool.d.ts +22 -0
- package/dist/vendor/codali/tools/research/TnlTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/research/TnlTool.js +246 -0
- package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/HostToolchain.js +14 -2
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +3 -2
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +34 -4
- package/dist/vendor/codali/tools/system/TimeTool.d.ts +4 -0
- package/dist/vendor/codali/tools/system/TimeTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/system/TimeTool.js +22 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +71 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.js +91 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts +3 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/VitestTool.js +128 -0
- package/dist/vendor/config/AGENTS.md +11 -0
- package/dist/vendor/config/deterministic/install-python.mjs +16 -0
- package/dist/vendor/config/deterministic/node-worker.mjs +77 -0
- package/dist/vendor/config/deterministic/python-worker.py +222 -0
- package/dist/vendor/config/deterministic/requirements.txt +6 -0
- package/dist/vendor/config/docdex-runtime.json +21 -0
- package/dist/vendor/config/docdex-tools-0.2.99.json +3977 -0
- package/dist/vendor/config/documents/install-python.mjs +16 -0
- package/dist/vendor/config/documents/requirements.txt +10 -0
- package/dist/vendor/config/documents/worker.py +267 -0
- package/dist/vendor/config/skills/planning/SKILL.md +13 -0
- package/package.json +11 -4
|
@@ -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]}))
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { DocdexClient } from "../../docdex/DocdexClient.js";
|
|
2
|
+
import { type ToolDefinition } from "../ToolTypes.js";
|
|
3
|
+
export declare const createDocdexCatalogTools: (client: DocdexClient, existing: ReadonlySet<string>) => ToolDefinition[];
|
|
4
|
+
//# sourceMappingURL=DocdexCatalogTools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DocdexCatalogTools.d.ts","sourceRoot":"","sources":["../../../src/tools/docdex/DocdexCatalogTools.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAG1E,eAAO,MAAM,wBAAwB,GAAI,QAAQ,YAAY,EAAE,UAAU,WAAW,CAAC,MAAM,CAAC,KAAG,cAAc,EAiC3G,CAAC"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { realpath } from "node:fs/promises";
|
|
3
|
+
import { docdexCatalog, docdexCatalogKind } from "../../docdex/DocdexCatalog.js";
|
|
4
|
+
import { ToolExecutionError } from "../ToolTypes.js";
|
|
5
|
+
const boundFields = new Set(["project_root", "repo_path", "repo_root", "current_repo_root", "repo_scope", "conversation_namespace", "agent_id", "agent", "caller_agent_id", "caller_model", "primary_cost_per_million", "allow_sensitive"]);
|
|
6
|
+
export const createDocdexCatalogTools = (client, existing) => docdexCatalog.filter(tool => !existing.has(tool.name)).map(entry => {
|
|
7
|
+
const kind = docdexCatalogKind(entry.name);
|
|
8
|
+
if (!kind)
|
|
9
|
+
throw Error(`Unclassified Docdex tool in bundled catalog: ${entry.name}`);
|
|
10
|
+
const properties = Object.fromEntries(Object.entries(entry.inputSchema.properties ?? {}).filter(([key]) => !boundFields.has(key)));
|
|
11
|
+
return { name: entry.name, description: entry.description, capability: kind === "web" ? "web" : "docdex", readOnly: kind === "read" || kind === "web",
|
|
12
|
+
inputSchema: { ...entry.inputSchema, properties, required: entry.inputSchema.required?.filter(key => !boundFields.has(key)), additionalProperties: false },
|
|
13
|
+
handler: async (raw, context) => {
|
|
14
|
+
const root = client.getRepoRoot();
|
|
15
|
+
if (!root)
|
|
16
|
+
throw new ToolExecutionError("docdex_context_missing", "Catalog operations require an explicitly bound local repository");
|
|
17
|
+
const args = { ...raw };
|
|
18
|
+
for (const key of boundFields)
|
|
19
|
+
delete args[key];
|
|
20
|
+
for (const field of ["project_root", "repo_root", "current_repo_root", "repo_scope"])
|
|
21
|
+
if (entry.inputSchema.properties?.[field])
|
|
22
|
+
args[field] = root;
|
|
23
|
+
if (entry.inputSchema.properties?.agent_id)
|
|
24
|
+
args.agent_id = "codali-terminal";
|
|
25
|
+
if (entry.inputSchema.properties?.allow_sensitive)
|
|
26
|
+
args.allow_sensitive = false;
|
|
27
|
+
if (entry.name === "docdex_conversation_hook")
|
|
28
|
+
args.wait_for_processing = true;
|
|
29
|
+
if (entry.name === "docdex_local_completion") {
|
|
30
|
+
args.agent = "model:configured-docdex-helper";
|
|
31
|
+
args.mode = "draft_only";
|
|
32
|
+
args.max_tokens = Math.min(2048, Number(args.max_tokens) || 1024);
|
|
33
|
+
}
|
|
34
|
+
// Catalog features may accept artifacts, never an unrestricted host path.
|
|
35
|
+
for (const key of ["artifact_path", "current_plan_path", "current_files", "paths", "file", "path"]) {
|
|
36
|
+
const value = args[key];
|
|
37
|
+
if (value === undefined)
|
|
38
|
+
continue;
|
|
39
|
+
const values = Array.isArray(value) ? value : [value];
|
|
40
|
+
for (const candidate of values) {
|
|
41
|
+
if (typeof candidate !== "string")
|
|
42
|
+
throw new ToolExecutionError("tool_invalid_args", "Expected repository-relative paths");
|
|
43
|
+
const target = path.resolve(root, candidate);
|
|
44
|
+
const relative = path.relative(root, target);
|
|
45
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
46
|
+
throw new ToolExecutionError("tool_permission_denied", "Docdex catalog paths must remain in the bound repository");
|
|
47
|
+
const actual = await realpath(target);
|
|
48
|
+
const realRoot = await realpath(root);
|
|
49
|
+
if (actual !== realRoot && !actual.startsWith(`${realRoot}${path.sep}`))
|
|
50
|
+
throw new ToolExecutionError("tool_permission_denied", "Docdex path resolves outside the repository");
|
|
51
|
+
await context.checkPath?.(actual, "read");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const result = await client.callCatalog(entry.name, args);
|
|
55
|
+
return { output: JSON.stringify(result), data: result };
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
});
|
|
@@ -34,6 +34,8 @@ export type RelevanceJudge = (input: {
|
|
|
34
34
|
results: unknown;
|
|
35
35
|
}) => Promise<boolean>;
|
|
36
36
|
export interface DocdexToolOptions {
|
|
37
|
+
/** Include the versioned, explicitly classified standard MCP catalog. */
|
|
38
|
+
includeCatalog?: boolean;
|
|
37
39
|
judgeRelevance?: RelevanceJudge;
|
|
38
40
|
/** Terminal clients authorize web research as a separate operation. */
|
|
39
41
|
allowSearchWebFallback?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DocdexTools.d.ts","sourceRoot":"","sources":["../../../src/tools/docdex/DocdexTools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"DocdexTools.d.ts","sourceRoot":"","sources":["../../../src/tools/docdex/DocdexTools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAmEjE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,GAC7B,OAAO,MAAM,GAAG,SAAS,EACzB,gBAAgB,MAAM,KACrB,MAAM,GAAG,SAWX,CAAC;AAwCF,0CAA0C;AAC1C,eAAO,MAAM,uBAAuB,QAAO,IAG1C,CAAC;AA0DF,eAAO,MAAM,iBAAiB,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SAO3D,CAAC;AA8GF;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;CAClB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAEvB,MAAM,WAAW,iBAAiB;IAChC,yEAAyE;IACzE,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,uEAAuE;IACvE,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC;AAED,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,YAAY,EACpB,UAAS,iBAAsB,KAC9B,cAAc,EAGhB,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createDocdexCatalogTools } from "./DocdexCatalogTools.js";
|
|
1
2
|
const toOutput = (payload) => ({
|
|
2
3
|
output: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2),
|
|
3
4
|
data: payload,
|
|
@@ -60,29 +61,6 @@ const hasWebFindings = (payload) => {
|
|
|
60
61
|
const fetches = discovery.fetches;
|
|
61
62
|
return Array.isArray(fetches) && fetches.length > 0;
|
|
62
63
|
};
|
|
63
|
-
/**
|
|
64
|
-
* Whether a web-research payload carries anything quotable. Docdex answers a
|
|
65
|
-
* cache hit with discovery metadata only, which reads as success but gives a
|
|
66
|
-
* model nothing to cite.
|
|
67
|
-
*/
|
|
68
|
-
const hasWebContent = (payload) => {
|
|
69
|
-
if (!isRecord(payload))
|
|
70
|
-
return false;
|
|
71
|
-
// Fetched pages first. `hits` is not evidence of a successful fetch: with
|
|
72
|
-
// forceWeb it still carries local index matches, so judging by it alone
|
|
73
|
-
// reports success for a call that downloaded nothing.
|
|
74
|
-
const discovery = isRecord(payload.webDiscovery) ? payload.webDiscovery : undefined;
|
|
75
|
-
const fetches = Array.isArray(discovery?.fetches) ? discovery.fetches : [];
|
|
76
|
-
if (fetches.some((page) => isRecord(page) && (page.ai_digested_content || page.content))) {
|
|
77
|
-
return true;
|
|
78
|
-
}
|
|
79
|
-
for (const key of ["web_context", "webContext"]) {
|
|
80
|
-
const value = payload[key];
|
|
81
|
-
if (Array.isArray(value) && value.length > 0)
|
|
82
|
-
return true;
|
|
83
|
-
}
|
|
84
|
-
return false;
|
|
85
|
-
};
|
|
86
64
|
/**
|
|
87
65
|
* Rewrites a path into the repo-relative form docdex accepts.
|
|
88
66
|
*
|
|
@@ -209,55 +187,62 @@ export const normalizeWebQuery = (value) => {
|
|
|
209
187
|
? collapsed.slice(0, MAX_WEB_QUERY_CHARS).trimEnd()
|
|
210
188
|
: collapsed;
|
|
211
189
|
};
|
|
212
|
-
/**
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* Reduces a web-research response to the pages it actually fetched.
|
|
217
|
-
*
|
|
218
|
-
* The raw response is the wrong shape twice over. The fetched pages — the whole
|
|
219
|
-
* point of the call — are buried at `webDiscovery.fetches`, where the evidence
|
|
220
|
-
* normalizer does not look, while `hits` holds whatever the *local* index
|
|
221
|
-
* matched. For an external question those hits are repo source files, so a
|
|
222
|
-
* question about a central bank's interest rate came back citing eight files
|
|
223
|
-
* from this repository and none of the eight pages just downloaded.
|
|
224
|
-
*
|
|
225
|
-
* Suppressing local hits by asking docdex to skip its local search does not
|
|
226
|
-
* work: docdex indexes the pages it fetches and serves them back through that
|
|
227
|
-
* same path, so skipping it returns nothing at all. The response has to be
|
|
228
|
-
* reshaped here instead.
|
|
229
|
-
*/
|
|
190
|
+
/** Keep web evidence readable inside the smallest native inspection result cap. */
|
|
191
|
+
const MAX_WEB_OUTPUT_CHARS = 3800;
|
|
192
|
+
/** Preserve discovery links without treating an unvisited result as fetched evidence. */
|
|
230
193
|
const toWebResearchOutput = (payload) => {
|
|
231
|
-
if (!isRecord(payload))
|
|
194
|
+
if (!isRecord(payload) || !isRecord(payload.webDiscovery))
|
|
232
195
|
return payload;
|
|
233
|
-
const discovery =
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
"";
|
|
248
|
-
return {
|
|
249
|
-
url: page.url,
|
|
250
|
-
content: body.slice(0, MAX_WEB_PAGE_CHARS),
|
|
251
|
-
...(page.relevance_score !== undefined ? { relevanceScore: page.relevance_score } : {}),
|
|
252
|
-
};
|
|
253
|
-
})
|
|
254
|
-
.filter((page) => page.content.trim().length > 0);
|
|
255
|
-
if (pages.length === 0)
|
|
256
|
-
return payload;
|
|
257
|
-
return {
|
|
258
|
-
query: isRecord(discovery?.discovery) ? discovery.discovery.query : undefined,
|
|
259
|
-
pages,
|
|
196
|
+
const discovery = payload.webDiscovery;
|
|
197
|
+
const inner = isRecord(discovery.discovery) ? discovery.discovery : discovery;
|
|
198
|
+
const fetches = Array.isArray(discovery.fetches) ? discovery.fetches.filter(isRecord) : [];
|
|
199
|
+
const results = Array.isArray(inner.results) ? inner.results.filter(isRecord) : [];
|
|
200
|
+
// Never truncate a URL into a different citation. Oversized/invalid URLs are omitted.
|
|
201
|
+
const validUrl = (value) => {
|
|
202
|
+
if (typeof value !== "string" || value.length > 800)
|
|
203
|
+
return false;
|
|
204
|
+
try {
|
|
205
|
+
return ["http:", "https:"].includes(new URL(value).protocol);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
260
210
|
};
|
|
211
|
+
const pages = fetches.filter(page => validUrl(page.url))
|
|
212
|
+
.sort((a, b) => Number(b.relevance_score ?? 0) - Number(a.relevance_score ?? 0)).slice(0, 6)
|
|
213
|
+
.map(page => {
|
|
214
|
+
const raw = typeof page.content === "string" ? page.content.trim() : "";
|
|
215
|
+
const body = raw || (typeof page.ai_digested_content === "string" ? page.ai_digested_content : "");
|
|
216
|
+
return { url: page.url, content: body.slice(0, 1500),
|
|
217
|
+
evidenceType: raw ? "fetched_excerpt" : "generated_summary", truncated: body.length > 1500 };
|
|
218
|
+
}).filter(page => page.content.length > 0);
|
|
219
|
+
const fetched = new Set(pages.map(page => page.url));
|
|
220
|
+
const discoveries = results.filter(item => validUrl(item.url)).slice(0, 8).map(item => ({
|
|
221
|
+
url: item.url, title: typeof item.title === "string" ? item.title.slice(0, 120) : "",
|
|
222
|
+
visited: fetched.has(item.url),
|
|
223
|
+
}));
|
|
224
|
+
const output = { query: typeof inner.query === "string" ? inner.query.slice(0, 400) : undefined,
|
|
225
|
+
notice: "Discovery links and generated summaries are leads, not verified primary sources. Open the relevant page to verify claims; cite only URLs actually retrieved.",
|
|
226
|
+
pages, discoveries, truncated: pages.some(page => page.truncated) || pages.length < fetches.length || discoveries.length < results.length };
|
|
227
|
+
// Account for JSON escaping and metadata, retaining valid JSON at the tool-loop cap.
|
|
228
|
+
while (JSON.stringify(output, null, 2).length > MAX_WEB_OUTPUT_CHARS) {
|
|
229
|
+
output.truncated = true;
|
|
230
|
+
const longest = pages.reduce((best, page) => !best || page.content.length > best.content.length ? page : best, undefined);
|
|
231
|
+
if (longest && longest.content.length > 200) {
|
|
232
|
+
longest.content = longest.content.slice(0, Math.max(200, longest.content.length - 300));
|
|
233
|
+
longest.truncated = true;
|
|
234
|
+
}
|
|
235
|
+
else if (discoveries.length > 1)
|
|
236
|
+
discoveries.pop();
|
|
237
|
+
else if (pages.length)
|
|
238
|
+
pages.pop();
|
|
239
|
+
else if (discoveries.length)
|
|
240
|
+
discoveries.pop();
|
|
241
|
+
else
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
// A visited link may have lost its excerpt to the bound; visited still records a real fetch.
|
|
245
|
+
return output;
|
|
261
246
|
};
|
|
262
247
|
/** Hits to re-snippet. Enough to cover the answer, few enough to stay quick. */
|
|
263
248
|
const QUERY_SNIPPET_HITS = 3;
|
|
@@ -314,7 +299,10 @@ const withDocdexMetadata = (tools) => tools.map((tool) => ({
|
|
|
314
299
|
readOnly: tool.readOnly ?? !DOCDEX_WRITE_TOOLS.has(tool.name),
|
|
315
300
|
capability: tool.capability ?? docdexCapabilityFor(tool.name),
|
|
316
301
|
}));
|
|
317
|
-
export const createDocdexTools = (client, options = {}) =>
|
|
302
|
+
export const createDocdexTools = (client, options = {}) => {
|
|
303
|
+
const tools = withDocdexMetadata([...docdexToolDefinitions(client, options), ...continuityTools(client)]);
|
|
304
|
+
return options.includeCatalog ? [...tools, ...createDocdexCatalogTools(client, new Set(tools.map(tool => tool.name)))] : tools;
|
|
305
|
+
};
|
|
318
306
|
const continuityTools = (client) => {
|
|
319
307
|
const single = (name, description, key, call) => ({
|
|
320
308
|
name, description, inputSchema: { type: "object", properties: { [key]: { type: "string", minLength: 1, maxLength: 12000 } }, required: [key], additionalProperties: false },
|
|
@@ -358,8 +346,9 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
358
346
|
{
|
|
359
347
|
name: "docdex_search",
|
|
360
348
|
description: "Search the indexed repository and organizational memory for code, docs, and prior decisions. " +
|
|
361
|
-
|
|
362
|
-
|
|
349
|
+
(options.allowSearchWebFallback === false
|
|
350
|
+
? "This tool searches the local repository only; use an advertised web research tool for external information. "
|
|
351
|
+
: "Searches locally first and falls back to the web when the local index has nothing relevant. ") +
|
|
363
352
|
"Returns file paths, doc ids, and for the top results a snippet taken from the part of the " +
|
|
364
353
|
"file that matches the query. For more of a file, follow up with docdex_symbols for its " +
|
|
365
354
|
"signatures or docdex_open for a specific range of lines.",
|
|
@@ -413,7 +402,7 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
413
402
|
},
|
|
414
403
|
{
|
|
415
404
|
name: "docdex_open",
|
|
416
|
-
description: "Read
|
|
405
|
+
description: "Read a file slice by repo-relative path or search doc id. Path ranges clamp to file bounds by default and return the actual line range; set clamp:false to require an exact range. Use head when the file length is unknown.",
|
|
417
406
|
inputSchema: {
|
|
418
407
|
type: "object",
|
|
419
408
|
properties: {
|
|
@@ -430,7 +419,7 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
430
419
|
handler: async (args) => {
|
|
431
420
|
const { docId, path, window, textOnly, startLine, endLine, head, clamp } = args;
|
|
432
421
|
if (path) {
|
|
433
|
-
const result = await client.openFile(path, { startLine, endLine, head, clamp });
|
|
422
|
+
const result = await client.openFile(path, { startLine, endLine, head, clamp: clamp ?? true });
|
|
434
423
|
return toOutput(result);
|
|
435
424
|
}
|
|
436
425
|
if (!docId) {
|
|
@@ -443,8 +432,7 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
443
432
|
{
|
|
444
433
|
name: "docdex_symbols",
|
|
445
434
|
description: "List the definitions in a file with their exact signatures and line numbers — functions, " +
|
|
446
|
-
"classes, methods, exported constants. Use after docdex_search
|
|
447
|
-
"actually contains, since search snippets only show the file's opening lines.",
|
|
435
|
+
"classes, methods, exported constants. Use after docdex_search for exact structure beyond its bounded excerpts.",
|
|
448
436
|
inputSchema: {
|
|
449
437
|
type: "object",
|
|
450
438
|
required: ["path"],
|
|
@@ -562,7 +550,7 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
562
550
|
},
|
|
563
551
|
{
|
|
564
552
|
name: "docdex_open_file",
|
|
565
|
-
description: "Open a file by path via docdex (MCP).",
|
|
553
|
+
description: "Open a file by path via docdex (MCP). Ranges clamp to file bounds by default and return the actual line range; set clamp:false to require an exact range.",
|
|
566
554
|
inputSchema: {
|
|
567
555
|
type: "object",
|
|
568
556
|
required: ["path"],
|
|
@@ -576,7 +564,7 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
576
564
|
},
|
|
577
565
|
handler: async (args) => {
|
|
578
566
|
const { path, startLine, endLine, head, clamp } = args;
|
|
579
|
-
const result = await client.openFile(path, { startLine, endLine, head, clamp });
|
|
567
|
+
const result = await client.openFile(path, { startLine, endLine, head, clamp: clamp ?? true });
|
|
580
568
|
return toOutput(result);
|
|
581
569
|
},
|
|
582
570
|
},
|
|
@@ -656,7 +644,7 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
656
644
|
query: { type: "string" },
|
|
657
645
|
forceWeb: { type: "boolean" },
|
|
658
646
|
skipLocalSearch: { type: "boolean" },
|
|
659
|
-
webLimit: { type: "
|
|
647
|
+
webLimit: { type: "integer", minimum: 1, maximum: 5 },
|
|
660
648
|
noCache: { type: "boolean" },
|
|
661
649
|
},
|
|
662
650
|
},
|
|
@@ -682,8 +670,8 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
682
670
|
try {
|
|
683
671
|
result = await client.webResearch(normalizedQuery, {
|
|
684
672
|
forceWeb: forceWeb ?? true,
|
|
685
|
-
skipLocalSearch,
|
|
686
|
-
webLimit,
|
|
673
|
+
skipLocalSearch: skipLocalSearch ?? true,
|
|
674
|
+
webLimit: webLimit ?? 3,
|
|
687
675
|
noCache,
|
|
688
676
|
});
|
|
689
677
|
}
|
|
@@ -694,30 +682,9 @@ const docdexToolDefinitions = (client, options) => [
|
|
|
694
682
|
}
|
|
695
683
|
throw error;
|
|
696
684
|
}
|
|
697
|
-
//
|
|
698
|
-
//
|
|
699
|
-
//
|
|
700
|
-
// was standing in for.
|
|
701
|
-
if (!noCache && !hasWebContent(result)) {
|
|
702
|
-
try {
|
|
703
|
-
const fresh = await client.webResearch(normalizedQuery, {
|
|
704
|
-
forceWeb: forceWeb ?? true,
|
|
705
|
-
skipLocalSearch,
|
|
706
|
-
webLimit,
|
|
707
|
-
noCache: true,
|
|
708
|
-
});
|
|
709
|
-
if (hasWebContent(fresh)) {
|
|
710
|
-
result = fresh;
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
catch (error) {
|
|
714
|
-
// Keep the cached response rather than failing a search that worked —
|
|
715
|
-
// but a refusal is worth remembering, so the next question does not
|
|
716
|
-
// spend another request discovering the same thing.
|
|
717
|
-
if (isWebQuotaRefusal(error))
|
|
718
|
-
noteWebRefusal(error);
|
|
719
|
-
}
|
|
720
|
-
}
|
|
685
|
+
// An empty/unavailable result is still an outcome. Do not spend a second
|
|
686
|
+
// metered search inside one tool receipt; a deliberate noCache retry must
|
|
687
|
+
// be a new native call, subject to the normal step and permission budget.
|
|
721
688
|
return toOutput(toWebResearchOutput(result));
|
|
722
689
|
},
|
|
723
690
|
},
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type DocumentToolOptions } from "./DocumentTools.js";
|
|
2
|
+
import type { DeterministicRuntimeCheck } from "../deterministic/DeterministicRuntime.js";
|
|
3
|
+
export declare function inspectDocumentRuntime(options?: DocumentToolOptions): Promise<{
|
|
4
|
+
pythonRoot: string;
|
|
5
|
+
installed: boolean;
|
|
6
|
+
workerSha256: string | undefined;
|
|
7
|
+
checkCommand: string;
|
|
8
|
+
installCommand: string;
|
|
9
|
+
note: string;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function checkDocumentRuntime(options?: DocumentToolOptions, signal?: AbortSignal): Promise<DeterministicRuntimeCheck[]>;
|
|
12
|
+
//# sourceMappingURL=DocumentRuntime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DocumentRuntime.d.ts","sourceRoot":"","sources":["../../../src/tools/documents/DocumentRuntime.ts"],"names":[],"mappings":"AAIA,OAAO,EAAkD,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE9G,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAE1F,wBAAsB,sBAAsB,CAAC,OAAO,GAAE,mBAAwB;;;;;;;GAO7E;AAED,wBAAsB,oBAAoB,CAAC,OAAO,GAAE,mBAAwB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,yBAAyB,EAAE,CAAC,CA0BxI"}
|