-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecutor.py
More file actions
1882 lines (1732 loc) · 89.9 KB
/
Copy pathexecutor.py
File metadata and controls
1882 lines (1732 loc) · 89.9 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
OpenTeddy Executor
Qwen-powered agent that executes individual SubTasks.
Supports Ollama Function Calling for tool use (shell, file, GCP, DB, HTTP).
Falls back to direct LLM inference if no tools are needed.
Reports confidence so the Orchestrator can decide on escalation.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import re
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Tuple
import httpx
from config import config
from model_profile import model_tier
from models import AgentRole, SubTask, TaskStatus
from skill_factory import SkillFactory
from tool_registry import ToolRegistry, tool_registry as _default_registry
from tracker import Tracker
logger = logging.getLogger(__name__)
_MAX_TOOL_ROUNDS = 10 # prevent infinite tool-call loops
# Objective failure markers in tool results — override self-reported confidence
# when present, so Claude takes over instead of a false "completed".
# New additions cover compose/YAML failures that previously slipped through
# ("yaml: unmarshal errors" on compose up would leave Qwen cheerfully
# reporting 65% confidence while nothing had actually started).
_FAILURE_SIGNAL_RE = re.compile(
r"\b(?:unhealthy|Restarting|Exited \(\d+\)|Dead|CrashLoopBackOff|"
r"Error response from daemon|ERROR \d{4}(?:\s*\(\d+\))?|"
r"WARNING: no compose file found|"
# docker-compose YAML / parse failures
r"yaml: unmarshal errors?|yaml: line \d+|"
r"failed to (?:parse|load|read) compose|"
r"services\.\w+\.(?:ports|volumes|environment).*?(?:is invalid|must be)|"
r"mapping values are not allowed in this context|"
r"required variable .* is not set|"
# Image / build failures
r"failed to solve with frontend|"
r"pull access denied|manifest unknown|"
r"(?:image|manifest) not found|"
# Network failures that block startup
r"bind:? address already in use|"
r"port is already allocated|"
# Filesystem / path failures — Qwen has been mis-reading these as
# "nothing interesting happened" and returning 100% confidence on
# what were actually total dead-ends (e.g. `docker compose -f
# /nonexistent/path.yml` → "open X: no such file or directory").
r"no such file or directory|"
r"open [^:\n]+: no such file|"
r"fatal: (?:not a git repository|could not read)|"
r"cannot list |cannot access |"
r"command not found|"
# cd failures — the exact shape `sh` emits: "/bin/sh: N: cd: can't cd to X"
r"cd: can'?t cd to |cd: no such file|"
# Empty-but-success compose output flagged by shell_tool
r"zero containers \(likely wrong cwd\))",
re.IGNORECASE,
)
_FAILURE_CLAMP_CONFIDENCE = 0.3
_OUTPUT_PREVIEW_CHARS = 500
# Refusal patterns — Qwen/Gemma sometimes hallucinate "I'm just a language
# model, I can't run shell commands" even though the tools are exposed via
# function calling. When we see that pattern in the FINAL answer (not in a
# tool result), we clamp confidence so Claude escalation takes over instead
# of marking a useless "I can't help you" response as completed.
_REFUSAL_SIGNAL_RE = re.compile(
r"(?:"
r"我是一個 ?AI|我是.{0,6}語言模型|我沒有.{0,8}(?:能力|權限).{0,6}執行|"
r"無法.{0,10}(?:直接)?執行|請(?:您|使用者).{0,6}自行執行|"
r"I (?:am|'m) (?:just |only )?(?:an? )?(?:AI|language model)|"
r"I (?:cannot|can't|don'?t have (?:the )?ability to) (?:execute|run|access)|"
r"please (?:run|execute) (?:the )?(?:following )?command(?:s)? (?:yourself|on your own)"
r")",
re.IGNORECASE,
)
def _format_tool_result_for_model(
tool_name: str, tool_result: Dict[str, Any],
) -> str:
"""Render a tool result as a labeled plain-text block instead of a
JSON dump.
Why not json.dumps()?
- Nested JSON with mid-string truncation markers (`... [truncated]`)
makes bigger local models think they've received incomplete
information, which pushes them to re-call the tool "to confirm".
- Labeled plain text makes exit_code / stdout / stderr / error
unambiguous at a glance, cutting the re-call reflex.
Output shape:
[tool_name] OK (32ms)
exit_code: 0
--- stdout ---
<stdout text>
--- stderr ---
<stderr text>
--- error ---
<error text, if any>
Missing sections are simply omitted (e.g. no stdout block on a
write_file success). Arbitrary string results become a single
'result:' section.
"""
success = tool_result.get("success")
duration = tool_result.get("duration_ms", 0)
status = "OK" if success else "FAILED"
lines: List[str] = [f"[{tool_name}] {status} ({duration}ms)"]
inner = tool_result.get("result")
if isinstance(inner, dict):
if "exit_code" in inner:
lines.append(f"exit_code: {inner['exit_code']}")
stdout = (inner.get("stdout") or "").rstrip()
stderr = (inner.get("stderr") or "").rstrip()
if stdout:
lines.append("--- stdout ---")
lines.append(stdout)
if stderr:
lines.append("--- stderr ---")
lines.append(stderr)
# For non-shell tools (file_read, docker_project_detect) the
# result dict carries domain-specific fields — surface whatever
# else is there as a compact JSON line so the model can still
# see structured data without us hiding it entirely.
extra = {k: v for k, v in inner.items()
if k not in ("stdout", "stderr", "exit_code")}
if extra:
try:
lines.append("--- result fields ---")
lines.append(json.dumps(extra, ensure_ascii=False, default=str)[:2000])
except Exception: # noqa: BLE001
pass
if not stdout and not stderr and not extra:
lines.append("(no output)")
elif isinstance(inner, str):
if inner.strip():
lines.append("--- result ---")
lines.append(inner)
elif inner is not None:
try:
lines.append("--- result ---")
lines.append(json.dumps(inner, ensure_ascii=False, default=str)[:2000])
except Exception: # noqa: BLE001
lines.append(str(inner)[:2000])
err = tool_result.get("error")
if err:
lines.append("--- error ---")
lines.append(str(err))
# Preserve any dedup notice attached when the inner result wasn't a dict.
notice = tool_result.get("_dedup_notice")
if notice:
lines.append(str(notice).strip())
return "\n".join(lines)
def _preview_tool_output(tool_result: Dict[str, Any]) -> str:
"""Produce a short string preview of a tool result for the Web UI.
Falls back through stdout → stderr → stringified result → error so the
collapsed tool card always shows something meaningful (not just "done").
"""
if not tool_result:
return ""
result = tool_result.get("result")
if isinstance(result, dict):
text = (
result.get("stdout")
or result.get("stderr")
or result.get("content")
or ""
)
if not text:
# Last resort: serialise the dict
text = json.dumps(result, ensure_ascii=False)
elif isinstance(result, str):
text = result
elif result is not None:
text = str(result)
else:
text = tool_result.get("error") or ""
text = (text or "").strip()
return text[:_OUTPUT_PREVIEW_CHARS]
# ── Mode-specific executor prompts ────────────────────────────────────────────
# The orchestrator tells us which mode the user picked. Each mode gets its
# own system prompt + tool exposure so we don't have to squeeze every
# possible behavior into one general prompt.
_SYSTEM_PROMPT_CODE = """\
You are Teddy-Exec, a precise task executor running inside the OpenTeddy
multi-agent system. You are NOT a chatbot and you are NOT "just a language
model" — you are an executor with real tool access on a real machine.
AVAILABLE TOOLS (you MUST call these via function calling, not describe them):
• shell_exec_readonly — run read-only shell commands: ls, cat, grep, find,
pwd, env, docker ps, docker logs, git status, etc.
• shell_exec_write — run shell commands that change state: git clone,
pip install, npm install, docker compose up/build/down, mkdir, mv, cp,
file writes, service restarts. (High-risk; the system gates approval
automatically — just call the tool.)
• file_read / file_write — read or write a file.
• http_request — make HTTP calls.
DEPLOYMENT HELPERS (prefer these over raw shell for deploy workflows):
• port_probe(port) — is this port in use? returns PID/process,
plus is_self, is_important, safe_to_kill_hint,
and a recommendation string. ALWAYS READ
safe_to_kill_hint before deciding what to do.
• docker_project_detect(dir) — scan for Dockerfile/compose; returns
services, ports, and a suggested command.
Call this FIRST for any deploy task.
• compose_validate(dir) — PRE-FLIGHT: `docker compose config --quiet`.
Always run before `up`. Cheap ~1s check
that catches YAML/env-substitution bugs
which would otherwise surface 30s into a
build as "yaml: unmarshal errors".
• env_file_lint(path) — scan .env for multi-line values, duplicate
keys, unterminated quotes. Run when
compose_validate reports a YAML unmarshal
error — the culprit is almost always .env.
• docker_diagnose(target) — bundled inspect + logs + port, with a
heuristic hint (OOM, port conflict, etc.).
Use whenever a container is unhealthy
(NOT when compose fails before creating
containers — use compose_validate for that).
• compose_remap_port(file, service, from, to) — edit a compose file to
rebind a host port. THE PREFERRED fix
when port_probe says safe_to_kill_hint=False.
• port_free(port) — HIGH RISK. Kill whatever holds a port.
Only when safe_to_kill_hint=True.
PORT-CONFLICT DECISION TREE (memorize this):
port_probe says in_use=True →
• safe_to_kill_hint=False (is_self OR is_important)
→ call compose_remap_port to move THE CONTAINER, do not touch host
• safe_to_kill_hint=True (regular user process)
→ port_free is OK (will prompt user), or compose_remap_port to be safe
• in_use=False
→ proceed with docker compose up
• (Plus any task-specific skills the system has created.)
ABSOLUTE RULES — violating these is a task failure:
0. The user message contains a `WORKSPACE: <absolute-path>` line — that is
the ONLY place you may operate. Treat it like your project root.
• Default behaviour: omit `working_dir` (the shell tool defaults to
WORKSPACE).
• If the project lives in a subdir, use a RELATIVE name like
working_dir="ads-agent". Never reach for an absolute path.
• NEVER set working_dir or `cd` to a sibling/parent of WORKSPACE
(e.g. /home/user/OpenTeddy when WORKSPACE is
/home/user/OpenTeddy/agent-workspace/<project>). That is the
agent's OWN source tree and will be HARD-BLOCKED — wasting a
round and producing nothing useful. The refusal message tells
you the exact path to use; copy it.
1. NEVER refuse with "I'm just a language model", "I can't run shell commands",
"please run these commands yourself", or any equivalent. You CAN run them.
If the sub-task asks you to deploy, install, or clone something, CALL
shell_exec_write with the actual command. Do not list commands as text.
2. If a tool result contains "unhealthy", "Exited", "Restarting",
"Error response", "ERROR <code>", or similar failure signals, you MUST:
(a) Investigate with follow-up tool calls (docker logs --tail=100 <name>,
docker inspect <name>, cat <file>).
(b) NOT report completion — set confidence < 0.5 and describe the failure
in "result". Let Claude escalation take over.
3. Always prefer calling a tool over narrating what you would do. If the
sub-task is "執行 git clone https://github.com/foo/bar", you MUST call
shell_exec_write with command="git clone https://github.com/foo/bar".
4. DO NOT repeat identical tool calls. Before calling a tool, scan the
recent messages — if you already called it with the same arguments
within this subtask, DO NOT call it again. Use the previous output
instead. The system will refuse a 3rd duplicate and force you to
stop. Repeated identical calls waste GPU and produce no new information.
4a. NEVER use commands that run forever. Specifically:
• `docker compose up` — ALWAYS include `-d` (the shell tool will
auto-add it but be explicit anyway).
• `docker logs` / `docker compose logs` — NEVER use `-f` /
`--follow`. Use `--tail=N` instead. The shell tool strips `-f`
automatically; do not rely on that, write it correctly.
• `tail -f` / `tail -F`, `journalctl -f`, `watch` — REFUSED by
the shell tool. Use `tail -n 200`, `journalctl -n 200`, or
run the inner command once.
These patterns hang on a container that is in a restart-crash loop
(logs flow forever, silence-timeout never trips), wasting an entire
subtask. If you need to confirm a container is up, use
`docker compose ps` — instant, single-shot, exits cleanly.
5. Only emit the final JSON (below) AFTER all tool work is done, or when the
task is genuinely a pure-reasoning question that needs no tools.
6. Analytic mode — if the subtask is to produce a data-analysis report,
put charts in fenced ```chart blocks inside the "result" field. The
frontend renders them as interactive Chart.js v4 figures. Example:
```chart
{
"type": "bar",
"data": {
"labels": ["Jan","Feb","Mar"],
"datasets": [{"label":"Revenue","data":[100,150,130],"backgroundColor":"#d97757"}]
},
"options": {"plugins":{"title":{"display":true,"text":"Q1 Revenue"}}}
}
```
Pick the chart type to match the data (line=trend, bar=compare, pie=share,
scatter=correlation, radar=multi-dim). Include 2–5 charts + a short
markdown summary with headings + bullet findings.
FINAL OUTPUT FORMAT (emit exactly one JSON object, no prose, no markdown):
{
"result": "<string: your answer / action result>",
"confidence": <float 0.0–1.0>,
"skill_needed": "<string snake_case or null>",
"skill_description": "<string or null>"
}
"""
_SYSTEM_PROMPT_CHAT = """\
You are Teddy-Exec in **Chat mode**. The user wants conversational text —
summaries, translations, explanations, answers, writing.
Just read the sub-task, think, and reply with the answer. Write in the same
language the user used. Format with markdown (headings, lists, bold) when it
improves readability — especially for summaries and structured explanations.
— Knowledge cutoff awareness ————————————————————————————————————
Your training data has a cutoff. For questions that depend on **current**
information — recent news, today's prices, sports scores, weather, version
numbers of fast-moving libraries / products, schedules, anything dated
later than your training data — you MUST call the `web_search` tool
instead of guessing. Then quote the sources back to the user with their
URLs so the answer is verifiable.
When you DO use search, follow this pattern:
1. Call web_search with a clean keyword query (not a full sentence).
Add the year for time-sensitive topics ("react 19 release notes 2026").
2. Read the top results.
3. Compose a markdown answer that cites at least 1 URL inline.
4. End with a short "Sources" list of the URLs you used.
When you do NOT need search:
- General explanations ("explain async/await")
- Math, logic, code reasoning
- Well-known historical facts
- Translations, summaries of text the user provided
Search adds latency — only call it when freshness genuinely matters.
— What NOT to do ————————————————————————————————————————————
- Do NOT mention shell commands, files, or "I would need to…" — those
tools are not available in chat mode.
- Do NOT fabricate a URL. If you didn't search, don't pretend you did.
- Do NOT call web_search for every message — only when freshness matters.
FINAL OUTPUT FORMAT (emit exactly one JSON object, no prose outside it):
{
"result": "<string: your markdown-formatted answer>",
"confidence": <float 0.0–1.0>,
"skill_needed": null,
"skill_description": null
}
"""
# Back-compat alias — existing code might import _SYSTEM_PROMPT.
_SYSTEM_PROMPT = _SYSTEM_PROMPT_CODE
_STRICT_PREAMBLE = """\
[STRICT MODE — small model, follow these rules EXACTLY:]
1. To USE a tool: emit ONLY the tool call. No prose around it. No \
"I will call X" preamble.
2. To ANSWER directly: emit ONLY the answer text. No "Final answer:" \
prefix. No bullet-points-of-what-you-thought.
3. NEVER mix tool calls and prose answers in the same response.
4. Keep responses short. Aim for the minimum tokens that solve the task.
Examples:
User: list /tmp
You: (call shell_exec_readonly with command='ls -la /tmp')
User: what is 2 + 2?
You: 4
User: summarise this file: /etc/hosts
You: (call file_read with path='/etc/hosts') # then on the next turn, after the result is given to you, emit the summary text
[End of strict-mode header. Below is the standard agent guide:]
"""
_OPEN_SUFFIX = """
[Capable model — extra freedom:]
You may take multiple reasoning steps before responding when the task is
genuinely complex. Keep the FINAL response concise; the user only sees the
last message, not your intermediate thinking.
"""
def _system_prompt_for_mode(mode: str, model_name: str = "") -> str:
"""Pick the base prompt for the given mode, then bend its strictness
to match the model's capability tier.
This is the core of "Adaptive Prompts" (#1) — small thinking models
(qwen3.5:2b etc.) get the strict preamble + few-shot examples; large
models get a brief openness suffix; mid-range stays as-is.
Also prepends a real-clock anchor (current date / weekday / timezone)
so the executor doesn't default to its training-cutoff year when the
user asks anything time-sensitive (`今天 / now / current year /
lunar date / etc.`). Imported lazily so executor.py doesn't grow a
new hard dependency on orchestrator.py.
"""
from orchestrator import _current_time_header
base = _SYSTEM_PROMPT_CHAT if mode == "chat" else _SYSTEM_PROMPT_CODE
tier = model_tier(model_name)
if tier == "strict":
return _current_time_header() + _STRICT_PREAMBLE + "\n" + base
if tier == "open":
return _current_time_header() + base + _OPEN_SUFFIX
return _current_time_header() + base
# ── Workspace artifact scanner ────────────────────────────────────────────────
# Used by Executor.execute() to spot files created/modified during a
# subtask that weren't emitted via the explicit producer-tool path
# (write_file, render_chart_report, etc.). The most common gap is shell
# redirects — `python foo.py > out.txt` writes a real file but the
# shell tool result doesn't carry a `path` or `bytes_written` key, so
# the inline emitter inside _qwen_execute can't see it.
#
# These walk the workspace once before the subtask runs and once after,
# diff the {path: (mtime, size)} dicts, and return the deltas. Cheap
# enough at typical OpenTeddy workspace scale (~hundreds of files) —
# ~10-50ms per scan. Massive `.git` / `node_modules` / `.venv` are
# explicitly skipped so a checkout of a Next.js project doesn't pay
# 50000-file walk costs each subtask.
_ARTIFACT_SCAN_SKIP_DIRS: frozenset = frozenset({
".git", "node_modules", ".venv", "venv", "__pycache__",
".pytest_cache", ".mypy_cache", "target", # rust target dir
".next", "dist", "build",
})
def _snapshot_workspace_files(
workspace_path: str,
) -> Dict[str, Tuple[float, int]]:
"""Walk `workspace_path` and return {abs_path: (mtime, size)} for
every regular file outside the skip-list of noise dirs. Failures
are swallowed and produce an empty snapshot — a stat error on one
file must never break the rest of the subtask."""
snap: Dict[str, Tuple[float, int]] = {}
if not workspace_path:
return snap
import os as _os
try:
for root, dirs, files in _os.walk(workspace_path):
dirs[:] = [d for d in dirs if d not in _ARTIFACT_SCAN_SKIP_DIRS]
for f in files:
p = _os.path.join(root, f)
try:
st = _os.stat(p)
snap[p] = (st.st_mtime, st.st_size)
except (OSError, PermissionError):
pass
except Exception: # noqa: BLE001
pass
return snap
def _diff_workspace_files(
workspace_path: str,
before: Dict[str, Tuple[float, int]],
) -> List[Tuple[str, int]]:
"""Return [(abs_path, size_bytes)] for files that are NEW (didn't
exist in `before`) or MODIFIED (mtime > before's mtime). Used by
the post-subtask scan to emit artifact events. Skip-dir set
matches _snapshot so the diff doesn't claim a node_modules/* file
is "new" — it was never in the snapshot to begin with."""
deltas: List[Tuple[str, int]] = []
if not workspace_path:
return deltas
import os as _os
try:
for root, dirs, files in _os.walk(workspace_path):
dirs[:] = [d for d in dirs if d not in _ARTIFACT_SCAN_SKIP_DIRS]
for f in files:
p = _os.path.join(root, f)
try:
st = _os.stat(p)
except (OSError, PermissionError):
continue
prev = before.get(p)
if prev is None or st.st_mtime > prev[0]:
deltas.append((p, st.st_size))
except Exception: # noqa: BLE001
pass
return deltas
class Executor:
"""Qwen 3 executor agent with Ollama function-calling support."""
def __init__(
self,
tracker: Tracker,
skill_factory: SkillFactory,
registry: Optional[ToolRegistry] = None,
ws_callback: Optional[Callable] = None,
) -> None:
self.tracker = tracker
self.skill_factory = skill_factory
self.registry: ToolRegistry = registry or _default_registry
self.ws_callback = ws_callback # async fn(event_dict) for UI pushes
self._http = httpx.AsyncClient(timeout=120)
# subtask_id → list of {path, relative_path, size_bytes, tool}.
# Populated by _push_event when an artifact event flows; drained
# by orchestrator's deliverable verifier (#2). See pop_subtask_artifacts.
self._subtask_artifacts: Dict[str, List[Dict[str, Any]]] = {}
async def close(self) -> None:
await self._http.aclose()
# ── Public API ────────────────────────────────────────────────────────────
async def execute(
self, subtask: SubTask, context: Dict, mode: str = "code",
) -> SubTask:
"""Execute a subtask. Returns the updated subtask with result / status.
`mode` comes from the session (chat / code / analytic) and flips
both the system prompt and the available tool set below.
"""
subtask.status = TaskStatus.RUNNING
await self.tracker.update_subtask(subtask)
# Snapshot the workspace BEFORE the tool loop so we can detect any
# files created/modified during the subtask — including those
# written via shell redirects (`python foo.py > out.txt`), wget,
# tar extraction, or scripts that internally call open(...,'w')
# without going through the file_write tool. The existing
# producer-tool emission inside _qwen_execute catches the
# `write_file` / `python_exec` / `db_query_to_csv` paths;
# shell-redirect outputs were the gap real users hit (Telegram
# bug report 2026-06-03: github_trending_results.txt produced
# via shell redirect was invisible to both the chat UI's
# download chip and the Telegram bridge's result formatter).
from config import effective_workspace_dir as _ws
try:
workspace_path = _ws() or ""
except Exception: # noqa: BLE001
workspace_path = ""
ws_snapshot = (
_snapshot_workspace_files(workspace_path) if workspace_path else {}
)
# 1. Try a matching skill first — skills are available in all modes
# except pure chat (where tools make no sense).
if mode != "chat":
skill_result = await self._try_skill(subtask, context)
if skill_result is not None:
success, output = skill_result
subtask.result = output
subtask.confidence = 0.95 if success else 0.2
subtask.status = TaskStatus.COMPLETED if success else TaskStatus.FAILED
subtask.completed_at = datetime.utcnow()
await self.tracker.update_subtask(subtask)
await self._scan_and_emit_new_artifacts(
workspace_path, ws_snapshot, subtask,
)
return subtask
# 2. Qwen with function calling
result, confidence, skill_hint, skill_desc = await self._qwen_execute(
subtask.description, context,
task_id=subtask.parent_task_id,
subtask_id=subtask.id,
mode=mode,
)
subtask.result = result
subtask.confidence = confidence
subtask.skill_hint = skill_hint
if confidence >= config.escalation_confidence_threshold:
subtask.status = TaskStatus.COMPLETED
else:
subtask.status = TaskStatus.FAILED
subtask.completed_at = datetime.utcnow()
await self.tracker.update_subtask(subtask)
# Post-run workspace scan — emit synthetic artifact events for
# any file that appeared / was modified during this subtask but
# wasn't already registered via a producer tool. Dedupe against
# what _qwen_execute already pushed so we never double-chip.
await self._scan_and_emit_new_artifacts(
workspace_path, ws_snapshot, subtask,
)
# 3. Background: request skill creation if signalled
if skill_hint and skill_desc:
await self._request_skill_creation(skill_hint, skill_desc)
return subtask
async def _scan_and_emit_new_artifacts(
self,
workspace_path: str,
before_snapshot: Dict[str, Tuple[float, int]],
subtask: SubTask,
) -> None:
"""Diff the workspace against the pre-subtask snapshot and emit
synthetic 'artifact' events for any file that's new or modified.
Catches files created by shell redirects, scripts, archive
extraction, etc. — anything the producer-tool path in
_qwen_execute can't see because it only knows about explicit
`path` / `bytes_written` keys in the tool result.
Dedupes against artifacts already collected for this subtask
(the producer-tool path), so the same file never produces two
download chips."""
if not workspace_path:
return
try:
new_files = _diff_workspace_files(workspace_path, before_snapshot)
except Exception as exc: # noqa: BLE001
logger.debug("workspace diff failed: %s", exc)
return
if not new_files:
return
# Skip paths already emitted via a producer tool this subtask.
# _subtask_artifacts is keyed by subtask_id and populated by
# _push_event whenever an artifact event flows through.
already = {
a.get("path")
for a in self._subtask_artifacts.get(subtask.id, [])
if a.get("path")
}
import os as _os
for fpath, size_bytes in new_files:
if fpath in already:
continue
try:
rel = _os.path.relpath(fpath, workspace_path)
except Exception: # noqa: BLE001
rel = ""
artifact_info = {
"tool": "shell_output",
"path": fpath,
"relative_path": rel,
"size_bytes": size_bytes,
"name": _os.path.basename(fpath),
}
await self._push_event({
"event": "artifact",
"task_id": subtask.parent_task_id,
"subtask_id": subtask.id,
**artifact_info,
})
try:
await self.tracker.append_task_artifact(
subtask.parent_task_id, artifact_info,
)
except Exception: # noqa: BLE001
pass
# ── Ollama Function Calling ───────────────────────────────────────────────
async def _qwen_execute(
self,
description: str,
context: Dict,
task_id: str = "unknown",
subtask_id: str = "",
mode: str = "code",
) -> Tuple[str, float, Optional[str], Optional[str]]:
"""
Multi-turn Qwen chat with Ollama function calling.
Loop up to _MAX_TOOL_ROUNDS tool calls before forcing a final answer.
`mode` picks the system prompt and gates whether tools are exposed
at all — in chat mode we send no `tools` field so the model is
forced into a pure single-turn answer (no accidental shell calls).
"""
system_prompt = _system_prompt_for_mode(mode, config.qwen_model)
# One-line trace so it's obvious in the log which prompt tier the
# current model is running under (strict / balanced / open).
logger.info(
"Executor prompt tier=%s mode=%s model=%s",
model_tier(config.qwen_model), mode, config.qwen_model,
)
# Pin the active session workspace at the top of EVERY round's
# user message. Without this, small/mid models drift after a few
# tool rounds — they remember the project name ("OpenTeddy") but
# not the exact directory ("/.../agent-workspace/ads-agent"), so
# they reach for `cd /home/user/OpenTeddy && docker compose up`
# which the shell guard then has to refuse round after round,
# burning GPU each time. Surfacing the path positively (here is
# WHERE you work) is more reliable than the system prompt's
# negative rule (don't go HERE). The shell tool also reads this
# path from config so refusals are guaranteed-consistent with
# what the model sees.
from config import effective_workspace_dir as _ws
try:
workspace_path = _ws() or ""
except Exception: # noqa: BLE001
workspace_path = ""
workspace_block = ""
if workspace_path:
workspace_block = (
f"WORKSPACE: {workspace_path}\n"
"All shell commands and `working_dir` arguments MUST stay "
"inside this directory. If you need to `cd`, only `cd` to "
"subdirectories of WORKSPACE — never to a sibling or parent. "
"Omit `working_dir` to default to WORKSPACE.\n\n"
)
messages: List[Dict[str, Any]] = [
{
"role": "user",
"content": (
workspace_block
+ f"Task: {description}\n\n"
f"Context: {json.dumps(context, ensure_ascii=False)[:2000]}"
),
}
]
# Chat mode hides almost all tools — it's text reasoning only —
# but exposes web_search so the local model can ground answers
# in current data when its training cutoff would otherwise force
# it to hallucinate (recent events, new versions, today's prices).
# Without web_search a 2B/4B local model invents plausible-
# looking facts; with it, the model can say "let me look that up"
# and quote real sources. The other tools (shell, file, db, etc.)
# stay hidden so chat can't accidentally write files or run
# commands while answering a casual question.
if mode == "chat":
tools = self.registry.get_schemas_by_names(["web_search"])
else:
tools = self.registry.get_schemas()
objective_failure_seen = False
# Duplicate-call tracker. Small local models (Qwen 2.5 3B) routinely
# re-call the same tool with the same args because their
# short-term attention over tool results is weak. Each extra
# round burns full GPU inference. We:
# - Nudge Qwen on the 2nd identical call (warning in the result)
# - Force-end the loop on the 3rd (inject a terminate message,
# don't execute the tool — just tell Qwen to emit its final
# JSON answer instead of burning another round).
# Key = (tool_name, canonical args JSON). Stable across retries.
call_counts: Dict[str, int] = {}
# ── A: Discovery tool memos ─────────────────────────────────────
# After "discovery" tools (csv_describe, read_file, list_directory,
# csv_head, json_read) succeed, we append a one-line summary of
# what was learned to this list. The memos get prepended to the
# system prompt on every subsequent chat call — which means
# they're NEVER subject to #4 compression (system field is
# separate from messages[]) and the model can't "forget" what
# it already inspected. Direct fix for the "small model called
# csv_describe 4 times on the same file" pathology.
discovery_memos: List[str] = []
# ── B: per-tool-name hard cap (separate from exact-args dedup) ──
# The exact-args gate above only catches `read_file({path:'a'})`
# called 3× with identical args. It can't stop a model from
# firing 12 different `python_exec` calls at the same dataset
# — exactly the failure mode that ate 8 hours on a real task.
# Cap each tool NAME at MAX_PER_TOOL_NAME calls per subtask;
# past that we synthesize a refusal so the model has to commit.
#
# The default 5 catches the loop case but is way too tight for
# legitimate exploration workflows — auditing a new Next.js
# project routinely needs to read 8-12 different files (README,
# layout.tsx, page.tsx, globals.css, package.json, tsconfig,
# eslint config, …). Cap-hitting on file #6 made the model
# think it was stuck → `rm -rf project && recreate` loop on a
# real user task. Read-only inspection tools therefore get a
# much higher cap; state-mutating tools (write_file,
# shell_exec_write, python_exec, …) keep the original 5.
tool_name_counts: Dict[str, int] = {}
MAX_PER_TOOL_NAME = 5
# Allowlist: read-only "exploration" tools where 5 distinct
# calls is way too few. Each entry maps tool_name → its cap.
# Anything missing here falls back to MAX_PER_TOOL_NAME.
_PER_TOOL_NAME_OVERRIDES: Dict[str, int] = {
# File-system inspection
"read_file": 12,
"list_directory": 12,
# Document / data extraction (read-only, often hit many
# different files in one analytic flow)
"pdf_extract_text": 10,
"doc_to_markdown": 12, # markitdown-backed, broader coverage
"cyber_skill_lookup": 8, # multi-query refinement common
"csv_describe": 10,
# DB introspection — auditing a schema needs many describes
"db_list_tables": 10,
"db_describe_table": 15,
"db_query": 12,
# Web / network look-ups
"web_search": 10,
"fetch_url": 10,
# Browser tool — same "scrape N pages of a listing" use
# case as fetch_url, just slower. 8 is plenty for the
# event-listing kind of task ("find all August + September
# concerts across these 3 sites"); each call is ~3-5 s, so
# 8 calls = ~30 s, which is a sensible upper bound before
# we want the model to step back and rethink.
"browser_fetch": 8,
# Shell read-only commands the user reported hitting the cap
# on (ls, cat, grep …). Idempotent; multiple distinct calls
# are fine, just not the same one repeatedly (that's caught
# by the exact-args dedup above).
"shell_exec_readonly": 10,
}
def _cap_for(_name: str) -> int:
return _PER_TOOL_NAME_OVERRIDES.get(_name, MAX_PER_TOOL_NAME)
# ── D: stuck-loop circuit breaker ────────────────────────────
# If a subtask accumulates this many tool failures in total, we
# stop letting it spin and force the model to emit a final answer
# with what it has. Catches "kept retrying python_exec with new
# syntax errors forever" pattern.
total_tool_failures = 0
MAX_TOTAL_FAILURES = 5
def _call_key(tname: str, targs: Dict[str, Any]) -> str:
try:
return f"{tname}::{json.dumps(targs, sort_keys=True, ensure_ascii=False)}"
except Exception: # noqa: BLE001
return f"{tname}::{targs!r}"
# Context watchdog state. We track the most recent prompt_eval_count
# from Ollama so the next round can decide if it needs to compress
# earlier turns before they bust num_ctx and the model starts
# truncating (or in extreme cases, simply silently dropping the
# original task description). Reset to 0 after a successful compress.
last_prompt_tokens = 0
num_ctx = int(getattr(config, "qwen_num_ctx", 16384))
compress_at_f = float(getattr(config, "context_compress_at", 0.7))
compress_threshold = max(1024, int(num_ctx * compress_at_f))
for round_idx in range(_MAX_TOOL_ROUNDS):
# ── Context watchdog (#4) ──────────────────────────────────────
# If the previous round's prompt was already >= 70% of num_ctx,
# we're one turn away from the model losing its grip. Compress
# mid-conversation messages now while there's still headroom.
if (
last_prompt_tokens >= compress_threshold
and len(messages) > 4
):
logger.info(
"Context watchdog: prompt_tokens=%d >= %d (num_ctx=%d) "
"— compressing %d earlier messages.",
last_prompt_tokens, compress_threshold, num_ctx,
len(messages) - 4,
)
messages = await self._compress_messages(messages, system_prompt)
last_prompt_tokens = 0 # next call will re-measure
# Streaming is gated on both the user setting AND the active
# local engine — vLLM runs non-streamed in this cut (see
# local_engine.supports_streaming).
import local_engine
stream_on = (
bool(getattr(config, "streaming_enabled", True))
and local_engine.supports_streaming()
)
# #A: stitch discovery memos onto the system prompt so the
# model sees them every turn. Putting them in `system`
# (not `messages`) keeps them safe from #4 compression
# which only ever rewrites the messages[] history.
effective_system = system_prompt
if discovery_memos:
effective_system = (
system_prompt
+ "\n\n[Discovery memo — what you ALREADY learned in this subtask. "
"Do NOT call these tools again on the same file/path; "
"use the info below directly:]\n"
+ "\n".join(f" • {m}" for m in discovery_memos)
)
# Engine-aware request body. local_engine.build_payload
# produces the Ollama /api/chat shape (with num_ctx +
# keep_alive) or the vLLM OpenAI shape depending on the
# active engine. num_ctx is the real budget the watchdog
# keeps us under (Ollama only; vLLM sets it at serve time).
payload: Dict[str, Any] = local_engine.build_payload(
model=config.qwen_model,
messages=messages,
system=effective_system,
tools=tools or None,
stream=stream_on,
temperature=float(getattr(config, "qwen_temperature", 0.2)),
num_predict=config.qwen_max_tokens,
num_ctx=num_ctx,
keep_alive=getattr(config, "ollama_keep_alive", "24h"),
)
_chat_url = local_engine.chat_endpoint()
try:
if stream_on:
# Stream NDJSON chunks from Ollama, push each text
# delta onto the WebSocket so the chat bubble fills
# in word-by-word. We accumulate the full content +
# tool_calls so the rest of the loop can consume the
# response identically to the non-streaming path.
acc_content = ""
acc_thinking = ""
acc_tool_calls: List[Dict[str, Any]] = []
last_chunk: Dict[str, Any] = {}
async with self._http.stream(
"POST",
_chat_url,
json=payload,
) as resp:
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.strip():
continue
try:
chunk = json.loads(line)
except Exception: # noqa: BLE001
continue
msg = chunk.get("message") or {}
d_content = msg.get("content") or ""
d_thinking = msg.get("thinking") or ""
if d_content:
acc_content += d_content
await self._push_event({
"type": "chat.stream.delta",
"task_id": task_id,
"subtask_id": subtask_id,
"text": d_content,
})
if d_thinking:
acc_thinking += d_thinking
tcs = msg.get("tool_calls") or []
if tcs:
acc_tool_calls.extend(tcs)
if chunk.get("done"):
last_chunk = chunk
# Re-shape into the same structure non-streaming returned.
# Carry through Ollama's timing stats (eval_duration,
# total_duration) so #6 can compute t/s from them.
data = {
"message": {
"content": acc_content,
"thinking": acc_thinking,
"tool_calls": acc_tool_calls,
},
"prompt_eval_count": last_chunk.get("prompt_eval_count", 0),
"eval_count": last_chunk.get("eval_count", 0),
"eval_duration": last_chunk.get("eval_duration", 0),
"total_duration": last_chunk.get("total_duration", 0),
"prompt_eval_duration": last_chunk.get("prompt_eval_duration", 0),
"done_reason": last_chunk.get("done_reason"),
}
# Mark the stream as complete so the UI can stop the
# word-by-word painter and lock in the final markdown.
await self._push_event({
"type": "chat.stream.end",
"task_id": task_id,
"subtask_id": subtask_id,
})
else:
resp = await self._http.post(
_chat_url,
json=payload,
)
resp.raise_for_status()
# normalize_response maps vLLM's OpenAI shape to the
# Ollama shape the rest of this loop reads; Ollama