Upload 19 files
Browse files- v2/vllm_nanoclaw_runtime/__init__.py +5 -0
- v2/vllm_nanoclaw_runtime/__pycache__/__init__.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/backend.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/cli.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/prompts.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/protocol.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/runner.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/tasks.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/tools.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/__pycache__/types.cpython-310.pyc +0 -0
- v2/vllm_nanoclaw_runtime/backend.py +99 -0
- v2/vllm_nanoclaw_runtime/cli.py +141 -0
- v2/vllm_nanoclaw_runtime/prompts.py +202 -0
- v2/vllm_nanoclaw_runtime/protocol.py +212 -0
- v2/vllm_nanoclaw_runtime/run_qwen3_5_27b_nanoclaw_runtime_eager.sh +357 -0
- v2/vllm_nanoclaw_runtime/runner.py +456 -0
- v2/vllm_nanoclaw_runtime/tasks.py +78 -0
- v2/vllm_nanoclaw_runtime/tools.py +705 -0
- v2/vllm_nanoclaw_runtime/types.py +41 -0
v2/vllm_nanoclaw_runtime/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local vLLM-backed Nanoclaw-compatible runtime."""
|
| 2 |
+
|
| 3 |
+
__all__ = ["__version__"]
|
| 4 |
+
|
| 5 |
+
__version__ = "0.2.0"
|
v2/vllm_nanoclaw_runtime/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (232 Bytes). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/backend.cpython-310.pyc
ADDED
|
Binary file (2.78 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/cli.cpython-310.pyc
ADDED
|
Binary file (5.53 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/prompts.cpython-310.pyc
ADDED
|
Binary file (7.84 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/protocol.cpython-310.pyc
ADDED
|
Binary file (6.18 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/runner.cpython-310.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/tasks.cpython-310.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/tools.cpython-310.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/__pycache__/types.cpython-310.pyc
ADDED
|
Binary file (1.65 kB). View file
|
|
|
v2/vllm_nanoclaw_runtime/backend.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def build_llm(args: argparse.Namespace) -> Any:
|
| 8 |
+
from vllm import LLM
|
| 9 |
+
|
| 10 |
+
llm_kwargs: dict[str, Any] = {
|
| 11 |
+
"model": args.model,
|
| 12 |
+
"tokenizer": args.tokenizer or args.model,
|
| 13 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 14 |
+
"dtype": args.dtype,
|
| 15 |
+
"max_model_len": args.max_model_len,
|
| 16 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 17 |
+
"trust_remote_code": args.trust_remote_code,
|
| 18 |
+
"enforce_eager": args.enforce_eager,
|
| 19 |
+
"enable_prefix_caching": args.enable_prefix_caching,
|
| 20 |
+
}
|
| 21 |
+
if args.max_num_batched_tokens is not None:
|
| 22 |
+
llm_kwargs["max_num_batched_tokens"] = args.max_num_batched_tokens
|
| 23 |
+
if args.max_num_seqs is not None:
|
| 24 |
+
llm_kwargs["max_num_seqs"] = args.max_num_seqs
|
| 25 |
+
if args.seed is not None:
|
| 26 |
+
llm_kwargs["seed"] = args.seed
|
| 27 |
+
return LLM(**llm_kwargs)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def build_sampling_params(args: argparse.Namespace) -> Any:
|
| 31 |
+
from vllm import SamplingParams
|
| 32 |
+
|
| 33 |
+
return SamplingParams(
|
| 34 |
+
temperature=args.temperature,
|
| 35 |
+
top_p=args.top_p,
|
| 36 |
+
top_k=args.top_k,
|
| 37 |
+
max_tokens=args.max_tokens,
|
| 38 |
+
skip_special_tokens=True,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_tokenizer(args: argparse.Namespace) -> Any:
|
| 43 |
+
from transformers import AutoTokenizer
|
| 44 |
+
|
| 45 |
+
return AutoTokenizer.from_pretrained(
|
| 46 |
+
args.tokenizer or args.model,
|
| 47 |
+
trust_remote_code=args.trust_remote_code,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def apply_chat_template(tokenizer: Any, messages: list[dict[str, str]], *, enable_thinking: bool) -> str:
|
| 52 |
+
kwargs = {"tokenize": False, "add_generation_prompt": True}
|
| 53 |
+
try:
|
| 54 |
+
return tokenizer.apply_chat_template(messages, enable_thinking=enable_thinking, **kwargs)
|
| 55 |
+
except TypeError as exc:
|
| 56 |
+
message = str(exc)
|
| 57 |
+
if "enable_thinking" not in message and "unexpected" not in message:
|
| 58 |
+
raise
|
| 59 |
+
return tokenizer.apply_chat_template(messages, **kwargs)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def generate_reply(
|
| 63 |
+
*,
|
| 64 |
+
llm: Any,
|
| 65 |
+
tokenizer: Any,
|
| 66 |
+
sampling_params: Any,
|
| 67 |
+
messages: list[dict[str, str]],
|
| 68 |
+
enable_thinking: bool,
|
| 69 |
+
) -> str:
|
| 70 |
+
replies = generate_replies(
|
| 71 |
+
llm=llm,
|
| 72 |
+
tokenizer=tokenizer,
|
| 73 |
+
sampling_params=sampling_params,
|
| 74 |
+
message_batches=[messages],
|
| 75 |
+
enable_thinking=enable_thinking,
|
| 76 |
+
)
|
| 77 |
+
return replies[0] if replies else ""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def generate_replies(
|
| 81 |
+
*,
|
| 82 |
+
llm: Any,
|
| 83 |
+
tokenizer: Any,
|
| 84 |
+
sampling_params: Any,
|
| 85 |
+
message_batches: list[list[dict[str, str]]],
|
| 86 |
+
enable_thinking: bool,
|
| 87 |
+
) -> list[str]:
|
| 88 |
+
prompts = [
|
| 89 |
+
apply_chat_template(tokenizer, messages, enable_thinking=enable_thinking)
|
| 90 |
+
for messages in message_batches
|
| 91 |
+
]
|
| 92 |
+
request_outputs = llm.generate(prompts, sampling_params, use_tqdm=False)
|
| 93 |
+
replies: list[str] = []
|
| 94 |
+
for request_output in request_outputs:
|
| 95 |
+
if not request_output.outputs:
|
| 96 |
+
replies.append("")
|
| 97 |
+
continue
|
| 98 |
+
replies.append(request_output.outputs[0].text.strip())
|
| 99 |
+
return replies
|
v2/vllm_nanoclaw_runtime/cli.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from .backend import build_llm, build_sampling_params, load_tokenizer
|
| 9 |
+
from .runner import iter_jsonl_results, run_task, run_tasks_batched, utc_now, write_summary
|
| 10 |
+
from .tasks import discover_tasks
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
| 14 |
+
parser = argparse.ArgumentParser(
|
| 15 |
+
description="Run Nanoclaw-compatible workplace tasks with a local vLLM model.",
|
| 16 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument("--base-tasks", required=True, help="Input base_tasks directory.")
|
| 19 |
+
parser.add_argument("--output", required=True, help="Output result root directory.")
|
| 20 |
+
parser.add_argument("--model", required=True, help="Local model path or model name for vLLM.")
|
| 21 |
+
parser.add_argument("--tokenizer", default=None, help="Tokenizer path; defaults to --model.")
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--task-id",
|
| 24 |
+
action="append",
|
| 25 |
+
default=None,
|
| 26 |
+
help="Run only this task id. Can be specified multiple times.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument("--task-glob", default="data_*", help="Task directory glob under base_tasks/tasks.")
|
| 29 |
+
parser.add_argument("--overwrite", action="store_true", help="Overwrite existing task result dirs.")
|
| 30 |
+
parser.add_argument("--resume", action="store_true", help="Skip completed task result dirs.")
|
| 31 |
+
parser.add_argument("--run-verifier", action="store_true", help="Run copied verify_workplace.py after inference.")
|
| 32 |
+
parser.add_argument("--verifier-timeout", type=float, default=120.0, help="Verifier timeout in seconds.")
|
| 33 |
+
|
| 34 |
+
thinking = parser.add_mutually_exclusive_group()
|
| 35 |
+
thinking.add_argument("--enable-thinking", dest="enable_thinking", action="store_true")
|
| 36 |
+
thinking.add_argument("--disable-thinking", dest="enable_thinking", action="store_false")
|
| 37 |
+
parser.set_defaults(enable_thinking=False)
|
| 38 |
+
|
| 39 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 40 |
+
parser.add_argument("--dtype", default="bfloat16", choices=("auto", "float16", "bfloat16", "float32"))
|
| 41 |
+
parser.add_argument("--max-model-len", type=int, default=8192)
|
| 42 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 43 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 44 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
|
| 45 |
+
parser.add_argument("--trust-remote-code", action=argparse.BooleanOptionalAction, default=True)
|
| 46 |
+
parser.add_argument("--enforce-eager", action="store_true")
|
| 47 |
+
parser.add_argument("--enable-prefix-caching", action="store_true")
|
| 48 |
+
|
| 49 |
+
parser.add_argument("--max-steps", type=int, default=20, help="Maximum agent/tool turns per task.")
|
| 50 |
+
parser.add_argument(
|
| 51 |
+
"--agent-batch-size",
|
| 52 |
+
type=int,
|
| 53 |
+
default=1,
|
| 54 |
+
help="Number of active tasks to advance in each vLLM.generate batch.",
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument("--max-tokens", type=int, default=2048, help="Maximum generated tokens per turn.")
|
| 57 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
| 58 |
+
parser.add_argument("--top-p", type=float, default=0.95)
|
| 59 |
+
parser.add_argument("--top-k", type=int, default=-1)
|
| 60 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 61 |
+
parser.add_argument("--read-limit", type=int, default=24000, help="Maximum characters returned by read.")
|
| 62 |
+
parser.add_argument("--list-limit", type=int, default=500, help="Maximum entries returned by ls/find/grep.")
|
| 63 |
+
parser.add_argument("--allow-python-tool", action="store_true", help="Enable model generated Python execution.")
|
| 64 |
+
parser.add_argument("--python-timeout", type=float, default=20.0, help="run_python timeout in seconds.")
|
| 65 |
+
parser.add_argument("--bash-timeout", type=float, default=20.0, help="restricted bash/exec timeout in seconds.")
|
| 66 |
+
args = parser.parse_args(argv)
|
| 67 |
+
|
| 68 |
+
if args.max_steps <= 0:
|
| 69 |
+
parser.error("--max-steps must be positive")
|
| 70 |
+
if args.agent_batch_size <= 0:
|
| 71 |
+
parser.error("--agent-batch-size must be positive")
|
| 72 |
+
if args.resume and args.overwrite:
|
| 73 |
+
parser.error("--resume and --overwrite are mutually exclusive")
|
| 74 |
+
return args
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main(argv: list[str] | None = None) -> int:
|
| 78 |
+
args = parse_args(argv)
|
| 79 |
+
base_tasks = Path(args.base_tasks).expanduser().resolve()
|
| 80 |
+
output_root = Path(args.output).expanduser().resolve()
|
| 81 |
+
requested_task_ids = set(args.task_id) if args.task_id else None
|
| 82 |
+
specs = discover_tasks(base_tasks, task_glob=args.task_glob, task_ids=requested_task_ids)
|
| 83 |
+
|
| 84 |
+
print(f"[info] base_tasks={base_tasks}", file=sys.stderr)
|
| 85 |
+
print(f"[info] output={output_root}", file=sys.stderr)
|
| 86 |
+
print(f"[info] tasks={len(specs)}", file=sys.stderr)
|
| 87 |
+
print(f"[info] model={args.model}", file=sys.stderr)
|
| 88 |
+
print(f"[info] agent_batch_size={args.agent_batch_size}", file=sys.stderr)
|
| 89 |
+
|
| 90 |
+
tokenizer = load_tokenizer(args)
|
| 91 |
+
llm = build_llm(args)
|
| 92 |
+
sampling_params = build_sampling_params(args)
|
| 93 |
+
|
| 94 |
+
started_at = utc_now()
|
| 95 |
+
results: list[dict[str, Any]] = []
|
| 96 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 97 |
+
|
| 98 |
+
if args.agent_batch_size > 1 and len(specs) > 1:
|
| 99 |
+
results = run_tasks_batched(
|
| 100 |
+
specs=specs,
|
| 101 |
+
result_root=output_root,
|
| 102 |
+
llm=llm,
|
| 103 |
+
tokenizer=tokenizer,
|
| 104 |
+
sampling_params=sampling_params,
|
| 105 |
+
args=args,
|
| 106 |
+
)
|
| 107 |
+
(output_root / "results.jsonl").write_text(iter_jsonl_results(results), encoding="utf-8")
|
| 108 |
+
write_summary(output_root, results, started_at)
|
| 109 |
+
else:
|
| 110 |
+
for spec in specs:
|
| 111 |
+
print(f"[task] {spec.task_id}", file=sys.stderr)
|
| 112 |
+
try:
|
| 113 |
+
result = run_task(
|
| 114 |
+
spec=spec,
|
| 115 |
+
result_root=output_root,
|
| 116 |
+
llm=llm,
|
| 117 |
+
tokenizer=tokenizer,
|
| 118 |
+
sampling_params=sampling_params,
|
| 119 |
+
args=args,
|
| 120 |
+
)
|
| 121 |
+
except Exception as exc:
|
| 122 |
+
result = {
|
| 123 |
+
"task_id": spec.task_id,
|
| 124 |
+
"status": "failed",
|
| 125 |
+
"result_dir": str(output_root / spec.task_id),
|
| 126 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 127 |
+
}
|
| 128 |
+
print(f"[error] {spec.task_id}: {result['error']}", file=sys.stderr)
|
| 129 |
+
results.append(result)
|
| 130 |
+
(output_root / "results.jsonl").write_text(iter_jsonl_results(results), encoding="utf-8")
|
| 131 |
+
write_summary(output_root, results, started_at)
|
| 132 |
+
|
| 133 |
+
completed = sum(1 for result in results if result.get("status") == "completed")
|
| 134 |
+
failed = sum(1 for result in results if result.get("status") == "failed")
|
| 135 |
+
skipped = sum(1 for result in results if result.get("status") == "skipped")
|
| 136 |
+
print(f"[done] completed={completed} failed={failed} skipped={skipped} output={output_root}", file=sys.stderr)
|
| 137 |
+
return 1 if failed else 0
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
raise SystemExit(main())
|
v2/vllm_nanoclaw_runtime/prompts.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
TOOL_DESCRIPTIONS: tuple[tuple[str, str], ...] = (
|
| 8 |
+
("read", "Read a text file from the workspace."),
|
| 9 |
+
("write", "Create or replace a text file in the workspace."),
|
| 10 |
+
("edit", "Make a precise in-file text replacement in a workspace file."),
|
| 11 |
+
("apply_patch", "Apply one or more exact text replacements across workspace files."),
|
| 12 |
+
("grep", "Search workspace file contents with a regular expression."),
|
| 13 |
+
("memory_search", "Search MEMORY.md and memory/*.md for relevant prior context."),
|
| 14 |
+
("memory_get", "Read a narrow line range from MEMORY.md or memory/*.md."),
|
| 15 |
+
("memory_append", "Append a note to MEMORY.md or a file under memory/."),
|
| 16 |
+
("find", "Find workspace files by glob pattern."),
|
| 17 |
+
("ls", "List directory contents from the workspace."),
|
| 18 |
+
(
|
| 19 |
+
"exec",
|
| 20 |
+
"Run a restricted bash command in the workspace. Commands and path operands are validated before execution.",
|
| 21 |
+
),
|
| 22 |
+
(
|
| 23 |
+
"bash",
|
| 24 |
+
"Run a restricted bash command, inline script, or workspace script. Commands and path operands must stay inside the task workspace.",
|
| 25 |
+
),
|
| 26 |
+
("ask_human_for_confirmation", "Ask the human to approve exactly one command execution."),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
PYTHON_TOOL_PROMPT = """
|
| 30 |
+
## Local Extension
|
| 31 |
+
|
| 32 |
+
The runner may expose one extra local-only tool when enabled:
|
| 33 |
+
- run_python: Execute Python code inside the workspace.
|
| 34 |
+
|
| 35 |
+
Use run_python only when it is useful for reliable data processing. The code
|
| 36 |
+
runs with the workspace as the current directory. Destructive operations,
|
| 37 |
+
absolute paths, shell commands, subprocess calls, and parent-directory access
|
| 38 |
+
are blocked by the runner.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_system_prompt(
|
| 43 |
+
allow_python_tool: bool,
|
| 44 |
+
*,
|
| 45 |
+
workspace_dir: Path | str | None = None,
|
| 46 |
+
model: str | None = None,
|
| 47 |
+
max_steps: int | None = None,
|
| 48 |
+
date_time: str | None = None,
|
| 49 |
+
timezone_name: str | None = None,
|
| 50 |
+
) -> str:
|
| 51 |
+
"""Build a Nanoclaw-compatible system prompt for local vLLM text output.
|
| 52 |
+
|
| 53 |
+
Native Nanoclaw sends OpenAI tool schemas and receives structured
|
| 54 |
+
``tool_calls``. Local vLLM text generation has no native tool-call channel,
|
| 55 |
+
so this prompt keeps Nanoclaw's runtime contract and adds a narrow JSON
|
| 56 |
+
representation for tool calls.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
now = datetime.now().astimezone()
|
| 60 |
+
runtime_date_time = date_time or now.isoformat()
|
| 61 |
+
runtime_timezone = timezone_name or str(now.tzinfo or "UTC")
|
| 62 |
+
runtime_model = model or "local-vllm"
|
| 63 |
+
runtime_max_steps = max_steps if max_steps is not None else "unknown"
|
| 64 |
+
runtime_workspace = str(Path(workspace_dir).resolve()) if workspace_dir is not None else "<task workspace>"
|
| 65 |
+
|
| 66 |
+
chunks = [
|
| 67 |
+
"You are a personal assistant running inside nanoclaw.",
|
| 68 |
+
"nanoclaw implements an experimental OpenClaw-like subset. Follow the provided runtime contract exactly and do not assume unsupported product features exist.",
|
| 69 |
+
"",
|
| 70 |
+
*_tool_prompt_lines(),
|
| 71 |
+
*_tool_call_style_prompt_lines(),
|
| 72 |
+
*_local_vllm_tool_call_prompt_lines(),
|
| 73 |
+
*_memory_recall_prompt_lines(),
|
| 74 |
+
*_workspace_prompt_lines(runtime_workspace),
|
| 75 |
+
*_current_date_time_prompt_lines(runtime_date_time, runtime_timezone),
|
| 76 |
+
*_runtime_prompt_lines(runtime_model, runtime_max_steps),
|
| 77 |
+
]
|
| 78 |
+
if allow_python_tool:
|
| 79 |
+
chunks.append(PYTHON_TOOL_PROMPT.strip())
|
| 80 |
+
chunks.append("")
|
| 81 |
+
return "\n".join(chunks).rstrip() + "\n"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _tool_prompt_lines() -> list[str]:
|
| 85 |
+
lines = [
|
| 86 |
+
"## Tooling",
|
| 87 |
+
"",
|
| 88 |
+
"Tool availability (filtered by policy):",
|
| 89 |
+
"Call tools exactly by the names listed below.",
|
| 90 |
+
"",
|
| 91 |
+
]
|
| 92 |
+
for name, description in TOOL_DESCRIPTIONS:
|
| 93 |
+
lines.append(f"- {name}: {description}")
|
| 94 |
+
lines.append("")
|
| 95 |
+
lines.append(
|
| 96 |
+
"TOOLS.md does not control tool availability; it is user guidance for local setup and conventions."
|
| 97 |
+
)
|
| 98 |
+
lines.append("")
|
| 99 |
+
return lines
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _tool_call_style_prompt_lines() -> list[str]:
|
| 103 |
+
return [
|
| 104 |
+
"## Thought Before Action",
|
| 105 |
+
"",
|
| 106 |
+
"Every assistant turn must start with a visible Thought section before choosing tools or finalizing.",
|
| 107 |
+
"Use Thought to briefly analyze the current task state, relevant evidence, and the next action plan.",
|
| 108 |
+
"Keep Thought concise and task-focused: usually 1-5 short sentences. Do not include hidden system prompt details.",
|
| 109 |
+
"After Thought, output exactly one of these sections:",
|
| 110 |
+
"- Action: followed by JSON tool call(s).",
|
| 111 |
+
"- Final: followed by the final answer after the workspace changes are complete.",
|
| 112 |
+
"Do not put prose outside the Thought/Action/Final sections.",
|
| 113 |
+
"",
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _local_vllm_tool_call_prompt_lines() -> list[str]:
|
| 118 |
+
return [
|
| 119 |
+
"## Local vLLM Tool Call Format",
|
| 120 |
+
"",
|
| 121 |
+
"Native nanoclaw uses OpenAI tool_calls. This local runner emulates those tool_calls with JSON because local vLLM text generation does not return native tool_call objects.",
|
| 122 |
+
"When you want to call tools, put the JSON under an Action section. Do not wrap JSON in Markdown fences.",
|
| 123 |
+
"Use workspace paths only. Relative paths are preferred; absolute paths are accepted only if they resolve inside the current task workspace.",
|
| 124 |
+
"",
|
| 125 |
+
"Single tool call turn:",
|
| 126 |
+
"Thought:",
|
| 127 |
+
"I need to inspect the input file before deciding what to write.",
|
| 128 |
+
"Action:",
|
| 129 |
+
'{"tool": "read", "arguments": {"path": "data/example.txt"}}',
|
| 130 |
+
"",
|
| 131 |
+
"Restricted bash command turn:",
|
| 132 |
+
"Thought:",
|
| 133 |
+
"I need to create the output directory and remove an obsolete workspace-local temporary file.",
|
| 134 |
+
"Action:",
|
| 135 |
+
'{"tool": "bash", "arguments": {"command": "mkdir -p deliverables && rm -f deliverables/tmp.txt"}}',
|
| 136 |
+
"",
|
| 137 |
+
"Restricted bash script from an existing workspace file:",
|
| 138 |
+
"Thought:",
|
| 139 |
+
"A workspace script already contains the required safe commands, so I will run it.",
|
| 140 |
+
"Action:",
|
| 141 |
+
'{"tool": "bash", "arguments": {"path": "scripts/process.sh"}}',
|
| 142 |
+
"",
|
| 143 |
+
"Multiple tool calls in one assistant turn:",
|
| 144 |
+
"Thought:",
|
| 145 |
+
"I need both a directory listing and the likely input file contents before proceeding.",
|
| 146 |
+
"Action:",
|
| 147 |
+
'{"actions": [{"tool": "ls", "arguments": {"path": "."}}, {"tool": "read", "arguments": {"path": "data/example.txt"}}]}',
|
| 148 |
+
"",
|
| 149 |
+
"OpenAI-style tool_calls JSON is also accepted under Action:",
|
| 150 |
+
"Thought:",
|
| 151 |
+
"I will use the OpenAI-style tool_calls surface for this read action.",
|
| 152 |
+
"Action:",
|
| 153 |
+
'{"tool_calls": [{"function": {"name": "read", "arguments": "{\\"path\\": \\"data/example.txt\\"}"}}]}',
|
| 154 |
+
"",
|
| 155 |
+
"Final answer turn:",
|
| 156 |
+
"Thought:",
|
| 157 |
+
"The requested files have been created and the workspace now satisfies the task.",
|
| 158 |
+
"Final:",
|
| 159 |
+
"Done. Created the requested deliverable in the workspace.",
|
| 160 |
+
"",
|
| 161 |
+
"The bash/exec tools reject unsupported shell syntax and reject rm, mkdir, cp, mv, touch, chmod, cat, grep, find, and similar path operands that escape the workspace.",
|
| 162 |
+
"When the requested workspace changes are complete, do not call a tool. Use Thought followed by Final.",
|
| 163 |
+
"",
|
| 164 |
+
]
|
| 165 |
+
def _memory_recall_prompt_lines() -> list[str]:
|
| 166 |
+
return [
|
| 167 |
+
"## Memory Recall",
|
| 168 |
+
"",
|
| 169 |
+
"Memory recall instructions are disabled for this run by runtime policy.",
|
| 170 |
+
"",
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _workspace_prompt_lines(workspace_dir: str) -> list[str]:
|
| 175 |
+
return [
|
| 176 |
+
"## Workspace",
|
| 177 |
+
"",
|
| 178 |
+
f"Your working directory is: {workspace_dir}",
|
| 179 |
+
"Treat this directory as the primary workspace for file operations unless explicitly instructed otherwise.",
|
| 180 |
+
"All local runner file tools are restricted to this task workspace.",
|
| 181 |
+
"",
|
| 182 |
+
]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _current_date_time_prompt_lines(date_time: str, timezone_name: str) -> list[str]:
|
| 186 |
+
return [
|
| 187 |
+
"## Current Date & Time",
|
| 188 |
+
"",
|
| 189 |
+
f"Current date/time: {date_time}",
|
| 190 |
+
f"Timezone: {timezone_name}",
|
| 191 |
+
"",
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _runtime_prompt_lines(model: str, max_steps: int | str) -> list[str]:
|
| 196 |
+
return [
|
| 197 |
+
"## Runtime",
|
| 198 |
+
"",
|
| 199 |
+
f"Runtime: model={model} | run_mode=normal | memory_policy=off | max_steps={max_steps}",
|
| 200 |
+
"Command approval: non-read-only exec commands are rejected.",
|
| 201 |
+
"",
|
| 202 |
+
]
|
v2/vllm_nanoclaw_runtime/protocol.py
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
SECTION_MARKER_RE = re.compile(r"(?im)^[ \t]*(thought|action|final(?: answer)?)\s*:\s*")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(frozen=True, slots=True)
|
| 13 |
+
class ParsedModelReply:
|
| 14 |
+
thought: str | None
|
| 15 |
+
actions: list[dict[str, Any]] | None = None
|
| 16 |
+
final_answer: str | None = None
|
| 17 |
+
|
| 18 |
+
@property
|
| 19 |
+
def is_final(self) -> bool:
|
| 20 |
+
return self.final_answer is not None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def parse_model_reply(text: str) -> ParsedModelReply:
|
| 24 |
+
"""Parse a model turn using the visible Thought + Action/Final protocol.
|
| 25 |
+
|
| 26 |
+
Preferred formats::
|
| 27 |
+
|
| 28 |
+
Thought:
|
| 29 |
+
...
|
| 30 |
+
Action:
|
| 31 |
+
{"tool": "read", "arguments": {"path": "data/a.txt"}}
|
| 32 |
+
|
| 33 |
+
Thought:
|
| 34 |
+
...
|
| 35 |
+
Final:
|
| 36 |
+
Done.
|
| 37 |
+
|
| 38 |
+
The legacy JSON-only tool-call format is still accepted for compatibility.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
action_match = find_section_marker(text, {"action"})
|
| 42 |
+
if action_match is not None:
|
| 43 |
+
action_text = text[action_match.end() :].strip()
|
| 44 |
+
actions = extract_tool_actions(action_text)
|
| 45 |
+
return ParsedModelReply(thought=extract_thought(text, stop_match=action_match), actions=actions)
|
| 46 |
+
|
| 47 |
+
final_match = find_section_marker(text, {"final", "final answer"})
|
| 48 |
+
if final_match is not None:
|
| 49 |
+
final_answer = text[final_match.end() :].strip()
|
| 50 |
+
if not final_answer:
|
| 51 |
+
raise ValueError("Final section is empty")
|
| 52 |
+
return ParsedModelReply(
|
| 53 |
+
thought=extract_thought(text, stop_match=final_match),
|
| 54 |
+
final_answer=final_answer,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
return ParsedModelReply(thought=extract_prefix_thought(text), actions=extract_tool_actions(text))
|
| 59 |
+
except ValueError:
|
| 60 |
+
if is_plain_final_text(text):
|
| 61 |
+
return ParsedModelReply(thought=None, final_answer=text.strip())
|
| 62 |
+
raise
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def find_section_marker(text: str, names: set[str]) -> re.Match[str] | None:
|
| 66 |
+
normalized_names = {name.lower() for name in names}
|
| 67 |
+
for match in SECTION_MARKER_RE.finditer(text):
|
| 68 |
+
if match.group(1).lower() in normalized_names:
|
| 69 |
+
return match
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def extract_thought(text: str, *, stop_match: re.Match[str] | None) -> str | None:
|
| 74 |
+
thought_match = find_section_marker(text, {"thought"})
|
| 75 |
+
if thought_match is not None:
|
| 76 |
+
end = stop_match.start() if stop_match is not None and stop_match.start() > thought_match.end() else len(text)
|
| 77 |
+
thought = text[thought_match.end() : end].strip()
|
| 78 |
+
return thought or None
|
| 79 |
+
|
| 80 |
+
if stop_match is not None:
|
| 81 |
+
prefix = text[: stop_match.start()].strip()
|
| 82 |
+
return prefix or None
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def extract_prefix_thought(text: str) -> str | None:
|
| 87 |
+
json_start = find_first_json_start(text)
|
| 88 |
+
if json_start is None:
|
| 89 |
+
return None
|
| 90 |
+
prefix = text[:json_start].strip()
|
| 91 |
+
return prefix or None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def is_plain_final_text(text: str) -> bool:
|
| 95 |
+
stripped = text.strip()
|
| 96 |
+
if not stripped:
|
| 97 |
+
return False
|
| 98 |
+
if stripped.startswith("```"):
|
| 99 |
+
return False
|
| 100 |
+
return stripped[0] not in "[{"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def extract_tool_actions(text: str) -> list[dict[str, Any]]:
|
| 104 |
+
parsed = extract_json_value(text)
|
| 105 |
+
if isinstance(parsed, dict):
|
| 106 |
+
if "actions" in parsed:
|
| 107 |
+
raw_actions = parsed["actions"]
|
| 108 |
+
elif "tool_calls" in parsed:
|
| 109 |
+
raw_actions = parsed["tool_calls"]
|
| 110 |
+
else:
|
| 111 |
+
raw_actions = [parsed]
|
| 112 |
+
elif isinstance(parsed, list):
|
| 113 |
+
raw_actions = parsed
|
| 114 |
+
else:
|
| 115 |
+
raise ValueError("tool call JSON must be an object or array")
|
| 116 |
+
|
| 117 |
+
if not isinstance(raw_actions, list) or not raw_actions:
|
| 118 |
+
raise ValueError("actions must be a non-empty array")
|
| 119 |
+
|
| 120 |
+
actions: list[dict[str, Any]] = []
|
| 121 |
+
for index, raw_action in enumerate(raw_actions, start=1):
|
| 122 |
+
if not isinstance(raw_action, dict):
|
| 123 |
+
raise ValueError(f"action #{index} must be an object")
|
| 124 |
+
actions.append(normalize_tool_action(raw_action))
|
| 125 |
+
return actions
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def normalize_tool_action(raw_action: dict[str, Any]) -> dict[str, Any]:
|
| 129 |
+
if "function" in raw_action and isinstance(raw_action["function"], dict):
|
| 130 |
+
function = raw_action["function"]
|
| 131 |
+
return normalize_named_tool_action(function.get("name"), function.get("arguments", {}))
|
| 132 |
+
if "tool" in raw_action or "name" in raw_action:
|
| 133 |
+
return normalize_named_tool_action(
|
| 134 |
+
raw_action.get("tool", raw_action.get("name")),
|
| 135 |
+
raw_action.get("arguments", {}),
|
| 136 |
+
)
|
| 137 |
+
if "action" in raw_action:
|
| 138 |
+
return dict(raw_action)
|
| 139 |
+
raise ValueError("action object must contain 'tool', 'name', 'function', or 'action'")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def normalize_named_tool_action(name: Any, arguments: Any) -> dict[str, Any]:
|
| 143 |
+
if not isinstance(name, str) or not name.strip():
|
| 144 |
+
raise ValueError("tool name must be a non-empty string")
|
| 145 |
+
if isinstance(arguments, str):
|
| 146 |
+
try:
|
| 147 |
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
| 148 |
+
except json.JSONDecodeError as exc:
|
| 149 |
+
raise ValueError(f"tool arguments are not valid JSON: {exc}") from exc
|
| 150 |
+
if arguments is None:
|
| 151 |
+
arguments = {}
|
| 152 |
+
if not isinstance(arguments, dict):
|
| 153 |
+
raise ValueError("tool arguments must be an object")
|
| 154 |
+
action = dict(arguments)
|
| 155 |
+
action["action"] = name.strip()
|
| 156 |
+
return action
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def extract_json_value(text: str) -> Any:
|
| 160 |
+
stripped = strip_code_fence(text.strip())
|
| 161 |
+
try:
|
| 162 |
+
return json.loads(stripped)
|
| 163 |
+
except json.JSONDecodeError:
|
| 164 |
+
return json.loads(find_first_json_value(stripped))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def strip_code_fence(text: str) -> str:
|
| 168 |
+
if not text.startswith("```"):
|
| 169 |
+
return text
|
| 170 |
+
lines = text.splitlines()
|
| 171 |
+
if len(lines) >= 3 and lines[-1].strip() == "```":
|
| 172 |
+
return "\n".join(lines[1:-1]).strip()
|
| 173 |
+
return text
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def find_first_json_start(text: str) -> int | None:
|
| 177 |
+
object_start = text.find("{")
|
| 178 |
+
array_start = text.find("[")
|
| 179 |
+
starts = [index for index in (object_start, array_start) if index != -1]
|
| 180 |
+
return min(starts) if starts else None
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def find_first_json_value(text: str) -> str:
|
| 184 |
+
start = find_first_json_start(text)
|
| 185 |
+
if start is None:
|
| 186 |
+
raise ValueError("no JSON object or array found")
|
| 187 |
+
opening = text[start]
|
| 188 |
+
closing = "}" if opening == "{" else "]"
|
| 189 |
+
|
| 190 |
+
depth = 0
|
| 191 |
+
in_string = False
|
| 192 |
+
escaped = False
|
| 193 |
+
for index in range(start, len(text)):
|
| 194 |
+
char = text[index]
|
| 195 |
+
if in_string:
|
| 196 |
+
if escaped:
|
| 197 |
+
escaped = False
|
| 198 |
+
elif char == "\\":
|
| 199 |
+
escaped = True
|
| 200 |
+
elif char == '"':
|
| 201 |
+
in_string = False
|
| 202 |
+
continue
|
| 203 |
+
|
| 204 |
+
if char == '"':
|
| 205 |
+
in_string = True
|
| 206 |
+
elif char == opening:
|
| 207 |
+
depth += 1
|
| 208 |
+
elif char == closing:
|
| 209 |
+
depth -= 1
|
| 210 |
+
if depth == 0:
|
| 211 |
+
return text[start : index + 1]
|
| 212 |
+
raise ValueError("unterminated JSON value")
|
v2/vllm_nanoclaw_runtime/run_qwen3_5_27b_nanoclaw_runtime_eager.sh
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Qwen3.5-27B 单机 vLLM Nanoclaw runtime 完整启动脚本
|
| 3 |
+
# 说明:
|
| 4 |
+
# 1) 本脚本放在 vllm_nanoclaw_runtime 项目目录内,可以直接启动整个项目;
|
| 5 |
+
# 2) 环境安装与关键 NPU/vLLM 参数沿用之前能跑通的 eager 脚本;
|
| 6 |
+
# 3) 推理入口为 python3 -m vllm_nanoclaw_runtime.cli,不依赖外层 wrapper;
|
| 7 |
+
# 4) 默认输入为项目父目录下的 “数据示例”,输出到项目父目录下 result_nanoclaw_vllm;
|
| 8 |
+
# 5) 默认 TP=4,只用 0,1,2,3 四张卡;如需 8 卡,手动传 TP=8 ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7。
|
| 9 |
+
|
| 10 |
+
set -xeo pipefail
|
| 11 |
+
|
| 12 |
+
SCRIPT_VERSION="qwen3.5-27b-vllm-nanoclaw-runtime-eager-0610-v1"
|
| 13 |
+
echo "========== ${SCRIPT_VERSION} =========="
|
| 14 |
+
|
| 15 |
+
# ================= 当前项目路径 =================
|
| 16 |
+
# RUNTIME_DIR 是本脚本所在目录,也就是 vllm_nanoclaw_runtime 项目目录。
|
| 17 |
+
# PROJECT_ROOT 默认是它的父目录,用于让 python -m 能 import vllm_nanoclaw_runtime。
|
| 18 |
+
RUNTIME_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
| 19 |
+
PROJECT_ROOT=${PROJECT_ROOT:-$(cd "${RUNTIME_DIR}/.." && pwd)}
|
| 20 |
+
|
| 21 |
+
# ================= 基础路径:沿用之前能跑通的 eager 环境 =================
|
| 22 |
+
WORK_DIR=${WORK_DIR:-/opt/huawei/dataset/zyr_yuyin/lyf/verl-06-08/verl}
|
| 23 |
+
SCRIPT_DIR=${SCRIPT_DIR:-${PROJECT_ROOT}}
|
| 24 |
+
INSTALL_DIR=${INSTALL_DIR:-/home/ma-user}
|
| 25 |
+
BKGS=${BKGS:-/opt/huawei/dataset/zyr_yuyin/bkgs}
|
| 26 |
+
VLLM_LATEST_PKGS=${VLLM_LATEST_PKGS:-/opt/huawei/dataset/zyr_yuyin/lyf/verl-05-12/verl_new_26_05_09/pkgs}
|
| 27 |
+
CANN_BKGS=${CANN_BKGS:-/opt/huawei/dataset/zyr_yuyin/lyf/vllm_bkgs_1015}
|
| 28 |
+
|
| 29 |
+
MODEL_PATH=${MODEL_PATH:-/opt/huawei/dataset/zyr_yuyin/models/Qwen/Qwen3___5-27B}
|
| 30 |
+
BASE_TASKS=${BASE_TASKS:-${SCRIPT_DIR}/数据示例}
|
| 31 |
+
RESULT_ROOT=${RESULT_ROOT:-${SCRIPT_DIR}/result_nanoclaw_vllm}
|
| 32 |
+
RUNNER_MODULE=${RUNNER_MODULE:-vllm_nanoclaw_runtime.cli}
|
| 33 |
+
|
| 34 |
+
GCC_INSTALL_PREFIX=${GCC_INSTALL_PREFIX:-/home/ma-user/gcc-11.3.0}
|
| 35 |
+
COMPILED_GCC_ARCHIVE_PATH=${COMPILED_GCC_ARCHIVE_PATH:-/opt/huawei/dataset/zyr_yuyin/bkgs/gcc-11.3.0-compiled-aarch64.tar.gz}
|
| 36 |
+
|
| 37 |
+
# 第一次跑或环境不确定时保持默认 1;如果环境已经装好,可 SETUP_ENV=0 跳过安装段。
|
| 38 |
+
SETUP_ENV=${SETUP_ENV:-1}
|
| 39 |
+
|
| 40 |
+
chmod 755 "${INSTALL_DIR}" || true
|
| 41 |
+
mkdir -p "${RESULT_ROOT}"
|
| 42 |
+
|
| 43 |
+
# ================= NPU 基础信息 =================
|
| 44 |
+
npu-smi info || true
|
| 45 |
+
|
| 46 |
+
if [ "${SETUP_ENV}" = "1" ]; then
|
| 47 |
+
# ================= Python / 基础包 =================
|
| 48 |
+
pip install --upgrade pip
|
| 49 |
+
pip uninstall -y moxing-framework || true
|
| 50 |
+
|
| 51 |
+
# ================= GCC 11.3.0 =================
|
| 52 |
+
echo "--> 正在从缓存恢复 GCC 11.3.0..."
|
| 53 |
+
tar -xzf "${COMPILED_GCC_ARCHIVE_PATH}" -C /home/ma-user/
|
| 54 |
+
export PATH=${GCC_INSTALL_PREFIX}/bin:${PATH}
|
| 55 |
+
export LD_LIBRARY_PATH=${GCC_INSTALL_PREFIX}/lib64:${GCC_INSTALL_PREFIX}/lib:${LD_LIBRARY_PATH:-}
|
| 56 |
+
export CC=${GCC_INSTALL_PREFIX}/bin/gcc
|
| 57 |
+
export CXX=${GCC_INSTALL_PREFIX}/bin/g++
|
| 58 |
+
echo "--> 验证 GCC 版本:"
|
| 59 |
+
gcc --version
|
| 60 |
+
|
| 61 |
+
# ================= 准备安装包 =================
|
| 62 |
+
cd "${BKGS}"
|
| 63 |
+
cp jemalloc-5.3.0.tar.bz2 "${INSTALL_DIR}" || true
|
| 64 |
+
|
| 65 |
+
rm -rf "${INSTALL_DIR}/vllm" "${INSTALL_DIR}/vllm-ascend"
|
| 66 |
+
cp -r "${VLLM_LATEST_PKGS}/vllm" "${INSTALL_DIR}"
|
| 67 |
+
cp -r "${VLLM_LATEST_PKGS}/vllm-ascend" "${INSTALL_DIR}"
|
| 68 |
+
|
| 69 |
+
cp "${CANN_BKGS}/Ascend-cann-toolkit_8.5.0_linux-aarch64.run" "${INSTALL_DIR}"
|
| 70 |
+
cp "${CANN_BKGS}/Ascend-cann-910b-ops_8.5.0_linux-aarch64.run" "${INSTALL_DIR}"
|
| 71 |
+
cp "${CANN_BKGS}/Ascend-cann-nnal_8.5.0_linux-aarch64.run" "${INSTALL_DIR}"
|
| 72 |
+
|
| 73 |
+
# ================= 安装 CANN / NNAL =================
|
| 74 |
+
echo "################"
|
| 75 |
+
echo "## set ascend env"
|
| 76 |
+
echo "################"
|
| 77 |
+
|
| 78 |
+
cd "${INSTALL_DIR}"
|
| 79 |
+
|
| 80 |
+
chmod +x Ascend-cann-toolkit_8.5.0_linux-aarch64.run
|
| 81 |
+
bash Ascend-cann-toolkit_8.5.0_linux-aarch64.run --install --quiet
|
| 82 |
+
source "${INSTALL_DIR}/Ascend/ascend-toolkit/set_env.sh"
|
| 83 |
+
|
| 84 |
+
chmod +x Ascend-cann-910b-ops_8.5.0_linux-aarch64.run
|
| 85 |
+
bash Ascend-cann-910b-ops_8.5.0_linux-aarch64.run --install --quiet
|
| 86 |
+
|
| 87 |
+
chmod +x Ascend-cann-nnal_8.5.0_linux-aarch64.run
|
| 88 |
+
bash Ascend-cann-nnal_8.5.0_linux-aarch64.run --install --quiet
|
| 89 |
+
source "${INSTALL_DIR}/Ascend/nnal/atb/set_env.sh"
|
| 90 |
+
|
| 91 |
+
export ASCEND_HOME_PATH=${ASCEND_TOOLKIT_HOME}
|
| 92 |
+
export LD_LIBRARY_PATH=/usr/local/Ascend/driver/lib64:/usr/local/Ascend/driver/lib64/common:${LD_LIBRARY_PATH:-}
|
| 93 |
+
echo "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
|
| 94 |
+
|
| 95 |
+
# ================= 安装 PyTorch / torch-npu =================
|
| 96 |
+
pip3 install torch==2.9.0
|
| 97 |
+
pip3 install pyyaml setuptools
|
| 98 |
+
pip3 install torch-npu==2.9.0
|
| 99 |
+
pip3 install torchvision==0.24.0 torchaudio==2.9.0
|
| 100 |
+
|
| 101 |
+
ASCEND_TOOLKIT_PYTHON_PATH=/home/ma-user/Ascend/ascend-toolkit/latest/python/site-packages
|
| 102 |
+
export PYTHONPATH=${PYTHONPATH:-}:${INSTALL_DIR}:${ASCEND_TOOLKIT_PYTHON_PATH}
|
| 103 |
+
pip install pybind11==2.13.6
|
| 104 |
+
|
| 105 |
+
# ================= 安装 vLLM / vLLM-Ascend =================
|
| 106 |
+
cd "${INSTALL_DIR}/vllm"
|
| 107 |
+
VLLM_TARGET_DEVICE=empty pip install .
|
| 108 |
+
|
| 109 |
+
cd "${INSTALL_DIR}/vllm-ascend"
|
| 110 |
+
pip install -e .
|
| 111 |
+
|
| 112 |
+
# ================= 可选 jemalloc:默认关闭,避免额外编译耗时 =================
|
| 113 |
+
INSTALL_JEMALLOC=${INSTALL_JEMALLOC:-0}
|
| 114 |
+
if [ "${INSTALL_JEMALLOC}" = "1" ]; then
|
| 115 |
+
cd "${INSTALL_DIR}"
|
| 116 |
+
tar -xvf jemalloc-5.3.0.tar.bz2
|
| 117 |
+
cd jemalloc-5.3.0
|
| 118 |
+
./configure --prefix="${INSTALL_DIR}"
|
| 119 |
+
make -j"$(nproc)"
|
| 120 |
+
make install
|
| 121 |
+
export LD_PRELOAD=${INSTALL_DIR}/lib/libjemalloc.so.2:${LD_PRELOAD:-}
|
| 122 |
+
fi
|
| 123 |
+
|
| 124 |
+
# ================= 安装 Triton-Ascend 3.2.1 =================
|
| 125 |
+
pip install --no-deps /opt/huawei/dataset/zyr_yuyin/bkgs/triton_ascend-3.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl
|
| 126 |
+
|
| 127 |
+
# ================= 安装 VERL 依赖:沿用之前环境,主要提供 transformers/tokenizer 等 =================
|
| 128 |
+
cd "${WORK_DIR}"
|
| 129 |
+
pip install -r requirements-npu.txt
|
| 130 |
+
pip install -e .
|
| 131 |
+
pip install --upgrade 'urllib3==1.26.11'
|
| 132 |
+
pip install loguru
|
| 133 |
+
pip install tree_sitter==0.21.3
|
| 134 |
+
pip install tree-sitter-java==0.21.0
|
| 135 |
+
pip install tree-sitter-javascript==0.21.4
|
| 136 |
+
|
| 137 |
+
ACL_PATH=/home/ma-user/Ascend/ascend-toolkit/latest/aarch64-linux/lib64
|
| 138 |
+
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${ACL_PATH}
|
| 139 |
+
echo "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
|
| 140 |
+
|
| 141 |
+
pip uninstall -y transformers || true
|
| 142 |
+
pip install transformers==5.3.0
|
| 143 |
+
pip install accelerate==1.13.0 mathruler
|
| 144 |
+
pip install jsonargparse
|
| 145 |
+
pip install deepdiff sympy html2text requests bs4 mpmath swanlab PandoraBox json_repair
|
| 146 |
+
pip list
|
| 147 |
+
else
|
| 148 |
+
# 环境已经装好时,仍然尝试 source CANN/NNAL 环境。
|
| 149 |
+
if [ -f "${INSTALL_DIR}/Ascend/ascend-toolkit/set_env.sh" ]; then
|
| 150 |
+
source "${INSTALL_DIR}/Ascend/ascend-toolkit/set_env.sh"
|
| 151 |
+
fi
|
| 152 |
+
if [ -f "${INSTALL_DIR}/Ascend/nnal/atb/set_env.sh" ]; then
|
| 153 |
+
source "${INSTALL_DIR}/Ascend/nnal/atb/set_env.sh"
|
| 154 |
+
fi
|
| 155 |
+
export PATH=${GCC_INSTALL_PREFIX}/bin:${PATH}
|
| 156 |
+
export LD_LIBRARY_PATH=${GCC_INSTALL_PREFIX}/lib64:${GCC_INSTALL_PREFIX}/lib:${LD_LIBRARY_PATH:-}
|
| 157 |
+
export PYTHONPATH=${PYTHONPATH:-}:${INSTALL_DIR}:/home/ma-user/Ascend/ascend-toolkit/latest/python/site-packages
|
| 158 |
+
export ASCEND_HOME_PATH=${ASCEND_TOOLKIT_HOME:-/home/ma-user/Ascend/ascend-toolkit/latest}
|
| 159 |
+
export LD_LIBRARY_PATH=/usr/local/Ascend/driver/lib64:/usr/local/Ascend/driver/lib64/common:${LD_LIBRARY_PATH:-}
|
| 160 |
+
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/ma-user/Ascend/ascend-toolkit/latest/aarch64-linux/lib64
|
| 161 |
+
fi
|
| 162 |
+
|
| 163 |
+
# ================= PLOG:兼容 ModelArts 环境;非 ModelArts 也能跑 =================
|
| 164 |
+
if [ -n "${MA_VJ_NAME:-}" ] && [ -n "${VC_TASK_INDEX:-}" ] && [ -n "${MA_LOG_DIR:-}" ]; then
|
| 165 |
+
ma_vj_name=$(echo "${MA_VJ_NAME}" | sed 's:ma-job:modelarts-job:g')
|
| 166 |
+
task_name=worker-${VC_TASK_INDEX}
|
| 167 |
+
task_plog_path=${MA_LOG_DIR}/${ma_vj_name}/${task_name}
|
| 168 |
+
mkdir -p "${task_plog_path}"
|
| 169 |
+
export ASCEND_PROCESS_LOG_PATH=${task_plog_path}/${VC_TASK_INDEX}
|
| 170 |
+
else
|
| 171 |
+
export ASCEND_PROCESS_LOG_PATH=${ASCEND_PROCESS_LOG_PATH:-${SCRIPT_DIR}/plog_nanoclaw_vllm}
|
| 172 |
+
mkdir -p "${ASCEND_PROCESS_LOG_PATH}"
|
| 173 |
+
fi
|
| 174 |
+
echo "plog path: ${ASCEND_PROCESS_LOG_PATH}"
|
| 175 |
+
|
| 176 |
+
# ================= 单机 vLLM/HCCL 环境:沿用可运行 eager 配置 =================
|
| 177 |
+
cd "${PROJECT_ROOT}"
|
| 178 |
+
export PYTHONPATH=${PROJECT_ROOT}:${PYTHONPATH:-}
|
| 179 |
+
|
| 180 |
+
export ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES:-0,1,2,3}
|
| 181 |
+
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-1}
|
| 182 |
+
export TOKENIZERS_PARALLELISM=false
|
| 183 |
+
export PYTHONUNBUFFERED=1
|
| 184 |
+
export ASCEND_GLOBAL_LOG_LEVEL=${ASCEND_GLOBAL_LOG_LEVEL:-3}
|
| 185 |
+
|
| 186 |
+
export VLLM_LOGGING_LEVEL=${VLLM_LOGGING_LEVEL:-INFO}
|
| 187 |
+
export VLLM_USE_V1=${VLLM_USE_V1:-1}
|
| 188 |
+
export VLLM_ENABLE_V1_MULTIPROCESSING=${VLLM_ENABLE_V1_MULTIPROCESSING:-0}
|
| 189 |
+
export VLLM_ASCEND_ENABLE_NZ=${VLLM_ASCEND_ENABLE_NZ:-0}
|
| 190 |
+
export VLLM_ENGINE_ITERATION_TIMEOUT_S=${VLLM_ENGINE_ITERATION_TIMEOUT_S:-3600}
|
| 191 |
+
export VLLM_WORKER_MULTIPROC_METHOD=${VLLM_WORKER_MULTIPROC_METHOD:-spawn}
|
| 192 |
+
|
| 193 |
+
# eager 兜底:规避 profile_run / torch.compile / TorchDynamo 相关问题。
|
| 194 |
+
export TORCHDYNAMO_DISABLE=${TORCHDYNAMO_DISABLE:-1}
|
| 195 |
+
export TORCH_COMPILE_DISABLE=${TORCH_COMPILE_DISABLE:-1}
|
| 196 |
+
|
| 197 |
+
export HCCL_CONNECT_TIMEOUT=${HCCL_CONNECT_TIMEOUT:-3600}
|
| 198 |
+
export HCCL_EXEC_TIMEOUT=${HCCL_EXEC_TIMEOUT:-3600}
|
| 199 |
+
export HCCL_EVENT_TIMEOUT=${HCCL_EVENT_TIMEOUT:-7200}
|
| 200 |
+
export HCCL_BUFFSIZE=${HCCL_BUFFSIZE:-8}
|
| 201 |
+
export P2P_HCCL_BUFFSIZE=${P2P_HCCL_BUFFSIZE:-16}
|
| 202 |
+
export HCCL_OP_EXPANSION_MODE=${HCCL_OP_EXPANSION_MODE:-AIV}
|
| 203 |
+
export HCCL_ASYNC_ERROR_HANDLING=${HCCL_ASYNC_ERROR_HANDLING:-0}
|
| 204 |
+
|
| 205 |
+
export TASK_QUEUE_ENABLE=${TASK_QUEUE_ENABLE:-1}
|
| 206 |
+
export COMBINED_ENABLE=${COMBINED_ENABLE:-1}
|
| 207 |
+
export CLOSE_MATMUL_K_SHIFT=${CLOSE_MATMUL_K_SHIFT:-1}
|
| 208 |
+
export ATB_MATMUL_SHUFFLE_K_ENABLE=${ATB_MATMUL_SHUFFLE_K_ENABLE:-0}
|
| 209 |
+
export PYTORCH_NPU_ALLOC_CONF=${PYTORCH_NPU_ALLOC_CONF:-expandable_segments:True}
|
| 210 |
+
|
| 211 |
+
ulimit -n 65536 || true
|
| 212 |
+
npu-smi info || true
|
| 213 |
+
|
| 214 |
+
# ================= vLLM / agent 参数 =================
|
| 215 |
+
TP=${TP:-4}
|
| 216 |
+
DTYPE=${DTYPE:-bfloat16}
|
| 217 |
+
MAX_MODEL_LEN=${MAX_MODEL_LEN:-262144}
|
| 218 |
+
MAX_NUM_BATCHED_TOKENS=${MAX_NUM_BATCHED_TOKENS:-32768}
|
| 219 |
+
MAX_NUM_SEQS=${MAX_NUM_SEQS:-512}
|
| 220 |
+
GPU_MEMORY_UTILIZATION=${GPU_MEMORY_UTILIZATION:-0.70}
|
| 221 |
+
|
| 222 |
+
MAX_STEPS=${MAX_STEPS:-20}
|
| 223 |
+
AGENT_BATCH_SIZE=${AGENT_BATCH_SIZE:-8}
|
| 224 |
+
MAX_TOKENS=${MAX_TOKENS:-2048}
|
| 225 |
+
TEMPERATURE=${TEMPERATURE:-0.2}
|
| 226 |
+
TOP_P=${TOP_P:-0.95}
|
| 227 |
+
TOP_K=${TOP_K:--1}
|
| 228 |
+
DISABLE_THINKING=${DISABLE_THINKING:-1}
|
| 229 |
+
RESUME=${RESUME:-0}
|
| 230 |
+
OVERWRITE=${OVERWRITE:-1}
|
| 231 |
+
ENFORCE_EAGER=${ENFORCE_EAGER:-1}
|
| 232 |
+
ENABLE_PREFIX_CACHING=${ENABLE_PREFIX_CACHING:-0}
|
| 233 |
+
RUN_VERIFIER=${RUN_VERIFIER:-0}
|
| 234 |
+
ALLOW_PYTHON_TOOL=${ALLOW_PYTHON_TOOL:-0}
|
| 235 |
+
PYTHON_TIMEOUT=${PYTHON_TIMEOUT:-20}
|
| 236 |
+
BASH_TIMEOUT=${BASH_TIMEOUT:-20}
|
| 237 |
+
VERIFIER_TIMEOUT=${VERIFIER_TIMEOUT:-120}
|
| 238 |
+
|
| 239 |
+
# 可选:只跑某些任务。多个任务用逗号分隔,如 TASK_IDS=data_1487,data_0002。
|
| 240 |
+
TASK_IDS=${TASK_IDS:-}
|
| 241 |
+
TASK_GLOB=${TASK_GLOB:-data_*}
|
| 242 |
+
|
| 243 |
+
if [ ! -f "${RUNTIME_DIR}/cli.py" ]; then
|
| 244 |
+
echo "ERROR: vllm_nanoclaw_runtime cli.py not found: ${RUNTIME_DIR}/cli.py" >&2
|
| 245 |
+
exit 2
|
| 246 |
+
fi
|
| 247 |
+
|
| 248 |
+
if [ ! -d "${BASE_TASKS}" ]; then
|
| 249 |
+
echo "ERROR: BASE_TASKS directory not found: ${BASE_TASKS}" >&2
|
| 250 |
+
exit 2
|
| 251 |
+
fi
|
| 252 |
+
|
| 253 |
+
mkdir -p "${RESULT_ROOT}"
|
| 254 |
+
|
| 255 |
+
args=(
|
| 256 |
+
--base-tasks "${BASE_TASKS}"
|
| 257 |
+
--output "${RESULT_ROOT}"
|
| 258 |
+
--model "${MODEL_PATH}"
|
| 259 |
+
--task-glob "${TASK_GLOB}"
|
| 260 |
+
--tensor-parallel-size "${TP}"
|
| 261 |
+
--dtype "${DTYPE}"
|
| 262 |
+
--max-model-len "${MAX_MODEL_LEN}"
|
| 263 |
+
--max-num-batched-tokens "${MAX_NUM_BATCHED_TOKENS}"
|
| 264 |
+
--max-num-seqs "${MAX_NUM_SEQS}"
|
| 265 |
+
--gpu-memory-utilization "${GPU_MEMORY_UTILIZATION}"
|
| 266 |
+
--max-steps "${MAX_STEPS}"
|
| 267 |
+
--agent-batch-size "${AGENT_BATCH_SIZE}"
|
| 268 |
+
--max-tokens "${MAX_TOKENS}"
|
| 269 |
+
--temperature "${TEMPERATURE}"
|
| 270 |
+
--top-p "${TOP_P}"
|
| 271 |
+
--top-k "${TOP_K}"
|
| 272 |
+
--python-timeout "${PYTHON_TIMEOUT}"
|
| 273 |
+
--bash-timeout "${BASH_TIMEOUT}"
|
| 274 |
+
--verifier-timeout "${VERIFIER_TIMEOUT}"
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
if [ -n "${TASK_IDS}" ]; then
|
| 278 |
+
IFS=',' read -ra task_id_array <<< "${TASK_IDS}"
|
| 279 |
+
for task_id in "${task_id_array[@]}"; do
|
| 280 |
+
task_id_trimmed=$(echo "${task_id}" | xargs)
|
| 281 |
+
if [ -n "${task_id_trimmed}" ]; then
|
| 282 |
+
args+=(--task-id "${task_id_trimmed}")
|
| 283 |
+
fi
|
| 284 |
+
done
|
| 285 |
+
fi
|
| 286 |
+
|
| 287 |
+
if [ "${DISABLE_THINKING}" = "1" ] || [ "${DISABLE_THINKING}" = "true" ] || [ "${DISABLE_THINKING}" = "True" ]; then
|
| 288 |
+
args+=(--disable-thinking)
|
| 289 |
+
else
|
| 290 |
+
args+=(--enable-thinking)
|
| 291 |
+
fi
|
| 292 |
+
|
| 293 |
+
if [ "${RESUME}" = "1" ] || [ "${RESUME}" = "true" ] || [ "${RESUME}" = "True" ]; then
|
| 294 |
+
args+=(--resume)
|
| 295 |
+
elif [ "${OVERWRITE}" = "1" ] || [ "${OVERWRITE}" = "true" ] || [ "${OVERWRITE}" = "True" ]; then
|
| 296 |
+
args+=(--overwrite)
|
| 297 |
+
fi
|
| 298 |
+
|
| 299 |
+
if [ "${ENFORCE_EAGER}" = "1" ] || [ "${ENFORCE_EAGER}" = "true" ] || [ "${ENFORCE_EAGER}" = "True" ]; then
|
| 300 |
+
args+=(--enforce-eager)
|
| 301 |
+
fi
|
| 302 |
+
|
| 303 |
+
if [ "${ENABLE_PREFIX_CACHING}" = "1" ] || [ "${ENABLE_PREFIX_CACHING}" = "true" ] || [ "${ENABLE_PREFIX_CACHING}" = "True" ]; then
|
| 304 |
+
args+=(--enable-prefix-caching)
|
| 305 |
+
fi
|
| 306 |
+
|
| 307 |
+
if [ "${RUN_VERIFIER}" = "1" ] || [ "${RUN_VERIFIER}" = "true" ] || [ "${RUN_VERIFIER}" = "True" ]; then
|
| 308 |
+
args+=(--run-verifier)
|
| 309 |
+
fi
|
| 310 |
+
|
| 311 |
+
if [ "${ALLOW_PYTHON_TOOL}" = "1" ] || [ "${ALLOW_PYTHON_TOOL}" = "true" ] || [ "${ALLOW_PYTHON_TOOL}" = "True" ]; then
|
| 312 |
+
args+=(--allow-python-tool)
|
| 313 |
+
fi
|
| 314 |
+
|
| 315 |
+
cat <<INFO
|
| 316 |
+
========== vLLM Nanoclaw-like eager runner config ==========
|
| 317 |
+
SCRIPT_VERSION=${SCRIPT_VERSION}
|
| 318 |
+
SCRIPT_DIR=${SCRIPT_DIR}
|
| 319 |
+
RUNTIME_DIR=${RUNTIME_DIR}
|
| 320 |
+
PROJECT_ROOT=${PROJECT_ROOT}
|
| 321 |
+
RUNNER_MODULE=${RUNNER_MODULE}
|
| 322 |
+
BASE_TASKS=${BASE_TASKS}
|
| 323 |
+
RESULT_ROOT=${RESULT_ROOT}
|
| 324 |
+
MODEL_PATH=${MODEL_PATH}
|
| 325 |
+
ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES}
|
| 326 |
+
TP=${TP}
|
| 327 |
+
DTYPE=${DTYPE}
|
| 328 |
+
MAX_MODEL_LEN=${MAX_MODEL_LEN}
|
| 329 |
+
MAX_NUM_BATCHED_TOKENS=${MAX_NUM_BATCHED_TOKENS}
|
| 330 |
+
MAX_NUM_SEQS=${MAX_NUM_SEQS}
|
| 331 |
+
GPU_MEMORY_UTILIZATION=${GPU_MEMORY_UTILIZATION}
|
| 332 |
+
MAX_STEPS=${MAX_STEPS}
|
| 333 |
+
AGENT_BATCH_SIZE=${AGENT_BATCH_SIZE}
|
| 334 |
+
MAX_TOKENS=${MAX_TOKENS}
|
| 335 |
+
TEMPERATURE=${TEMPERATURE}
|
| 336 |
+
TOP_P=${TOP_P}
|
| 337 |
+
TOP_K=${TOP_K}
|
| 338 |
+
DISABLE_THINKING=${DISABLE_THINKING}
|
| 339 |
+
ENFORCE_EAGER=${ENFORCE_EAGER}
|
| 340 |
+
ENABLE_PREFIX_CACHING=${ENABLE_PREFIX_CACHING}
|
| 341 |
+
RUN_VERIFIER=${RUN_VERIFIER}
|
| 342 |
+
ALLOW_PYTHON_TOOL=${ALLOW_PYTHON_TOOL}
|
| 343 |
+
BASH_TIMEOUT=${BASH_TIMEOUT}
|
| 344 |
+
TASK_IDS=${TASK_IDS}
|
| 345 |
+
TASK_GLOB=${TASK_GLOB}
|
| 346 |
+
SETUP_ENV=${SETUP_ENV}
|
| 347 |
+
VLLM_USE_V1=${VLLM_USE_V1}
|
| 348 |
+
VLLM_ENABLE_V1_MULTIPROCESSING=${VLLM_ENABLE_V1_MULTIPROCESSING}
|
| 349 |
+
VLLM_WORKER_MULTIPROC_METHOD=${VLLM_WORKER_MULTIPROC_METHOD}
|
| 350 |
+
TORCHDYNAMO_DISABLE=${TORCHDYNAMO_DISABLE}
|
| 351 |
+
TORCH_COMPILE_DISABLE=${TORCH_COMPILE_DISABLE}
|
| 352 |
+
HCCL_BUFFSIZE=${HCCL_BUFFSIZE}
|
| 353 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from collections.abc import Iterable
|
| 10 |
+
from datetime import datetime, timezone
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from .backend import generate_reply, generate_replies
|
| 15 |
+
from .prompts import build_system_prompt
|
| 16 |
+
from .protocol import parse_model_reply
|
| 17 |
+
from .tools import execute_actions, workspace_subprocess_env
|
| 18 |
+
from .types import TaskRunState, TaskSpec
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def utc_now() -> str:
|
| 22 |
+
return datetime.now(timezone.utc).isoformat()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def run_task(
|
| 26 |
+
*,
|
| 27 |
+
spec: TaskSpec,
|
| 28 |
+
result_root: Path,
|
| 29 |
+
llm: Any,
|
| 30 |
+
tokenizer: Any,
|
| 31 |
+
sampling_params: Any,
|
| 32 |
+
args: argparse.Namespace,
|
| 33 |
+
) -> dict[str, Any]:
|
| 34 |
+
prepared = prepare_task_run_state(spec=spec, result_root=result_root, args=args)
|
| 35 |
+
if isinstance(prepared, dict):
|
| 36 |
+
return prepared
|
| 37 |
+
|
| 38 |
+
state = prepared
|
| 39 |
+
try:
|
| 40 |
+
while state.status == "running" and state.steps_used < args.max_steps:
|
| 41 |
+
reply = generate_reply(
|
| 42 |
+
llm=llm,
|
| 43 |
+
tokenizer=tokenizer,
|
| 44 |
+
sampling_params=sampling_params,
|
| 45 |
+
messages=state.messages,
|
| 46 |
+
enable_thinking=args.enable_thinking,
|
| 47 |
+
)
|
| 48 |
+
process_task_reply(state, reply, args=args)
|
| 49 |
+
except Exception as exc:
|
| 50 |
+
state.status = "failed"
|
| 51 |
+
state.error = f"{type(exc).__name__}: {exc}"
|
| 52 |
+
state.events.append({"step": state.steps_used + 1, "error": state.error})
|
| 53 |
+
write_task_state_history(state)
|
| 54 |
+
raise
|
| 55 |
+
|
| 56 |
+
return finalize_task_state(state, args=args)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def prepare_task_run_state(
|
| 60 |
+
*,
|
| 61 |
+
spec: TaskSpec,
|
| 62 |
+
result_root: Path,
|
| 63 |
+
args: argparse.Namespace,
|
| 64 |
+
) -> TaskRunState | dict[str, Any]:
|
| 65 |
+
result_dir = result_root / spec.task_id
|
| 66 |
+
if result_dir.exists():
|
| 67 |
+
if args.overwrite:
|
| 68 |
+
shutil.rmtree(result_dir)
|
| 69 |
+
elif args.resume and is_completed_result(result_dir):
|
| 70 |
+
print(f"[skip] {spec.task_id}: completed result exists at {result_dir}", file=sys.stderr)
|
| 71 |
+
return {"task_id": spec.task_id, "status": "skipped", "result_dir": str(result_dir)}
|
| 72 |
+
else:
|
| 73 |
+
raise FileExistsError(f"result dir already exists: {result_dir}; pass --overwrite or --resume")
|
| 74 |
+
|
| 75 |
+
result_dir.mkdir(parents=True, exist_ok=False)
|
| 76 |
+
workspace_after = result_dir / "workspace_after"
|
| 77 |
+
workspace_before = result_dir / "workspace_before"
|
| 78 |
+
workspace_after.mkdir(parents=True, exist_ok=False)
|
| 79 |
+
|
| 80 |
+
prompt_text = spec.prompt_path.read_text(encoding="utf-8")
|
| 81 |
+
shutil.copy2(spec.prompt_path, result_dir / "task_prompt.md")
|
| 82 |
+
if spec.verifier_path is not None:
|
| 83 |
+
shutil.copy2(spec.verifier_path, result_dir / "verify_workplace.py")
|
| 84 |
+
|
| 85 |
+
env_result = run_env_builder(spec.env_builder_path, workspace_after)
|
| 86 |
+
shutil.copytree(workspace_after, workspace_before)
|
| 87 |
+
|
| 88 |
+
messages = build_initial_messages(
|
| 89 |
+
prompt_text=prompt_text,
|
| 90 |
+
workspace_after=workspace_after,
|
| 91 |
+
args=args,
|
| 92 |
+
)
|
| 93 |
+
state = TaskRunState(
|
| 94 |
+
spec=spec,
|
| 95 |
+
result_dir=result_dir,
|
| 96 |
+
workspace_before=workspace_before,
|
| 97 |
+
workspace_after=workspace_after,
|
| 98 |
+
history_path=result_dir / "conversation_history.json",
|
| 99 |
+
metadata_path=result_dir / "runner_metadata.json",
|
| 100 |
+
prompt_text=prompt_text,
|
| 101 |
+
env_result=env_result,
|
| 102 |
+
started_at=utc_now(),
|
| 103 |
+
messages=messages,
|
| 104 |
+
)
|
| 105 |
+
write_task_state_history(state)
|
| 106 |
+
return state
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def build_initial_messages(
|
| 110 |
+
*,
|
| 111 |
+
prompt_text: str,
|
| 112 |
+
workspace_after: Path,
|
| 113 |
+
args: argparse.Namespace,
|
| 114 |
+
) -> list[dict[str, str]]:
|
| 115 |
+
return [
|
| 116 |
+
{
|
| 117 |
+
"role": "system",
|
| 118 |
+
"content": build_system_prompt(
|
| 119 |
+
args.allow_python_tool,
|
| 120 |
+
workspace_dir=workspace_after,
|
| 121 |
+
model=args.model,
|
| 122 |
+
max_steps=args.max_steps,
|
| 123 |
+
),
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"role": "user",
|
| 127 |
+
"content": (
|
| 128 |
+
"Solve this task by using Nanoclaw-compatible tool calls to inspect and modify the workspace.\n"
|
| 129 |
+
"On every assistant turn, first write a concise Thought section, then write either an Action section with JSON tool calls or a Final section.\n"
|
| 130 |
+
"Only provide a final answer after the requested workspace changes are complete.\n\n"
|
| 131 |
+
f"Task:\n{prompt_text}"
|
| 132 |
+
),
|
| 133 |
+
},
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def run_tasks_batched(
|
| 138 |
+
*,
|
| 139 |
+
specs: list[TaskSpec],
|
| 140 |
+
result_root: Path,
|
| 141 |
+
llm: Any,
|
| 142 |
+
tokenizer: Any,
|
| 143 |
+
sampling_params: Any,
|
| 144 |
+
args: argparse.Namespace,
|
| 145 |
+
) -> list[dict[str, Any]]:
|
| 146 |
+
results: list[dict[str, Any]] = []
|
| 147 |
+
states: list[TaskRunState] = []
|
| 148 |
+
|
| 149 |
+
for spec in specs:
|
| 150 |
+
print(f"[prepare] {spec.task_id}", file=sys.stderr)
|
| 151 |
+
try:
|
| 152 |
+
prepared = prepare_task_run_state(spec=spec, result_root=result_root, args=args)
|
| 153 |
+
except Exception as exc:
|
| 154 |
+
result = {
|
| 155 |
+
"task_id": spec.task_id,
|
| 156 |
+
"status": "failed",
|
| 157 |
+
"result_dir": str(result_root / spec.task_id),
|
| 158 |
+
"error": f"{type(exc).__name__}: {exc}",
|
| 159 |
+
}
|
| 160 |
+
results.append(result)
|
| 161 |
+
print(f"[error] {spec.task_id}: {result['error']}", file=sys.stderr)
|
| 162 |
+
continue
|
| 163 |
+
|
| 164 |
+
if isinstance(prepared, dict):
|
| 165 |
+
results.append(prepared)
|
| 166 |
+
else:
|
| 167 |
+
states.append(prepared)
|
| 168 |
+
|
| 169 |
+
while True:
|
| 170 |
+
active_states = [state for state in states if state.status == "running"]
|
| 171 |
+
if not active_states:
|
| 172 |
+
break
|
| 173 |
+
|
| 174 |
+
current_batch = active_states[: args.agent_batch_size]
|
| 175 |
+
print(
|
| 176 |
+
"[batch] "
|
| 177 |
+
+ ", ".join(f"{state.spec.task_id}:step{state.steps_used + 1}" for state in current_batch),
|
| 178 |
+
file=sys.stderr,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
try:
|
| 182 |
+
replies = generate_replies(
|
| 183 |
+
llm=llm,
|
| 184 |
+
tokenizer=tokenizer,
|
| 185 |
+
sampling_params=sampling_params,
|
| 186 |
+
message_batches=[state.messages for state in current_batch],
|
| 187 |
+
enable_thinking=args.enable_thinking,
|
| 188 |
+
)
|
| 189 |
+
for state, reply in zip(current_batch, replies, strict=True):
|
| 190 |
+
process_task_reply(state, reply, args=args)
|
| 191 |
+
except Exception as exc:
|
| 192 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 193 |
+
for state in current_batch:
|
| 194 |
+
state.status = "failed"
|
| 195 |
+
state.error = error
|
| 196 |
+
state.events.append({"step": state.steps_used + 1, "error": error})
|
| 197 |
+
write_task_state_history(state)
|
| 198 |
+
|
| 199 |
+
for state in states:
|
| 200 |
+
results.append(finalize_task_state(state, args=args))
|
| 201 |
+
return results
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def process_task_reply(state: TaskRunState, reply: str, *, args: argparse.Namespace) -> None:
|
| 205 |
+
state.steps_used += 1
|
| 206 |
+
step = state.steps_used
|
| 207 |
+
state.messages.append({"role": "assistant", "content": reply})
|
| 208 |
+
|
| 209 |
+
try:
|
| 210 |
+
parsed_reply = parse_model_reply(reply)
|
| 211 |
+
except ValueError as exc:
|
| 212 |
+
observation = (
|
| 213 |
+
f"Action parse error: {exc}. Output exactly one turn in this format: "
|
| 214 |
+
"Thought: concise analysis, then Action: JSON tool_calls/actions; "
|
| 215 |
+
"or Thought: concise analysis, then Final: final answer only when the task is complete."
|
| 216 |
+
)
|
| 217 |
+
state.events.append({"step": step, "reply": reply, "error": observation})
|
| 218 |
+
if step >= args.max_steps:
|
| 219 |
+
state.status = "failed"
|
| 220 |
+
state.error = f"exceeded max steps ({args.max_steps}) without valid Thought+Action or Thought+Final"
|
| 221 |
+
else:
|
| 222 |
+
state.messages.append({"role": "user", "content": observation_message(observation)})
|
| 223 |
+
write_task_state_history(state)
|
| 224 |
+
return
|
| 225 |
+
|
| 226 |
+
if parsed_reply.is_final:
|
| 227 |
+
state.status = "completed"
|
| 228 |
+
state.final_answer = parsed_reply.final_answer or ""
|
| 229 |
+
state.events.append(
|
| 230 |
+
{
|
| 231 |
+
"step": step,
|
| 232 |
+
"reply": reply,
|
| 233 |
+
"thought": parsed_reply.thought,
|
| 234 |
+
"is_final": True,
|
| 235 |
+
"final_response_mode": "thought_final" if parsed_reply.thought else "plain_text_without_tool_calls",
|
| 236 |
+
}
|
| 237 |
+
)
|
| 238 |
+
write_task_state_history(state)
|
| 239 |
+
return
|
| 240 |
+
|
| 241 |
+
actions = parsed_reply.actions or []
|
| 242 |
+
action_events, observation, is_final, final_answer = execute_actions(
|
| 243 |
+
actions,
|
| 244 |
+
state.workspace_after,
|
| 245 |
+
args=args,
|
| 246 |
+
step=step,
|
| 247 |
+
)
|
| 248 |
+
state.events.append(
|
| 249 |
+
{
|
| 250 |
+
"step": step,
|
| 251 |
+
"reply": reply,
|
| 252 |
+
"thought": parsed_reply.thought,
|
| 253 |
+
"actions": action_events,
|
| 254 |
+
"observation": observation,
|
| 255 |
+
"is_final": is_final,
|
| 256 |
+
}
|
| 257 |
+
)
|
| 258 |
+
if is_final:
|
| 259 |
+
state.status = "completed"
|
| 260 |
+
state.final_answer = final_answer or ""
|
| 261 |
+
write_task_state_history(state)
|
| 262 |
+
return
|
| 263 |
+
|
| 264 |
+
if step >= args.max_steps:
|
| 265 |
+
state.status = "failed"
|
| 266 |
+
state.error = f"exceeded max steps ({args.max_steps}) without final answer"
|
| 267 |
+
else:
|
| 268 |
+
state.messages.append({"role": "user", "content": observation_message(observation)})
|
| 269 |
+
write_task_state_history(state)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def observation_message(observation: str) -> str:
|
| 273 |
+
return (
|
| 274 |
+
f"Observation:\n{observation}\n\n"
|
| 275 |
+
"Analyze the observation first. Then respond with either:\n"
|
| 276 |
+
"Thought:\n<concise analysis>\nAction:\n<JSON tool call(s)>\n\n"
|
| 277 |
+
"or, if the task is complete:\n"
|
| 278 |
+
"Thought:\n<concise completion check>\nFinal:\n<final answer>"
|
| 279 |
+
)
|
| 280 |
+
def finalize_task_state(state: TaskRunState, *, args: argparse.Namespace) -> dict[str, Any]:
|
| 281 |
+
if state.status == "running":
|
| 282 |
+
state.status = "failed"
|
| 283 |
+
state.error = state.error or f"exceeded max steps ({args.max_steps}) without final answer"
|
| 284 |
+
|
| 285 |
+
if args.run_verifier and state.spec.verifier_path is not None:
|
| 286 |
+
state.verifier_result = run_verifier(
|
| 287 |
+
state.result_dir / "verify_workplace.py",
|
| 288 |
+
state.workspace_after,
|
| 289 |
+
timeout=args.verifier_timeout,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
write_task_state_history(state)
|
| 293 |
+
metadata = {
|
| 294 |
+
"task_id": state.spec.task_id,
|
| 295 |
+
"status": state.status,
|
| 296 |
+
"error": state.error,
|
| 297 |
+
"final_answer": state.final_answer,
|
| 298 |
+
"steps_used": state.steps_used,
|
| 299 |
+
"started_at": state.started_at,
|
| 300 |
+
"finished_at": utc_now(),
|
| 301 |
+
"result_dir": str(state.result_dir),
|
| 302 |
+
"prompt_path": str(state.spec.prompt_path),
|
| 303 |
+
"env_builder_path": str(state.spec.env_builder_path),
|
| 304 |
+
"verifier_source_path": str(state.spec.verifier_path) if state.spec.verifier_path else None,
|
| 305 |
+
"workspace_before": str(state.workspace_before),
|
| 306 |
+
"workspace_after": str(state.workspace_after),
|
| 307 |
+
"conversation_history": str(state.history_path),
|
| 308 |
+
"env_builder": state.env_result,
|
| 309 |
+
"verifier": state.verifier_result,
|
| 310 |
+
"model": args.model,
|
| 311 |
+
"tokenizer": args.tokenizer or args.model,
|
| 312 |
+
"max_steps": args.max_steps,
|
| 313 |
+
"agent_batch_size": args.agent_batch_size,
|
| 314 |
+
"allow_python_tool": args.allow_python_tool,
|
| 315 |
+
"bash_timeout": getattr(args, "bash_timeout", 20.0),
|
| 316 |
+
"tool_call_transport": "local_vllm_json_text",
|
| 317 |
+
}
|
| 318 |
+
state.metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 319 |
+
return {
|
| 320 |
+
"task_id": state.spec.task_id,
|
| 321 |
+
"status": state.status,
|
| 322 |
+
"result_dir": str(state.result_dir),
|
| 323 |
+
"error": state.error,
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def write_task_state_history(state: TaskRunState) -> None:
|
| 328 |
+
write_history(
|
| 329 |
+
state.history_path,
|
| 330 |
+
spec=state.spec,
|
| 331 |
+
status=state.status,
|
| 332 |
+
final_answer=state.final_answer,
|
| 333 |
+
error=state.error,
|
| 334 |
+
messages=state.messages,
|
| 335 |
+
events=state.events,
|
| 336 |
+
started_at=state.started_at,
|
| 337 |
+
steps_used=state.steps_used,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def is_completed_result(result_dir: Path) -> bool:
|
| 342 |
+
metadata_path = result_dir / "runner_metadata.json"
|
| 343 |
+
if not metadata_path.is_file():
|
| 344 |
+
return False
|
| 345 |
+
try:
|
| 346 |
+
payload = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 347 |
+
except json.JSONDecodeError:
|
| 348 |
+
return False
|
| 349 |
+
return payload.get("status") == "completed"
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def run_env_builder(env_builder_path: Path, workspace: Path) -> dict[str, Any]:
|
| 353 |
+
started = time.time()
|
| 354 |
+
process = subprocess.run(
|
| 355 |
+
[sys.executable, str(env_builder_path)],
|
| 356 |
+
cwd=workspace,
|
| 357 |
+
text=True,
|
| 358 |
+
capture_output=True,
|
| 359 |
+
env=workspace_subprocess_env(workspace),
|
| 360 |
+
check=False,
|
| 361 |
+
)
|
| 362 |
+
result = {
|
| 363 |
+
"returncode": process.returncode,
|
| 364 |
+
"stdout": process.stdout,
|
| 365 |
+
"stderr": process.stderr,
|
| 366 |
+
"elapsed_seconds": round(time.time() - started, 3),
|
| 367 |
+
}
|
| 368 |
+
if process.returncode != 0:
|
| 369 |
+
raise RuntimeError(
|
| 370 |
+
f"env_builder.py failed for {env_builder_path} with code {process.returncode}\n"
|
| 371 |
+
f"stdout:\n{process.stdout}\n\nstderr:\n{process.stderr}"
|
| 372 |
+
)
|
| 373 |
+
return result
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def run_verifier(verifier_path: Path, workspace: Path, *, timeout: float) -> dict[str, Any]:
|
| 377 |
+
started = time.time()
|
| 378 |
+
try:
|
| 379 |
+
process = subprocess.run(
|
| 380 |
+
[sys.executable, str(verifier_path), str(workspace)],
|
| 381 |
+
cwd=verifier_path.parent,
|
| 382 |
+
text=True,
|
| 383 |
+
capture_output=True,
|
| 384 |
+
env=workspace_subprocess_env(workspace),
|
| 385 |
+
timeout=timeout,
|
| 386 |
+
check=False,
|
| 387 |
+
)
|
| 388 |
+
result: dict[str, Any] = {
|
| 389 |
+
"returncode": process.returncode,
|
| 390 |
+
"stdout": process.stdout,
|
| 391 |
+
"stderr": process.stderr,
|
| 392 |
+
"elapsed_seconds": round(time.time() - started, 3),
|
| 393 |
+
}
|
| 394 |
+
except subprocess.TimeoutExpired as exc:
|
| 395 |
+
result = {
|
| 396 |
+
"returncode": None,
|
| 397 |
+
"stdout": exc.stdout or "",
|
| 398 |
+
"stderr": exc.stderr or "",
|
| 399 |
+
"elapsed_seconds": round(time.time() - started, 3),
|
| 400 |
+
"error": f"verifier timed out after {timeout:g}s",
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
score_path = workspace / "workplace_score.json"
|
| 404 |
+
if score_path.is_file():
|
| 405 |
+
try:
|
| 406 |
+
result["workplace_score"] = json.loads(score_path.read_text(encoding="utf-8"))
|
| 407 |
+
except json.JSONDecodeError as exc:
|
| 408 |
+
result["workplace_score_error"] = str(exc)
|
| 409 |
+
return result
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def write_history(
|
| 413 |
+
path: Path,
|
| 414 |
+
*,
|
| 415 |
+
spec: TaskSpec,
|
| 416 |
+
status: str,
|
| 417 |
+
final_answer: str | None,
|
| 418 |
+
error: str | None,
|
| 419 |
+
messages: list[dict[str, str]],
|
| 420 |
+
events: list[dict[str, Any]],
|
| 421 |
+
started_at: str,
|
| 422 |
+
steps_used: int,
|
| 423 |
+
) -> None:
|
| 424 |
+
payload = {
|
| 425 |
+
"task_id": spec.task_id,
|
| 426 |
+
"status": status,
|
| 427 |
+
"final_answer": final_answer,
|
| 428 |
+
"error": error,
|
| 429 |
+
"started_at": started_at,
|
| 430 |
+
"updated_at": utc_now(),
|
| 431 |
+
"steps_used": steps_used,
|
| 432 |
+
"messages": messages,
|
| 433 |
+
"events": events,
|
| 434 |
+
}
|
| 435 |
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def write_summary(output_root: Path, results: list[dict[str, Any]], started_at: str) -> None:
|
| 439 |
+
summary = {
|
| 440 |
+
"started_at": started_at,
|
| 441 |
+
"finished_at": utc_now(),
|
| 442 |
+
"total": len(results),
|
| 443 |
+
"completed": sum(1 for result in results if result.get("status") == "completed"),
|
| 444 |
+
"failed": sum(1 for result in results if result.get("status") == "failed"),
|
| 445 |
+
"skipped": sum(1 for result in results if result.get("status") == "skipped"),
|
| 446 |
+
"results": results,
|
| 447 |
+
}
|
| 448 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 449 |
+
(output_root / "summary.json").write_text(
|
| 450 |
+
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
|
| 451 |
+
encoding="utf-8",
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def iter_jsonl_results(results: Iterable[dict[str, Any]]) -> str:
|
| 456 |
+
return "".join(json.dumps(result, ensure_ascii=False) + "\n" for result in results)
|
v2/vllm_nanoclaw_runtime/tasks.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from .types import TaskSpec
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def discover_tasks(base_tasks: Path, *, task_glob: str, task_ids: set[str] | None) -> list[TaskSpec]:
|
| 9 |
+
tasks_root = base_tasks / "tasks"
|
| 10 |
+
if not tasks_root.is_dir():
|
| 11 |
+
raise FileNotFoundError(f"tasks directory not found: {tasks_root}")
|
| 12 |
+
|
| 13 |
+
script_root = find_script_root(base_tasks)
|
| 14 |
+
specs: list[TaskSpec] = []
|
| 15 |
+
for task_dir in sorted(path for path in tasks_root.glob(task_glob) if path.is_dir()):
|
| 16 |
+
task_id = task_dir.name
|
| 17 |
+
if task_ids is not None and task_id not in task_ids:
|
| 18 |
+
continue
|
| 19 |
+
|
| 20 |
+
env_builder_path = task_dir / "env_builder.py"
|
| 21 |
+
if not env_builder_path.is_file():
|
| 22 |
+
continue
|
| 23 |
+
|
| 24 |
+
prompt_path = find_prompt_path(tasks_root, task_dir, task_id)
|
| 25 |
+
verifier_path = find_verifier_path(script_root, task_id) if script_root is not None else None
|
| 26 |
+
specs.append(
|
| 27 |
+
TaskSpec(
|
| 28 |
+
task_id=task_id,
|
| 29 |
+
task_dir=task_dir,
|
| 30 |
+
prompt_path=prompt_path,
|
| 31 |
+
env_builder_path=env_builder_path,
|
| 32 |
+
verifier_path=verifier_path,
|
| 33 |
+
)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
if task_ids is not None:
|
| 37 |
+
found_ids = {spec.task_id for spec in specs}
|
| 38 |
+
missing_ids = sorted(task_ids - found_ids)
|
| 39 |
+
if missing_ids:
|
| 40 |
+
raise FileNotFoundError(f"requested task ids not found or missing env_builder.py: {missing_ids}")
|
| 41 |
+
if not specs:
|
| 42 |
+
raise FileNotFoundError(f"no task directories matched {task_glob!r} under {tasks_root}")
|
| 43 |
+
return specs
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def find_script_root(base_tasks: Path) -> Path | None:
|
| 47 |
+
for dirname in ("scrips", "scripts"):
|
| 48 |
+
candidate = base_tasks / dirname
|
| 49 |
+
if candidate.is_dir():
|
| 50 |
+
return candidate
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def find_prompt_path(tasks_root: Path, task_dir: Path, task_id: str) -> Path:
|
| 55 |
+
candidates = (
|
| 56 |
+
tasks_root / "prompts" / f"{task_id}.md",
|
| 57 |
+
task_dir / "prompt.md",
|
| 58 |
+
task_dir / "task.md",
|
| 59 |
+
)
|
| 60 |
+
for candidate in candidates:
|
| 61 |
+
if candidate.is_file():
|
| 62 |
+
return candidate
|
| 63 |
+
raise FileNotFoundError(
|
| 64 |
+
f"prompt file not found for {task_id}; tried: "
|
| 65 |
+
+ ", ".join(str(path) for path in candidates)
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def find_verifier_path(script_root: Path, task_id: str) -> Path | None:
|
| 70 |
+
candidates = (
|
| 71 |
+
script_root / task_id / "verify_workplace.py",
|
| 72 |
+
script_root / f"{task_id}.py",
|
| 73 |
+
script_root / "verify_workplace.py",
|
| 74 |
+
)
|
| 75 |
+
for candidate in candidates:
|
| 76 |
+
if candidate.is_file():
|
| 77 |
+
return candidate
|
| 78 |
+
return None
|
v2/vllm_nanoclaw_runtime/tools.py
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import shlex
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from .types import ToolResult
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
DANGEROUS_PYTHON_PATTERNS = (
|
| 16 |
+
"rm -",
|
| 17 |
+
"rmtree",
|
| 18 |
+
"unlink",
|
| 19 |
+
"remove(",
|
| 20 |
+
"removedirs",
|
| 21 |
+
"rmdir",
|
| 22 |
+
"os.system",
|
| 23 |
+
"os.popen",
|
| 24 |
+
"subprocess",
|
| 25 |
+
"shutil",
|
| 26 |
+
"send2trash",
|
| 27 |
+
"__import__",
|
| 28 |
+
"eval(",
|
| 29 |
+
"exec(",
|
| 30 |
+
"compile(",
|
| 31 |
+
"socket",
|
| 32 |
+
"httpx",
|
| 33 |
+
"requests",
|
| 34 |
+
"urllib",
|
| 35 |
+
)
|
| 36 |
+
ABSOLUTE_PATH_LITERAL = re.compile(r"[\"']/(?:[^\"']*)[\"']")
|
| 37 |
+
MAX_BASH_OUTPUT_CHARS = 4000
|
| 38 |
+
BASH_CONTROL_SPLIT = re.compile(r"\s*(?:&&|\|\||;|\n)\s*")
|
| 39 |
+
BASH_UNSUPPORTED_TOKENS = (">", "<", "`", "$(", "${", "$[", "<(", ">(")
|
| 40 |
+
BASH_COMMANDS_WITH_PATH_OPERANDS = {
|
| 41 |
+
"cat",
|
| 42 |
+
"head",
|
| 43 |
+
"tail",
|
| 44 |
+
"wc",
|
| 45 |
+
"ls",
|
| 46 |
+
"mkdir",
|
| 47 |
+
"touch",
|
| 48 |
+
"rm",
|
| 49 |
+
"cp",
|
| 50 |
+
"mv",
|
| 51 |
+
"chmod",
|
| 52 |
+
}
|
| 53 |
+
BASH_ALLOWED_COMMANDS = BASH_COMMANDS_WITH_PATH_OPERANDS | {
|
| 54 |
+
"pwd",
|
| 55 |
+
"echo",
|
| 56 |
+
"printf",
|
| 57 |
+
"true",
|
| 58 |
+
"false",
|
| 59 |
+
"test",
|
| 60 |
+
"[",
|
| 61 |
+
"set",
|
| 62 |
+
"grep",
|
| 63 |
+
"find",
|
| 64 |
+
"sort",
|
| 65 |
+
"uniq",
|
| 66 |
+
"cut",
|
| 67 |
+
"bash",
|
| 68 |
+
"sh",
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def execute_actions(
|
| 73 |
+
actions: list[dict[str, Any]],
|
| 74 |
+
workspace: Path,
|
| 75 |
+
*,
|
| 76 |
+
args: Any,
|
| 77 |
+
step: int,
|
| 78 |
+
) -> tuple[list[dict[str, Any]], str, bool, str | None]:
|
| 79 |
+
action_events: list[dict[str, Any]] = []
|
| 80 |
+
observations: list[str] = []
|
| 81 |
+
final_answer: str | None = None
|
| 82 |
+
is_final = False
|
| 83 |
+
|
| 84 |
+
for index, action in enumerate(actions, start=1):
|
| 85 |
+
result = execute_action(action, workspace, args=args, step=step)
|
| 86 |
+
action_name = str(action.get("action") or action.get("tool") or "<missing>")
|
| 87 |
+
action_events.append(
|
| 88 |
+
{
|
| 89 |
+
"index": index,
|
| 90 |
+
"action": action,
|
| 91 |
+
"observation": result.observation,
|
| 92 |
+
"is_final": result.is_final,
|
| 93 |
+
}
|
| 94 |
+
)
|
| 95 |
+
observations.append(f"Tool result {index} ({action_name}):\n{result.observation}")
|
| 96 |
+
if result.is_final:
|
| 97 |
+
is_final = True
|
| 98 |
+
final_answer = result.final_answer
|
| 99 |
+
break
|
| 100 |
+
|
| 101 |
+
return action_events, "\n\n".join(observations), is_final, final_answer
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def execute_action(action: dict[str, Any], workspace: Path, *, args: Any, step: int) -> ToolResult:
|
| 105 |
+
action_name = str(action.get("action", "")).strip()
|
| 106 |
+
try:
|
| 107 |
+
if action_name in {"list_dir", "ls"}:
|
| 108 |
+
path = str(action.get("path") or ".")
|
| 109 |
+
if bool(action.get("recursive", False)):
|
| 110 |
+
return ToolResult(list_dir_recursive(workspace, path, limit=args.list_limit))
|
| 111 |
+
return ToolResult(list_dir(workspace, path, limit=args.list_limit))
|
| 112 |
+
if action_name in {"read_file", "read"}:
|
| 113 |
+
return ToolResult(read_file(workspace, require_path_like(action), limit=args.read_limit))
|
| 114 |
+
if action_name in {"write_file", "write"}:
|
| 115 |
+
return ToolResult(write_file(workspace, require_path_like(action), require_string(action, "content")))
|
| 116 |
+
if action_name in {"edit_file", "edit"}:
|
| 117 |
+
return ToolResult(
|
| 118 |
+
edit_file(
|
| 119 |
+
workspace,
|
| 120 |
+
require_path_like(action),
|
| 121 |
+
require_string(action, "old_text"),
|
| 122 |
+
require_string(action, "new_text"),
|
| 123 |
+
replace_all=bool(action.get("replace_all", False)),
|
| 124 |
+
)
|
| 125 |
+
)
|
| 126 |
+
if action_name == "apply_patch":
|
| 127 |
+
changes = action.get("changes")
|
| 128 |
+
if not isinstance(changes, list):
|
| 129 |
+
return ToolResult("Error: 'changes' must be a list.")
|
| 130 |
+
return ToolResult(apply_workspace_patch(workspace, changes))
|
| 131 |
+
if action_name == "grep":
|
| 132 |
+
return ToolResult(
|
| 133 |
+
grep_workspace(
|
| 134 |
+
workspace,
|
| 135 |
+
require_string(action, "pattern"),
|
| 136 |
+
action.get("glob"),
|
| 137 |
+
limit=args.list_limit,
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
if action_name == "find":
|
| 141 |
+
return ToolResult(find_workspace_files(workspace, action.get("pattern"), limit=args.list_limit))
|
| 142 |
+
if action_name in {"memory_search", "memory_get", "memory_append"}:
|
| 143 |
+
return ToolResult("Error: memory is disabled in this local no-memory runner.")
|
| 144 |
+
if action_name in {"exec", "execute_dangerous_command", "bash"}:
|
| 145 |
+
return ToolResult(
|
| 146 |
+
execute_bash(
|
| 147 |
+
workspace,
|
| 148 |
+
command=str(action.get("command", "")) if action.get("command") is not None else None,
|
| 149 |
+
script=str(action.get("script", "")) if action.get("script") is not None else None,
|
| 150 |
+
script_path=str(action.get("script_path", action.get("path", ""))) if (action.get("script_path") is not None or action.get("path") is not None) else None,
|
| 151 |
+
step=step,
|
| 152 |
+
timeout=float(getattr(args, "bash_timeout", 20.0)),
|
| 153 |
+
)
|
| 154 |
+
)
|
| 155 |
+
if action_name == "ask_human_for_confirmation":
|
| 156 |
+
command = str(action.get("command", ""))
|
| 157 |
+
return ToolResult(f"Human response: Reject (auto). Command not approved: {command}")
|
| 158 |
+
if action_name == "mkdir":
|
| 159 |
+
return ToolResult(make_dir(workspace, require_string(action, "path")))
|
| 160 |
+
if action_name == "run_python":
|
| 161 |
+
if not args.allow_python_tool:
|
| 162 |
+
return ToolResult("Error: run_python is disabled. Use read/write/edit/apply_patch actions instead.")
|
| 163 |
+
return ToolResult(run_python(workspace, require_string(action, "code"), step=step, timeout=args.python_timeout))
|
| 164 |
+
if action_name == "finish":
|
| 165 |
+
return ToolResult(
|
| 166 |
+
observation="Finished.",
|
| 167 |
+
is_final=True,
|
| 168 |
+
final_answer=str(action.get("answer") or ""),
|
| 169 |
+
)
|
| 170 |
+
if not action_name:
|
| 171 |
+
return ToolResult("Error: missing action field.")
|
| 172 |
+
return ToolResult(f"Error: Unknown tool '{action_name}'.")
|
| 173 |
+
except Exception as exc:
|
| 174 |
+
return ToolResult(f"Error while executing {action_name or '<missing>'}: {type(exc).__name__}: {exc}")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def require_string(action: dict[str, Any], key: str) -> str:
|
| 178 |
+
value = action.get(key)
|
| 179 |
+
if not isinstance(value, str):
|
| 180 |
+
raise ValueError(f"field {key!r} must be a string")
|
| 181 |
+
return value
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def require_path_like(action: dict[str, Any]) -> str:
|
| 185 |
+
value = action.get("path", action.get("filename"))
|
| 186 |
+
if not isinstance(value, str):
|
| 187 |
+
raise ValueError("field 'path' must be a string")
|
| 188 |
+
return value
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def resolve_workspace_path(workspace: Path, relative_path: str) -> Path:
|
| 192 |
+
raw_path = relative_path.strip() or "."
|
| 193 |
+
candidate_path = Path(raw_path)
|
| 194 |
+
if candidate_path.is_absolute():
|
| 195 |
+
raise ValueError(f"absolute paths are not allowed: {relative_path}")
|
| 196 |
+
if any(part == ".." for part in candidate_path.parts):
|
| 197 |
+
raise ValueError(f"parent path '..' is not allowed: {relative_path}")
|
| 198 |
+
resolved = (workspace / candidate_path).resolve()
|
| 199 |
+
workspace_resolved = workspace.resolve()
|
| 200 |
+
if resolved != workspace_resolved and workspace_resolved not in resolved.parents:
|
| 201 |
+
raise ValueError(f"path escapes workspace: {relative_path}")
|
| 202 |
+
return resolved
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def relative_workspace_path(workspace: Path, path: Path) -> str:
|
| 206 |
+
workspace_resolved = workspace.resolve()
|
| 207 |
+
path_resolved = path.resolve()
|
| 208 |
+
if path_resolved == workspace_resolved:
|
| 209 |
+
return "."
|
| 210 |
+
return path_resolved.relative_to(workspace_resolved).as_posix()
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def json_dumps(payload: Any) -> str:
|
| 214 |
+
return json.dumps(payload, ensure_ascii=False, indent=2)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def list_dir(workspace: Path, relative_path: str, *, limit: int) -> str:
|
| 218 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 219 |
+
if not path.exists():
|
| 220 |
+
return "Error: path not found."
|
| 221 |
+
if path.is_file():
|
| 222 |
+
return json_dumps(
|
| 223 |
+
{
|
| 224 |
+
"path": relative_workspace_path(workspace, path),
|
| 225 |
+
"entries": [
|
| 226 |
+
{
|
| 227 |
+
"path": relative_workspace_path(workspace, path),
|
| 228 |
+
"type": "file",
|
| 229 |
+
}
|
| 230 |
+
],
|
| 231 |
+
"truncated": False,
|
| 232 |
+
}
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
entries = []
|
| 236 |
+
truncated = False
|
| 237 |
+
for index, child in enumerate(sorted(path.iterdir())):
|
| 238 |
+
if index >= limit:
|
| 239 |
+
truncated = True
|
| 240 |
+
break
|
| 241 |
+
entries.append(
|
| 242 |
+
{
|
| 243 |
+
"path": relative_workspace_path(workspace, child),
|
| 244 |
+
"type": "dir" if child.is_dir() else "file",
|
| 245 |
+
}
|
| 246 |
+
)
|
| 247 |
+
return json_dumps(
|
| 248 |
+
{
|
| 249 |
+
"path": relative_workspace_path(workspace, path),
|
| 250 |
+
"entries": entries,
|
| 251 |
+
"truncated": truncated,
|
| 252 |
+
}
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def list_dir_recursive(workspace: Path, relative_path: str, *, limit: int) -> str:
|
| 257 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 258 |
+
if not path.exists():
|
| 259 |
+
return "Error: path not found."
|
| 260 |
+
if path.is_file():
|
| 261 |
+
return list_dir(workspace, relative_path, limit=limit)
|
| 262 |
+
|
| 263 |
+
entries = []
|
| 264 |
+
truncated = False
|
| 265 |
+
for index, child in enumerate(sorted(path.rglob("*"))):
|
| 266 |
+
if index >= limit:
|
| 267 |
+
truncated = True
|
| 268 |
+
break
|
| 269 |
+
entries.append(
|
| 270 |
+
{
|
| 271 |
+
"path": relative_workspace_path(workspace, child),
|
| 272 |
+
"type": "dir" if child.is_dir() else "file",
|
| 273 |
+
}
|
| 274 |
+
)
|
| 275 |
+
return json_dumps(
|
| 276 |
+
{
|
| 277 |
+
"path": relative_workspace_path(workspace, path),
|
| 278 |
+
"entries": entries,
|
| 279 |
+
"truncated": truncated,
|
| 280 |
+
}
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def read_file(workspace: Path, relative_path: str, *, limit: int) -> str:
|
| 285 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 286 |
+
if not path.exists():
|
| 287 |
+
return f"Error: file does not exist: {relative_path}"
|
| 288 |
+
if not path.is_file():
|
| 289 |
+
return f"Error: path is not a file: {relative_path}"
|
| 290 |
+
content = path.read_text(encoding="utf-8", errors="replace")
|
| 291 |
+
if len(content) > limit:
|
| 292 |
+
return content[:limit] + f"\n... truncated after {limit} characters"
|
| 293 |
+
return content
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def write_file(workspace: Path, relative_path: str, content: str) -> str:
|
| 297 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 298 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 299 |
+
path.write_text(content, encoding="utf-8")
|
| 300 |
+
return "Success: File written."
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def edit_file(
|
| 304 |
+
workspace: Path,
|
| 305 |
+
relative_path: str,
|
| 306 |
+
old_text: str,
|
| 307 |
+
new_text: str,
|
| 308 |
+
*,
|
| 309 |
+
replace_all: bool,
|
| 310 |
+
) -> str:
|
| 311 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 312 |
+
content = path.read_text(encoding="utf-8")
|
| 313 |
+
occurrences = content.count(old_text)
|
| 314 |
+
if occurrences == 0:
|
| 315 |
+
return "Error: target text not found."
|
| 316 |
+
if not replace_all and occurrences != 1:
|
| 317 |
+
return "Error: target text matched multiple locations. Pass replace_all=true or provide more specific old_text."
|
| 318 |
+
updated = content.replace(old_text, new_text) if replace_all else content.replace(old_text, new_text, 1)
|
| 319 |
+
path.write_text(updated, encoding="utf-8")
|
| 320 |
+
changed = occurrences if replace_all else 1
|
| 321 |
+
return f"Success: Applied {changed} edit(s)."
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def make_dir(workspace: Path, relative_path: str) -> str:
|
| 325 |
+
path = resolve_workspace_path(workspace, relative_path)
|
| 326 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 327 |
+
return f"Success: directory exists: {relative_path}."
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def apply_workspace_patch(workspace: Path, changes: list[Any]) -> str:
|
| 331 |
+
if not changes:
|
| 332 |
+
return "Error: no changes provided."
|
| 333 |
+
results: list[str] = []
|
| 334 |
+
for index, change in enumerate(changes, start=1):
|
| 335 |
+
if not isinstance(change, dict):
|
| 336 |
+
return f"Error: change #{index} must be an object."
|
| 337 |
+
try:
|
| 338 |
+
result = edit_file(
|
| 339 |
+
workspace,
|
| 340 |
+
require_path_like(change),
|
| 341 |
+
require_string(change, "old_text"),
|
| 342 |
+
require_string(change, "new_text"),
|
| 343 |
+
replace_all=bool(change.get("replace_all", False)),
|
| 344 |
+
)
|
| 345 |
+
except Exception as exc:
|
| 346 |
+
return f"Error: {type(exc).__name__}: {exc} (change #{index})"
|
| 347 |
+
if result.startswith("Error:"):
|
| 348 |
+
return f"{result} (change #{index})"
|
| 349 |
+
results.append(f"change #{index}: {result}")
|
| 350 |
+
return "Success: Patch applied.\n" + "\n".join(results)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def validate_glob_pattern(raw_pattern: str) -> str | None:
|
| 354 |
+
glob_path = Path(raw_pattern)
|
| 355 |
+
if glob_path.is_absolute() or any(part == ".." for part in glob_path.parts):
|
| 356 |
+
return "glob must stay inside the workspace"
|
| 357 |
+
return None
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def find_workspace_files(workspace: Path, pattern: Any, *, limit: int) -> str:
|
| 361 |
+
raw_pattern = str(pattern or "**/*").strip() or "**/*"
|
| 362 |
+
validation_error = validate_glob_pattern(raw_pattern)
|
| 363 |
+
if validation_error is not None:
|
| 364 |
+
return f"Error: {validation_error}."
|
| 365 |
+
|
| 366 |
+
files = []
|
| 367 |
+
truncated = False
|
| 368 |
+
for index, path in enumerate(sorted(path for path in workspace.glob(raw_pattern) if path.is_file())):
|
| 369 |
+
if index >= limit:
|
| 370 |
+
truncated = True
|
| 371 |
+
break
|
| 372 |
+
files.append(relative_workspace_path(workspace, path))
|
| 373 |
+
return json_dumps({"files": files, "truncated": truncated})
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def grep_workspace(workspace: Path, pattern: str, glob_pattern: Any, *, limit: int) -> str:
|
| 377 |
+
try:
|
| 378 |
+
regex = re.compile(pattern)
|
| 379 |
+
except re.error as exc:
|
| 380 |
+
return f"Error: invalid regex: {exc}"
|
| 381 |
+
|
| 382 |
+
raw_glob = str(glob_pattern or "**/*").strip() or "**/*"
|
| 383 |
+
validation_error = validate_glob_pattern(raw_glob)
|
| 384 |
+
if validation_error is not None:
|
| 385 |
+
return f"Error: {validation_error}."
|
| 386 |
+
|
| 387 |
+
matches: list[dict[str, Any]] = []
|
| 388 |
+
truncated = False
|
| 389 |
+
for path in sorted(path for path in workspace.glob(raw_glob) if path.is_file()):
|
| 390 |
+
try:
|
| 391 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 392 |
+
except OSError:
|
| 393 |
+
continue
|
| 394 |
+
relative = relative_workspace_path(workspace, path)
|
| 395 |
+
for line_number, line in enumerate(text.splitlines(), start=1):
|
| 396 |
+
if not regex.search(line):
|
| 397 |
+
continue
|
| 398 |
+
if len(matches) >= limit:
|
| 399 |
+
truncated = True
|
| 400 |
+
return json_dumps({"matches": matches, "truncated": truncated})
|
| 401 |
+
matches.append({"path": relative, "line": line_number, "text": line})
|
| 402 |
+
return json_dumps({"matches": matches, "truncated": truncated})
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def execute_bash(
|
| 406 |
+
workspace: Path,
|
| 407 |
+
*,
|
| 408 |
+
command: str | None,
|
| 409 |
+
script: str | None,
|
| 410 |
+
script_path: str | None,
|
| 411 |
+
step: int,
|
| 412 |
+
timeout: float,
|
| 413 |
+
) -> str:
|
| 414 |
+
provided = [value is not None and value.strip() != "" for value in (command, script, script_path)]
|
| 415 |
+
if sum(provided) != 1:
|
| 416 |
+
return "Error: provide exactly one of command, script, or script_path/path for bash execution."
|
| 417 |
+
|
| 418 |
+
temp_script_path: Path | None = None
|
| 419 |
+
try:
|
| 420 |
+
if script is not None and script.strip():
|
| 421 |
+
validation_error = validate_bash_text(workspace, script)
|
| 422 |
+
if validation_error is not None:
|
| 423 |
+
return validation_error
|
| 424 |
+
temp_script_path = workspace / f".vllm_nanoclaw_bash_step_{step}.sh"
|
| 425 |
+
temp_script_path.write_text(script, encoding="utf-8")
|
| 426 |
+
argv = ["bash", str(temp_script_path.name)]
|
| 427 |
+
elif script_path is not None and script_path.strip():
|
| 428 |
+
resolved_script_path = resolve_workspace_path(workspace, script_path)
|
| 429 |
+
if not resolved_script_path.is_file():
|
| 430 |
+
return f"Error: bash script does not exist: {script_path}"
|
| 431 |
+
script_content = resolved_script_path.read_text(encoding="utf-8", errors="replace")
|
| 432 |
+
validation_error = validate_bash_text(workspace, script_content)
|
| 433 |
+
if validation_error is not None:
|
| 434 |
+
return validation_error
|
| 435 |
+
argv = ["bash", script_path]
|
| 436 |
+
else:
|
| 437 |
+
raw_command = command or ""
|
| 438 |
+
validation_error = validate_bash_text(workspace, raw_command)
|
| 439 |
+
if validation_error is not None:
|
| 440 |
+
return validation_error
|
| 441 |
+
argv = ["bash", "-lc", raw_command]
|
| 442 |
+
|
| 443 |
+
try:
|
| 444 |
+
process = subprocess.run(
|
| 445 |
+
argv,
|
| 446 |
+
cwd=workspace,
|
| 447 |
+
text=True,
|
| 448 |
+
capture_output=True,
|
| 449 |
+
env=workspace_subprocess_env(workspace),
|
| 450 |
+
timeout=timeout,
|
| 451 |
+
check=False,
|
| 452 |
+
)
|
| 453 |
+
except subprocess.TimeoutExpired as exc:
|
| 454 |
+
stdout = exc.stdout or ""
|
| 455 |
+
stderr = exc.stderr or ""
|
| 456 |
+
output = format_process_output(stdout, stderr)
|
| 457 |
+
return f"Error: bash timed out after {timeout:g}s\n{output}"
|
| 458 |
+
finally:
|
| 459 |
+
if temp_script_path is not None:
|
| 460 |
+
try:
|
| 461 |
+
temp_script_path.unlink()
|
| 462 |
+
except FileNotFoundError:
|
| 463 |
+
pass
|
| 464 |
+
|
| 465 |
+
output = format_process_output(process.stdout, process.stderr)
|
| 466 |
+
if len(output) > MAX_BASH_OUTPUT_CHARS:
|
| 467 |
+
output = output[:MAX_BASH_OUTPUT_CHARS] + "\n...(truncated)"
|
| 468 |
+
if process.returncode != 0:
|
| 469 |
+
return f"Error: bash exited with code {process.returncode}\n{output}"
|
| 470 |
+
return output
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def format_process_output(stdout: str | bytes | None, stderr: str | bytes | None) -> str:
|
| 474 |
+
stdout_text = stdout.decode() if isinstance(stdout, bytes) else (stdout or "")
|
| 475 |
+
stderr_text = stderr.decode() if isinstance(stderr, bytes) else (stderr or "")
|
| 476 |
+
output_parts = []
|
| 477 |
+
if stdout_text.strip():
|
| 478 |
+
output_parts.append(stdout_text.strip())
|
| 479 |
+
if stderr_text.strip():
|
| 480 |
+
output_parts.append(f"[stderr]\n{stderr_text.strip()}")
|
| 481 |
+
return "\n\n".join(output_parts) if output_parts else "(no output)"
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def validate_bash_text(workspace: Path, text: str) -> str | None:
|
| 485 |
+
if not text.strip():
|
| 486 |
+
return "Error: empty bash command/script."
|
| 487 |
+
unsupported_error = validate_unsupported_bash_syntax(text)
|
| 488 |
+
if unsupported_error is not None:
|
| 489 |
+
return unsupported_error
|
| 490 |
+
|
| 491 |
+
for line_number, raw_line in enumerate(text.splitlines() or [text], start=1):
|
| 492 |
+
stripped_line = raw_line.strip()
|
| 493 |
+
if not stripped_line or stripped_line.startswith("#") or stripped_line.startswith("#!"):
|
| 494 |
+
continue
|
| 495 |
+
for raw_segment in BASH_CONTROL_SPLIT.split(stripped_line):
|
| 496 |
+
segment = raw_segment.strip()
|
| 497 |
+
if not segment:
|
| 498 |
+
continue
|
| 499 |
+
segment_error = validate_bash_segment(workspace, segment)
|
| 500 |
+
if segment_error is not None:
|
| 501 |
+
return f"Error: unsafe bash at line {line_number}: {segment_error}"
|
| 502 |
+
return None
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def validate_unsupported_bash_syntax(text: str) -> str | None:
|
| 506 |
+
normalized = text.replace("&&", "").replace("||", "")
|
| 507 |
+
if "&" in normalized:
|
| 508 |
+
return "Error: unsupported bash syntax '&'. Background jobs are not allowed."
|
| 509 |
+
pipe_normalized = text.replace("||", "")
|
| 510 |
+
if "|" in pipe_normalized:
|
| 511 |
+
return "Error: unsupported bash syntax '|'. Pipes are not allowed."
|
| 512 |
+
for token in BASH_UNSUPPORTED_TOKENS:
|
| 513 |
+
if token in text:
|
| 514 |
+
return f"Error: unsupported bash syntax {token!r}. Redirection, command substitution, and process substitution are not allowed."
|
| 515 |
+
if "$" in text:
|
| 516 |
+
return "Error: unsupported bash syntax '$'. Variable expansion is not allowed in model-generated bash."
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def validate_bash_segment(workspace: Path, segment: str) -> str | None:
|
| 521 |
+
try:
|
| 522 |
+
argv = shlex.split(segment)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
return f"invalid command syntax: {exc}"
|
| 525 |
+
if not argv:
|
| 526 |
+
return None
|
| 527 |
+
|
| 528 |
+
command_name = argv[0]
|
| 529 |
+
if command_name not in BASH_ALLOWED_COMMANDS:
|
| 530 |
+
return f"command {command_name!r} is not allowed. Allowed commands: {', '.join(sorted(BASH_ALLOWED_COMMANDS))}"
|
| 531 |
+
if command_name in {"bash", "sh"}:
|
| 532 |
+
return validate_nested_bash_script(workspace, argv)
|
| 533 |
+
if command_name == "set":
|
| 534 |
+
return validate_set_command(argv)
|
| 535 |
+
|
| 536 |
+
for operand in bash_path_operands(argv):
|
| 537 |
+
path_error = validate_workspace_operand(workspace, operand)
|
| 538 |
+
if path_error is not None:
|
| 539 |
+
return path_error
|
| 540 |
+
return None
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def validate_set_command(argv: list[str]) -> str | None:
|
| 544 |
+
for argument in argv[1:]:
|
| 545 |
+
if not argument.startswith("-") and not argument.startswith("+"):
|
| 546 |
+
return "set only supports shell option flags in this restricted runner"
|
| 547 |
+
return None
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def validate_nested_bash_script(workspace: Path, argv: list[str]) -> str | None:
|
| 551 |
+
operands = list(iter_operands(argv[1:]))
|
| 552 |
+
if not operands:
|
| 553 |
+
return "bash/sh requires a script path in this restricted runner"
|
| 554 |
+
if operands[0] in {"-c", "--command"} or any(argument in {"-c", "--command"} for argument in argv[1:]):
|
| 555 |
+
return "bash/sh -c is not allowed inside restricted bash; use the bash tool command field instead"
|
| 556 |
+
script_operand = operands[0]
|
| 557 |
+
path_error = validate_workspace_operand(workspace, script_operand)
|
| 558 |
+
if path_error is not None:
|
| 559 |
+
return path_error
|
| 560 |
+
script_path = resolve_workspace_path(workspace, script_operand)
|
| 561 |
+
if not script_path.is_file():
|
| 562 |
+
return f"bash script does not exist: {script_operand}"
|
| 563 |
+
return validate_bash_text(workspace, script_path.read_text(encoding="utf-8", errors="replace"))
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def bash_path_operands(argv: list[str]) -> list[str]:
|
| 567 |
+
command_name = argv[0]
|
| 568 |
+
args = argv[1:]
|
| 569 |
+
if command_name == "pwd" or command_name in {"echo", "printf", "true", "false", "test", "["}:
|
| 570 |
+
return []
|
| 571 |
+
if command_name == "grep":
|
| 572 |
+
operands = list(iter_operands(args, options_with_values={"-e", "--regexp", "-f", "--file", "-m", "--max-count", "-A", "-B", "-C", "--after-context", "--before-context", "--context", "--include", "--exclude", "--exclude-dir"}))
|
| 573 |
+
uses_explicit_pattern_option = any(argument in {"-e", "--regexp", "-f", "--file"} or argument.startswith("-e") for argument in args)
|
| 574 |
+
return operands if uses_explicit_pattern_option else operands[1:]
|
| 575 |
+
if command_name == "find":
|
| 576 |
+
operands: list[str] = []
|
| 577 |
+
iterator = iter(args)
|
| 578 |
+
for argument in iterator:
|
| 579 |
+
if argument == "--":
|
| 580 |
+
continue
|
| 581 |
+
if argument.startswith("-") or argument in {"!", "(", ")"}:
|
| 582 |
+
if argument in {"-name", "-path", "-type", "-maxdepth", "-mindepth", "-size", "-mtime", "-newer"}:
|
| 583 |
+
next(iterator, None)
|
| 584 |
+
continue
|
| 585 |
+
operands.append(argument)
|
| 586 |
+
return operands[:1]
|
| 587 |
+
if command_name == "cut":
|
| 588 |
+
return list(iter_operands(args, options_with_values={"-b", "-c", "-d", "-f", "--bytes", "--characters", "--delimiter", "--fields"}))
|
| 589 |
+
if command_name in {"head", "tail"}:
|
| 590 |
+
return list(iter_operands(args, options_with_values={"-n", "--lines", "-c", "--bytes"}))
|
| 591 |
+
if command_name == "chmod":
|
| 592 |
+
operands = list(iter_operands(args))
|
| 593 |
+
return operands[1:]
|
| 594 |
+
return list(iter_operands(args))
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def iter_operands(args: list[str], *, options_with_values: set[str] | None = None) -> list[str]:
|
| 598 |
+
options_with_values = options_with_values or set()
|
| 599 |
+
operands: list[str] = []
|
| 600 |
+
skip_next = False
|
| 601 |
+
after_double_dash = False
|
| 602 |
+
for argument in args:
|
| 603 |
+
if skip_next:
|
| 604 |
+
skip_next = False
|
| 605 |
+
continue
|
| 606 |
+
if not after_double_dash and argument == "--":
|
| 607 |
+
after_double_dash = True
|
| 608 |
+
continue
|
| 609 |
+
if not after_double_dash and argument.startswith("-") and argument != "-":
|
| 610 |
+
option_name = argument.split("=", 1)[0]
|
| 611 |
+
if option_name in options_with_values and "=" not in argument:
|
| 612 |
+
skip_next = True
|
| 613 |
+
continue
|
| 614 |
+
operands.append(argument)
|
| 615 |
+
return operands
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def validate_workspace_operand(workspace: Path, operand: str) -> str | None:
|
| 619 |
+
if operand in {"", "-"}:
|
| 620 |
+
return None
|
| 621 |
+
if operand.startswith("~"):
|
| 622 |
+
return f"path {operand!r} is not allowed: '~' expansion is disabled"
|
| 623 |
+
|
| 624 |
+
candidate_path = Path(operand)
|
| 625 |
+
workspace_resolved = workspace.resolve()
|
| 626 |
+
resolved = candidate_path.resolve() if candidate_path.is_absolute() else (workspace / candidate_path).resolve()
|
| 627 |
+
if resolved != workspace_resolved and workspace_resolved not in resolved.parents:
|
| 628 |
+
return f"path escapes workspace: {operand}"
|
| 629 |
+
return None
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def run_python(workspace: Path, code: str, *, step: int, timeout: float) -> str:
|
| 633 |
+
safety_error = validate_python_tool_code(code)
|
| 634 |
+
if safety_error is not None:
|
| 635 |
+
return f"Error: blocked unsafe Python code: {safety_error}"
|
| 636 |
+
|
| 637 |
+
script_path = workspace / f".vllm_nanoclaw_step_{step}.py"
|
| 638 |
+
script_path.write_text(code, encoding="utf-8")
|
| 639 |
+
try:
|
| 640 |
+
try:
|
| 641 |
+
process = subprocess.run(
|
| 642 |
+
[sys.executable, str(script_path.name)],
|
| 643 |
+
cwd=workspace,
|
| 644 |
+
text=True,
|
| 645 |
+
capture_output=True,
|
| 646 |
+
env=workspace_subprocess_env(workspace),
|
| 647 |
+
timeout=timeout,
|
| 648 |
+
check=False,
|
| 649 |
+
)
|
| 650 |
+
except subprocess.TimeoutExpired as exc:
|
| 651 |
+
stdout = exc.stdout or ""
|
| 652 |
+
stderr = exc.stderr or ""
|
| 653 |
+
output_parts = []
|
| 654 |
+
if stdout:
|
| 655 |
+
output_parts.append(str(stdout).strip())
|
| 656 |
+
if stderr:
|
| 657 |
+
output_parts.append(f"[stderr]\n{str(stderr).strip()}")
|
| 658 |
+
output = "\n\n".join(output_parts) if output_parts else "(no output)"
|
| 659 |
+
return f"Error: Python timed out after {timeout:g}s\n{output}"
|
| 660 |
+
finally:
|
| 661 |
+
try:
|
| 662 |
+
script_path.unlink()
|
| 663 |
+
except FileNotFoundError:
|
| 664 |
+
pass
|
| 665 |
+
|
| 666 |
+
output_parts = []
|
| 667 |
+
if process.stdout.strip():
|
| 668 |
+
output_parts.append(process.stdout.strip())
|
| 669 |
+
if process.stderr.strip():
|
| 670 |
+
output_parts.append(f"[stderr]\n{process.stderr.strip()}")
|
| 671 |
+
output = "\n\n".join(output_parts) if output_parts else "(no output)"
|
| 672 |
+
if process.returncode != 0:
|
| 673 |
+
return f"Error: Python exited with code {process.returncode}\n{output}"
|
| 674 |
+
return output
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def validate_python_tool_code(code: str) -> str | None:
|
| 678 |
+
lowered = code.lower()
|
| 679 |
+
if ".." in code:
|
| 680 |
+
return "parent-directory path '..' is not allowed"
|
| 681 |
+
absolute_match = ABSOLUTE_PATH_LITERAL.search(code)
|
| 682 |
+
if absolute_match:
|
| 683 |
+
return f"absolute path literal is not allowed: {absolute_match.group(0)}"
|
| 684 |
+
for pattern in DANGEROUS_PYTHON_PATTERNS:
|
| 685 |
+
if pattern in lowered:
|
| 686 |
+
return f"forbidden pattern {pattern!r}"
|
| 687 |
+
return None
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def workspace_subprocess_env(workspace: Path) -> dict[str, str]:
|
| 691 |
+
workspace_resolved = workspace.resolve()
|
| 692 |
+
home_dir = workspace_resolved / ".runner_home"
|
| 693 |
+
tmp_dir = workspace_resolved / ".runner_tmp"
|
| 694 |
+
home_dir.mkdir(parents=True, exist_ok=True)
|
| 695 |
+
tmp_dir.mkdir(parents=True, exist_ok=True)
|
| 696 |
+
|
| 697 |
+
env = dict(os.environ)
|
| 698 |
+
env["HOME"] = str(home_dir)
|
| 699 |
+
env["TMPDIR"] = str(tmp_dir)
|
| 700 |
+
env["TEMP"] = str(tmp_dir)
|
| 701 |
+
env["TMP"] = str(tmp_dir)
|
| 702 |
+
env["PWD"] = str(workspace_resolved)
|
| 703 |
+
env["PYTHONNOUSERSITE"] = "1"
|
| 704 |
+
env["NANOCLAW_WORKSPACE"] = str(workspace_resolved)
|
| 705 |
+
return env
|
v2/vllm_nanoclaw_runtime/types.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass(frozen=True, slots=True)
|
| 9 |
+
class TaskSpec:
|
| 10 |
+
task_id: str
|
| 11 |
+
task_dir: Path
|
| 12 |
+
prompt_path: Path
|
| 13 |
+
env_builder_path: Path
|
| 14 |
+
verifier_path: Path | None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True, slots=True)
|
| 18 |
+
class ToolResult:
|
| 19 |
+
observation: str
|
| 20 |
+
is_final: bool = False
|
| 21 |
+
final_answer: str | None = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass(slots=True)
|
| 25 |
+
class TaskRunState:
|
| 26 |
+
spec: TaskSpec
|
| 27 |
+
result_dir: Path
|
| 28 |
+
workspace_before: Path
|
| 29 |
+
workspace_after: Path
|
| 30 |
+
history_path: Path
|
| 31 |
+
metadata_path: Path
|
| 32 |
+
prompt_text: str
|
| 33 |
+
env_result: dict[str, Any]
|
| 34 |
+
started_at: str
|
| 35 |
+
messages: list[dict[str, str]] = field(default_factory=list)
|
| 36 |
+
events: list[dict[str, Any]] = field(default_factory=list)
|
| 37 |
+
status: str = "running"
|
| 38 |
+
error: str | None = None
|
| 39 |
+
final_answer: str | None = None
|
| 40 |
+
steps_used: int = 0
|
| 41 |
+
verifier_result: dict[str, Any] | None = None
|