File size: 8,026 Bytes
81d22e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import glob as globlib, json, os, re, subprocess, openai, inspect
from datetime import datetime

MODEL = "claude-haiku-4.5"
RESET, BOLD, DIM = "\033[0m", "\033[1m", "\033[2m"
BLUE, CYAN, GREEN, YELLOW, RED = (
    "\033[34m",
    "\033[36m",
    "\033[32m",
    "\033[33m",
    "\033[31m",
)

CORE_TOOLS = {}
HIDDEN_TOOLS = {}
ACTIVATED_TOOLS = set()

def get_schema(f):
    """Generate OpenAI tool schema from function signature and docstring"""
    sig = inspect.signature(f)
    doc = inspect.getdoc(f) or ""
    properties = {}
    required = []
    for name, param in sig.parameters.items():
        p_type = "string"
        if param.annotation == int or param.annotation == float: p_type = "number"
        elif param.annotation == bool: p_type = "boolean"
        properties[name] = {"type": p_type}
        if param.default is inspect.Parameter.empty: required.append(name)
    return {
        "type": "function",
        "function": {
            "name": f.__name__,
            "description": doc,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": required,
            },
        },
    }

def tool(f):
    """Decorator for hidden tools"""
    HIDDEN_TOOLS[f.__name__] = {"fn": f, "schema": get_schema(f)}
    return f

def core_tool(f):
    """Decorator for core tools"""
    CORE_TOOLS[f.__name__] = {"fn": f, "schema": get_schema(f)}
    return f

@core_tool
def search_tools(query: str):
    """Search for hidden tools by fuzzy matching name, description, or parameters"""
    results = []
    q = query.lower()
    for name, data in HIDDEN_TOOLS.items():
        schema = data["schema"]["function"]
        desc = schema.get("description", "").lower()
        if q in name.lower() or q in desc or q in json.dumps(schema.get("parameters", {})):
            results.append(data["schema"])
            ACTIVATED_TOOLS.add(name)
    return json.dumps(results) if results else "No tools found"

@core_tool
def read(path: str, offset: int = 0, limit: int = None):
    """Read file with line numbers"""
    with open(path) as f:
        lines = f.readlines()
    l_limit = limit if limit is not None else len(lines)
    selected = lines[offset : offset + l_limit] if limit else lines[offset:]
    return "".join(f"{offset + idx + 1:4}| {line}" for idx, line in enumerate(selected))

@core_tool
def write(path: str, content: str):
    """Write content to file"""
    with open(path, "w") as f:
        f.write(content)
    return "ok"

@core_tool
def edit(path: str, old: str, new: str, all: bool = False):
    """Replace old with new in file"""
    with open(path) as f:
        text = f.read()
    if old not in text: return "error: old_string not found"
    count = text.count(old)
    if not all and count > 1: return f"error: old_string appears {count} times, must be unique (use all=true)"
    replacement = text.replace(old, new) if all else text.replace(old, new, 1)
    with open(path, "w") as f:
        f.write(replacement)
    return "ok"

@core_tool
def glob(pat: str, path: str = "."):
    """Find files by pattern"""
    pattern = (path + "/" + pat).replace("//", "/")
    files = globlib.glob(pattern, recursive=True)
    files = sorted(files, key=lambda f: os.path.getmtime(f) if os.path.isfile(f) else 0, reverse=True)
    return "\n".join(files) or "none"

@core_tool
def grep(pat: str, path: str = "."):
    """Search files for regex pattern"""
    pattern = re.compile(pat)
    hits = []
    for filepath in globlib.glob(path + "/**", recursive=True):
        try:
            with open(filepath) as f:
                for line_num, line in enumerate(f, 1):
                    if pattern.search(line): hits.append(f"{filepath}:{line_num}:{line.rstrip()}")
        except: pass
    return "\n".join(hits[:50]) or "none"

@core_tool
def bash(cmd: str):
    """Run shell command"""
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
    return (result.stdout + result.stderr).strip() or "(empty)"

@tool
def get_time():
    """Get current time"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

@tool
def get_weather():
    """Get current weather information based on the season"""
    now = datetime.now()
    month = now.strftime("%B")
    m = now.month
    if m in [12, 1, 2]: season = "winter"
    elif m in [3, 4, 5]: season = "spring"
    elif m in [6, 7, 8]: season = "summer"
    else: season = "autumn"
    return f"Its {month}, its the {season} season.."

def run_tool(name, args):
    try:
        if name in CORE_TOOLS: return CORE_TOOLS[name]["fn"](**args)
        if name in HIDDEN_TOOLS: return HIDDEN_TOOLS[name]["fn"](**args)
        return f"error: tool {name} not found"
    except Exception as err:
        return f"error: {err}"

client = openai.OpenAI(
    api_key=os.environ.get("POE_API_KEY", ""),
    base_url="https://api.poe.com/v1",
)

def separator():
    try: cols = os.get_terminal_size().columns
    except: cols = 80
    return f"{DIM}{'─' * min(cols, 80)}{RESET}"

def render_markdown(text):
    return re.sub(r"\*\*(.+?)\*\*", f"{BOLD}\\1{RESET}", text)

def main():
    print(f"{RED}ag-mini-cli{RESET} | {DIM}{MODEL} | {os.getcwd()}{RESET}\n")
    messages = []
    system_prompt = f"""
    You are a concise coding assistant. cwd: {os.getcwd()}

    When you are tasked with something that you do not have the tools to do, you should try searching for tools that can help you.

    Search for tools like weather, extra operations, math, etc. 

    """

    while True:
        try:
            print(separator())
            user_input = input(f"{BOLD}{BLUE}{RESET} ").strip()
            print(separator())
            if not user_input: continue
            if user_input in ("/q", "exit"): break
            if user_input == "/c":
                messages = []
                ACTIVATED_TOOLS.clear()
                print(f"{GREEN}⏺ Cleared conversation{RESET}")
                continue

            messages.append({"role": "user", "content": user_input})

            while True:
                current_tools = [data["schema"] for data in CORE_TOOLS.values()]
                current_tools += [HIDDEN_TOOLS[name]["schema"] for name in ACTIVATED_TOOLS if name in HIDDEN_TOOLS]
                
                response = client.chat.completions.create(
                    model=MODEL,
                    messages=[{"role": "system", "content": system_prompt}] + messages,
                    tools=current_tools if current_tools else None,
                )
                
                resp_msg = response.choices[0].message
                msg_dict = {"role": "assistant", "content": resp_msg.content}
                if resp_msg.tool_calls: msg_dict["tool_calls"] = resp_msg.tool_calls
                messages.append(msg_dict)

                if resp_msg.content: print(f"\n{CYAN}{RESET} {render_markdown(resp_msg.content)}")
                if not resp_msg.tool_calls: break

                for tool_call in resp_msg.tool_calls:
                    name = tool_call.function.name
                    args = json.loads(tool_call.function.arguments)
                    arg_preview = str(list(args.values())[0])[:50] if args else ""
                    print(f"\n{GREEN}{name.capitalize()}{RESET}({DIM}{arg_preview}{RESET})")
                    result = run_tool(name, args)
                    res_lines = str(result).split("\n")
                    preview = res_lines[0][:60]
                    if len(res_lines) > 1: preview += f" ... +{len(res_lines) - 1} lines"
                    elif len(res_lines[0]) > 60: preview += "..."
                    print(f"  {DIM}{preview}{RESET}")
                    messages.append({"role": "tool", "tool_call_id": tool_call.id, "name": name, "content": str(result)})
            print()
        except (KeyboardInterrupt, EOFError): break
        except Exception as err: print(f"{RED}⏺ Error: {err}{RESET}")

if __name__ == "__main__":
    main()