Repository navigation
Expand file tree
/
Copy pathtools.py
More file actions
238 lines (226 loc) · 8.61 KB
/
Copy pathtools.py
File metadata and controls
238 lines (226 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""Invoke existing tools directly, without an LLM or MCP transport."""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import sys
import uuid
from dataclasses import asdict
from pathlib import Path
from typing import Any
from aiohttp import ClientError
from jsonschema import ValidationError, validate
from sqlalchemy.exc import SQLAlchemyError
from ...core.identity import Identity
from ...tenancy.schema_search import schema_index
from ...tenancy.tool_runtime import build_tool_context
from ...tools.bound_metric import bind_view
from ...tools.context_candidates import decide_candidate
from ..metadata_options import parse_metadata_args
logger = logging.getLogger(__name__)
async def execute(ctx, calls):
results = []
for call in calls:
call_id = uuid.uuid4().hex
logger.info("cli_tool_start tool=%s call_id=%s", call["name"], call_id)
result = await ctx.tools.dispatch(call["name"], call["arguments"], ctx, call_id)
results.append(
{
"call_id": result.call_id,
"content": result.content,
"is_error": result.is_error,
}
)
if result.is_error:
logger.warning("cli_tool_failed tool=%s call_id=%s", call["name"], call_id)
break
logger.info("cli_tool_done tool=%s call_id=%s", call["name"], call_id)
return results
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--user-id", required=True)
parser.add_argument("--org-id", required=True)
parser.add_argument("--team-id")
parser.add_argument("--admin", action="store_true")
parser.add_argument("--store", default=":memory:")
commands = parser.add_subparsers(dest="command", required=True)
decision = commands.add_parser(
"decide-context", help="Operator review of a proposed definition"
)
decision.add_argument("candidate_id")
choice = decision.add_mutually_exclusive_group(required=True)
choice.add_argument("--approve", action="store_true")
choice.add_argument("--reject", action="store_true")
commands.add_parser("list", help="Print tool names and JSON argument schemas")
bind = commands.add_parser(
"bind-oracle-view", help="Confirm a metric view for a registered definition"
)
bind.add_argument("--term", required=True)
bind.add_argument("--layer", required=True, choices=("org", "team", "user"))
bind.add_argument("--definition", required=True)
bind.add_argument("--contract", required=True, type=Path)
commands.add_parser(
"index-schema", help="Refresh Qdrant for this organization and database"
)
call_parser = commands.add_parser("call", help="Invoke one tool")
call_parser.add_argument("name")
batch = commands.add_parser(
"batch", help="Run a JSON array of calls in one process"
)
for command in (call_parser, batch):
source = command.add_mutually_exclusive_group()
source.add_argument(
"--args", default=None, help="JSON object, or array for batch"
)
source.add_argument(
"--args-file", help="Read JSON from a file; '-' reads stdin"
)
args = parse_metadata_args(parser, argv)
logging.basicConfig(level=logging.INFO)
ctx = None
output: dict[str, Any]
try:
if not args.user_id.strip() or not args.org_id.strip():
raise ValueError("user and org IDs must not be blank")
ctx = build_tool_context(
Identity(
user_id=args.user_id,
guild_id=args.org_id,
channel_id=args.team_id,
is_admin=args.admin,
),
store_path=args.store,
metadata_url=args.metadata_url,
initialize_metadata=args.initialize_metadata,
)
specs = {spec.name: spec for spec in ctx.tools.specs()}
if args.command == "decide-context":
output = asyncio.run(
decide_candidate(ctx, args.candidate_id, approve=args.approve)
)
status = 0
elif args.command == "bind-oracle-view":
output = asyncio.run(
bind_view(
ctx,
args.term,
args.layer,
args.definition,
json.loads(args.contract.read_text()),
)
)
status = 0
elif args.command == "index-schema":
index = schema_index(ctx.explorer)
if not index or ctx.explorer is None:
raise ValueError(
"Configure a persistent DB, Qdrant and an embedding endpoint"
)
output = {
"indexed_tables": asyncio.run(
index.refresh(ctx.identity.kv_scope, ctx.explorer)
)
}
status = 0
elif args.command == "list":
output = {
"tools": [
{
**asdict(spec),
"parameters": {
**spec.parameters,
"additionalProperties": False,
},
}
for spec in specs.values()
]
}
status = 0
else:
raw = (
args.args
if args.args is not None
else ("[]" if args.command == "batch" else "{}")
)
if args.args_file:
raw = (
sys.stdin.read()
if args.args_file == "-"
else Path(args.args_file).read_text()
)
value = json.loads(raw)
calls = (
value
if args.command == "batch"
else [{"name": args.name, "arguments": value}]
)
validate(
calls,
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["name", "arguments"],
"properties": {
"name": {"type": "string"},
"arguments": {"type": "object"},
},
"additionalProperties": False,
},
},
)
# Validate the whole batch before any tool performs a metadata write.
for call in calls:
if call["name"] not in specs:
raise ValueError(f"unknown tool: {call['name']}")
if call["name"] == "run_sql":
validate(
call["arguments"],
{
"oneOf": [
{"required": ["sql"]},
{
"required": [
"metric_term",
"period_start",
"period_end",
]
},
]
},
)
validate(
call["arguments"],
{**specs[call["name"]].parameters, "additionalProperties": False},
)
results = asyncio.run(execute(ctx, calls))
output = (
results[0]
if args.command == "call"
else {
"results": results,
"completed": len(results),
"requested": len(calls),
}
)
status = 1 if any(result["is_error"] for result in results) else 0
except SQLAlchemyError as exc:
logger.error("oracle_operation_failed error_type=%s", type(exc).__name__)
output = {
"is_error": True,
"content": "Cannot access Oracle metadata or verify the view with this connection and account.",
}
status = 2
except (ValueError, RuntimeError, OSError, ValidationError, ClientError) as exc:
logger.warning("cli_input_failed error_type=%s", type(exc).__name__)
output = {"is_error": True, "content": str(exc)}
status = 2
finally:
if ctx is not None and ctx.store is not None:
ctx.store.close()
print(json.dumps(output, ensure_ascii=False))
return status
if __name__ == "__main__":
raise SystemExit(main())