Spaces:
Running
Running
Sync WebFetch and model selector updates
Browse filesFiles changed (8)
113 unmodified lines114115116117118119113 unmodified lines| `RH_SPACE_RETENTION_SECONDS` | `21600` | Delete inactive runs older than this many seconds. || `RH_SPACE_MAX_RUNS` | `40` | Keep at most this many inactive runs. || `RH_SPACE_CLEANUP_INTERVAL_SECONDS` | `900` | Background cleanup interval. || `RH_COLLECTION_ENABLED` | `true` | Automatically collect completed hosted runs. || `RH_COLLECTION_DATASET_REPO` | `CoCoOne/ResearchHarness-Data` | Dataset repo that receives trajectory PRs. || `RH_COLLECTION_BATCH_SIZE` | `5` | Create one dataset PR after this many collected runs. |113 unmodified lines114115116117118119120121113 unmodified lines| `RH_SPACE_RETENTION_SECONDS` | `21600` | Delete inactive runs older than this many seconds. || `RH_SPACE_MAX_RUNS` | `40` | Keep at most this many inactive runs. || `RH_SPACE_CLEANUP_INTERVAL_SECONDS` | `900` | Background cleanup interval. || `WEBFETCH_TIMEOUT_SECONDS` | `180` | Overall timeout for one WebFetch tool call. || `WEBFETCH_MAX_CHARS` | `30000` | Hard maximum characters returned by one URL-only WebFetch call. || `RH_COLLECTION_ENABLED` | `true` | Automatically collect completed hosted runs. || `RH_COLLECTION_DATASET_REPO` | `CoCoOne/ResearchHarness-Data` | Dataset repo that receives trajectory PRs. || `RH_COLLECTION_BATCH_SIZE` | `5` | Create one dataset PR after this many collected runs. |
20 unmodified lines21222324252627282930312 unmodified lines3435363738394024 unmodified lines6566676869707120 unmodified lines929394959697989910010110210310420 unmodified linespath=PROMPTS_DIR / "system_base.md",description="Base general-purpose system prompt for the harness.",),"extractor": PromptAsset(name="extractor",path=PROMPTS_DIR / "extractor.md",description="Goal-directed webpage extraction prompt used by WebFetch.",),}2 unmodified linesSYSTEM_PROMPT = _read_prompt_asset(PROMPT_ASSETS["system_base"])EXTRACTOR_PROMPT = _read_prompt_asset(PROMPT_ASSETS["extractor"])def _normalize_extra_blocks(blocks: Iterable[str] | None) -> list[str]:24 unmodified linesdef main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description="Inspect prompt assets.")parser.add_argument("--show-system", action="store_true", help="Print the composed system prompt.")parser.add_argument("--show-extractor", action="store_true", help="Print the extractor prompt.")parser.add_argument("--show-asset", metavar="NAME", help="Print one prompt asset by name.")parser.add_argument("--list-assets", action="store_true", help="List registered prompt assets.")parser.add_argument(20 unmodified linesprint(composed_system_prompt(current_date="<DATE>", extra_blocks=extra_blocks))return 0if args.show_extractor:print(EXTRACTOR_PROMPT)return 0print(f"prompt_asset_dir={PROMPTS_DIR}")print(f"system_prompt_chars={len(composed_system_prompt(current_date='<DATE>', extra_blocks=extra_blocks))}")print(f"extractor_prompt_chars={len(EXTRACTOR_PROMPT)}")return 020 unmodified lines2122232425262 unmodified lines29303132333424 unmodified lines59606162636420 unmodified lines858687888990919220 unmodified linespath=PROMPTS_DIR / "system_base.md",description="Base general-purpose system prompt for the harness.",),}2 unmodified linesSYSTEM_PROMPT = _read_prompt_asset(PROMPT_ASSETS["system_base"])def _normalize_extra_blocks(blocks: Iterable[str] | None) -> list[str]:24 unmodified linesdef main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description="Inspect prompt assets.")parser.add_argument("--show-system", action="store_true", help="Print the composed system prompt.")parser.add_argument("--show-asset", metavar="NAME", help="Print one prompt asset by name.")parser.add_argument("--list-assets", action="store_true", help="List registered prompt assets.")parser.add_argument(20 unmodified linesprint(composed_system_prompt(current_date="<DATE>", extra_blocks=extra_blocks))return 0print(f"prompt_asset_dir={PROMPTS_DIR}")print(f"system_prompt_chars={len(composed_system_prompt(current_date='<DATE>', extra_blocks=extra_blocks))}")return 0
12345678910111213141516171819Please process the following webpage content and user goal to extract relevant information.
## **Webpage Content** {webpage_content}
## **User Goal**{goal}
## **Task Guidelines**1. **Content Scanning for Rationale**: Locate the **specific sections/data** directly related to the user's goal within the webpage content2. **Key Extraction for Evidence**: Identify and extract the **most relevant information** from the content. Preserve the most useful original context as fully as practical.3. **Summary Output for Summary**: Organize a concise, goal-focused summary with clear logical flow.
## **Output Requirements**- Return a single JSON object only.- Required keys: `"rational"`, `"evidence"`, `"summary"`.- All three fields must always be present.- `"evidence"` and `"summary"` must be non-empty strings whenever relevant content exists.- If the page is irrelevant or insufficient, still return valid strings explaining that limitation.167 unmodified lines168169170171172173167 unmodified lines- fetch the chosen page with `WebFetch`- only then produce the final result- Do not treat `WebSearch` or `ScholarSearch` snippets as a substitute for `WebFetch` when page verification is required.- The `visited_url` in the final result should be a URL that was actually passed to `WebFetch`.## Terminal Workflow167 unmodified lines168169170171172173174167 unmodified lines- fetch the chosen page with `WebFetch`- only then produce the final result- Do not treat `WebSearch` or `ScholarSearch` snippets as a substitute for `WebFetch` when page verification is required.- `WebFetch` returns cleaned page text with line and truncation metadata. If the response is truncated or the needed evidence is outside the returned range, call `WebFetch` again with a narrower `start_line` / `end_line` range instead of repeating the same request.- The `visited_url` in the final result should be a URL that was actually passed to `WebFetch`.## Terminal Workflow
1234567891011121314151617181920212223242518 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394212 unmodified lines3073083093103113123135 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623631 unmodified line36536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346445 unmodified lines5105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066079 unmodified lines6176186196206216226233 unmodified lines627628629630631632633import argparseimport jsonimport osimport sysimport timefrom concurrent.futures import ThreadPoolExecutorfrom typing import Optional, Unionimport requestsimport tiktokenfrom openai import APIConnectionError, APIError, APITimeoutError, OpenAIfrom agent_base.provider_compat import apply_sampling_paramsfrom agent_base.prompt import EXTRACTOR_PROMPTfrom agent_base.tools.tooling import ToolBasefrom agent_base.utils import PROJECT_ROOT, env_flag, load_dotenvDEFAULT_LLM_TIMEOUT_SECONDS = 600.0DEFAULT_LLM_MAX_RETRIES = 10DEFAULT_TEMPERATURE = 0.6DEFAULT_TOP_P = 0.95DEFAULT_PRESENCE_PENALTY = 1.1def search_debug_enabled() -> bool:18 unmodified linesreturn f"{exc}; response_body={body}" if body else str(exc)def truncate_to_tokens(text: str, max_tokens: int = 95000) -> str:encoding = tiktoken.get_encoding("cl100k_base")tokens = encoding.encode(text)if len(tokens) <= max_tokens:return texttruncated_tokens = tokens[:max_tokens]return encoding.decode(truncated_tokens)def _stringify_field(value) -> str:if isinstance(value, str):return value.strip()if value is None:return ""if isinstance(value, (list, dict)):try:return json.dumps(value, ensure_ascii=False)except (TypeError, ValueError):return str(value).strip()return str(value).strip()def _webfetch_failure(url: str, goal: str, reason: str) -> str:useful_information = "The useful information in {url} for user goal {goal} as follows: \n\n".format(url=url, goal=goal)useful_information += "Evidence in page: \n" + reason + "\n\n"useful_information += "Summary: \n" + "The webpage content could not be processed into the required structured summary." + "\n\n"return useful_informationdef _parse_extractor_payload(raw) -> tuple[str, str] | None:if isinstance(raw, str):raw = raw.replace("```json", "").replace("```", "").strip()try:raw = json.loads(raw)except json.JSONDecodeError:return Noneif not isinstance(raw, dict):return Noneevidence = _stringify_field(raw.get("evidence"))summary = _stringify_field(raw.get("summary"))if not evidence or not summary:return Nonereturn evidence, summaryclass WebSearch(ToolBase):212 unmodified linesclass WebFetch(ToolBase):name = "WebFetch"description = "Fetch webpage content and return evidence plus a goal-focused summary."parameters = {"type": "object","properties": {5 unmodified lines"minItems": 1,"description": "The URL(s) of the webpage(s) to visit. Can be a single URL or an array of URLs.",},"goal": {"type": "string","description": "The goal of the visit for webpage(s).",},},"required": ["url", "goal"],}def __init__(self, cfg: Optional[dict] = None):super().__init__(cfg)self._summary_client: Optional[OpenAI] = Noneself._summary_api_base: Optional[str] = Noneself._summary_model_name = os.environ.get("MODEL_NAME", "").strip()self._summary_timeout_seconds = float(os.getenv("LLM_TIMEOUT_SECONDS", str(DEFAULT_LLM_TIMEOUT_SECONDS)))self._summary_temperature = float(os.getenv("TEMPERATURE", str(DEFAULT_TEMPERATURE)))self._summary_top_p = float(os.getenv("TOP_P", str(DEFAULT_TOP_P)))self._summary_presence_penalty = float(os.getenv("PRESENCE_PENALTY", str(DEFAULT_PRESENCE_PENALTY)))def _ensure_summary_client(self) -> Optional[OpenAI]:if self._summary_client is not None:return self._summary_clientself._summary_api_base = os.environ.get("API_BASE")self._summary_model_name = os.environ.get("MODEL_NAME", "").strip()self._summary_timeout_seconds = float(os.getenv("LLM_TIMEOUT_SECONDS", str(DEFAULT_LLM_TIMEOUT_SECONDS)))self._summary_temperature = float(os.getenv("TEMPERATURE", str(DEFAULT_TEMPERATURE)))self._summary_top_p = float(os.getenv("TOP_P", str(DEFAULT_TOP_P)))self._summary_presence_penalty = float(os.getenv("PRESENCE_PENALTY", str(DEFAULT_PRESENCE_PENALTY)))if not self._summary_api_base:return Noneself._summary_client = OpenAI(api_key=os.environ.get("API_KEY", "EMPTY"),base_url=self._summary_api_base,timeout=self._summary_timeout_seconds,)return self._summary_client@staticmethoddef _remaining_budget_seconds(runtime_deadline: Optional[float]) -> Optional[float]:1 unmodified linereturn Nonereturn runtime_deadline - time.time()def call(self, params: Union[str, dict], **kwargs) -> str:try:params = self.parse_json_args(params)url = params["url"]goal = params["goal"]except ValueError as exc:return f"[WebFetch] {exc}"runtime_deadline = kwargs.get("runtime_deadline")summary_model_name = str(kwargs.get("model_name") or "").strip()start_time = time.time()if isinstance(url, str):response = self.readpage_jina(url, goal, runtime_deadline=runtime_deadline, summary_model_name=summary_model_name)elif isinstance(url, list):response = []start_time = time.time()for one_url in url:remaining = self._remaining_budget_seconds(runtime_deadline)if remaining is not None and remaining <= 0:cur_response = _webfetch_failure(url=one_url,goal=goal,reason="Agent runtime limit reached before WebFetch could complete.",)response.append(cur_response)continueif time.time() - start_time > 900:cur_response = "The useful information in {url} for user goal {goal} as follows: \n\n".format(url=one_url, goal=goal)cur_response += "Evidence in page: \n" + "The provided webpage content could not be accessed. Please check the URL or file format." + "\n\n"cur_response += "Summary: \n" + "The webpage content could not be processed, and therefore, no information is available." + "\n\n"else:cur_response = self.readpage_jina(one_url,goal,runtime_deadline=runtime_deadline,summary_model_name=summary_model_name,)response.append(cur_response)response = "\n=======\n".join(response)else:return "[WebFetch] 'url' must be a string or a list of strings."if visit_debug_enabled():print(f"Summary Length {len(response)}")return response.strip()def call_server(self,msgs,max_retries=2,runtime_deadline: Optional[float] = None,model_name: str = "",):client = self._ensure_summary_client()if client is None or not self._summary_api_base:return "[WebFetch] Summary model error: API_BASE is not set."summary_model_name = str(model_name or self._summary_model_name or os.environ.get("MODEL_NAME", "")).strip()if not summary_model_name:return "[WebFetch] Summary model error: MODEL_NAME is not set."last_error = "unknown summary-model error"for attempt in range(max_retries):remaining = self._remaining_budget_seconds(runtime_deadline)if remaining is not None and remaining <= 0:return "[WebFetch] Summary model error: agent runtime limit reached."try:request_client = (client.with_options(timeout=min(self._summary_timeout_seconds, max(remaining, 0.001)))if remaining is not Noneelse client)request_kwargs = {"model": summary_model_name,"messages": msgs,}apply_sampling_params(request_kwargs,model_name=summary_model_name,temperature=self._summary_temperature,top_p=self._summary_top_p,presence_penalty=self._summary_presence_penalty,)chat_response = request_client.chat.completions.create(**request_kwargs)content = chat_response.choices[0].message.contentif content:return contentlast_error = "empty response from summary model"except (APIError, APIConnectionError, APITimeoutError) as exc:last_error = str(exc)if attempt == (max_retries - 1):return f"[WebFetch] Summary model error: {last_error}"return f"[WebFetch] Summary model error: {last_error}"def jina_readpage(self, url: str, runtime_deadline: Optional[float] = None) -> str:max_retries = 3timeout = 5045 unmodified linesdef readpage_jina(self,url: str,goal: str,runtime_deadline: Optional[float] = None,summary_model_name: str = "",) -> str:def summary_page_func(messages, max_retries=2, runtime_deadline: Optional[float] = None):return self.call_server(messages,max_retries=max_retries,runtime_deadline=runtime_deadline,model_name=summary_model_name,)max_retries = int(os.getenv("LLM_MAX_RETRIES", str(DEFAULT_LLM_MAX_RETRIES)))content = self.html_readpage_jina(url, runtime_deadline=runtime_deadline)if content and not content.startswith("[WebFetch] Failed to read page:") and content != "[WebFetch] Empty content." and not content.startswith("[document_parser]"):content = truncate_to_tokens(content, max_tokens=95000)messages = [{"role": "user", "content": EXTRACTOR_PROMPT.format(webpage_content=content, goal=goal)}]raw = summary_page_func(messages, max_retries=max_retries, runtime_deadline=runtime_deadline)summary_retries = 3while len(raw) < 10 and summary_retries >= 0:remaining = self._remaining_budget_seconds(runtime_deadline)if remaining is not None and remaining <= 0:return _webfetch_failure(url=url,goal=goal,reason="Agent runtime limit reached before WebFetch could complete.",)truncate_length = int(0.7 * len(content)) if summary_retries > 0 else 25000status_msg = (f"[WebFetch] Summary url[{url}] "f"attempt {3 - summary_retries + 1}/3, "f"content length: {len(content)}, "f"truncating to {truncate_length} chars") if summary_retries > 0 else (f"[WebFetch] Summary url[{url}] failed after 3 attempts, "f"final truncation to 25000 chars")if visit_debug_enabled():print(status_msg)content = content[:truncate_length]extraction_prompt = EXTRACTOR_PROMPT.format(webpage_content=content,goal=goal,)messages = [{"role": "user", "content": extraction_prompt}]raw = summary_page_func(messages, max_retries=max_retries, runtime_deadline=runtime_deadline)summary_retries -= 1parse_retry_times = 0parsed = _parse_extractor_payload(raw)while parse_retry_times < 3:if parsed is not None:breakremaining = self._remaining_budget_seconds(runtime_deadline)if remaining is not None and remaining <= 0:return _webfetch_failure(url=url,goal=goal,reason="Agent runtime limit reached before WebFetch could complete.",)raw = summary_page_func(messages, max_retries=max_retries, runtime_deadline=runtime_deadline)parsed = _parse_extractor_payload(raw)parse_retry_times += 1if parsed is None:reason = "The webpage content was fetched, but the summary model did not return the required evidence and summary fields."if isinstance(raw, str) and raw.startswith("[WebFetch] Summary model error:"):reason = rawuseful_information = _webfetch_failure(url=url,goal=goal,reason=reason,)else:evidence, summary = parseduseful_information = "The useful information in {url} for user goal {goal} as follows: \n\n".format(url=url, goal=goal)useful_information += "Evidence in page: \n" + evidence + "\n\n"useful_information += "Summary: \n" + summary + "\n\n"if len(useful_information) < 10 and summary_retries < 0:if visit_debug_enabled():print("[WebFetch] Could not generate valid summary after maximum retries")useful_information = "[WebFetch] Failed to read page."return useful_informationreturn _webfetch_failure(url=url,goal=goal,reason="The provided webpage content could not be accessed. Please check the URL or file format.",)9 unmodified linesfetch_parser = subparsers.add_parser("fetch", help="Run WebFetch.")fetch_parser.add_argument("url")fetch_parser.add_argument("goal")args = parser.parse_args(argv)load_dotenv(PROJECT_ROOT / ".env")3 unmodified lineselif args.tool == "scholar":result = ScholarSearch().call({"query": [" ".join(args.query)]})else:result = WebFetch().call({"url": args.url, "goal": args.goal})print(result)return 012345678910111213141516171819202122232425262728293031323318 unmodified lines5253545556575859606162212 unmodified lines2752762772782792802815 unmodified lines2872882892902912922932942952962972982993003013023033043053063073083093101 unmodified line31231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441545 unmodified lines4614624634644654664674684694704714724734744754764774784794804819 unmodified lines4914924934944954964974984993 unmodified lines503504505506507508509510511512513514515516import argparseimport jsonimport osimport reimport sysimport timefrom concurrent.futures import ThreadPoolExecutorfrom typing import Optional, Unionimport requestsfrom agent_base.tools.tooling import ToolBasefrom agent_base.utils import PROJECT_ROOT, env_flag, load_dotenvDEFAULT_WEBFETCH_TIMEOUT_SECONDS = 180.0DEFAULT_WEBFETCH_MAX_CHARS = 30000def webfetch_timeout_seconds() -> float:timeout = float(os.getenv("WEBFETCH_TIMEOUT_SECONDS", str(DEFAULT_WEBFETCH_TIMEOUT_SECONDS)))if timeout <= 0:raise ValueError("WEBFETCH_TIMEOUT_SECONDS must be > 0.")return timeoutdef webfetch_default_max_chars() -> int:max_chars = int(os.getenv("WEBFETCH_MAX_CHARS", str(DEFAULT_WEBFETCH_MAX_CHARS)))if max_chars <= 0:raise ValueError("WEBFETCH_MAX_CHARS must be > 0.")return max_charsdef search_debug_enabled() -> bool:18 unmodified linesreturn f"{exc}; response_body={body}" if body else str(exc)def _clean_webpage_text(text: str) -> str:text = str(text or "").replace("\r\n", "\n").replace("\r", "\n").replace("\x00", "")text = re.sub(r"[ \t]+\n", "\n", text)text = re.sub(r"\n{4,}", "\n\n\n", text)return text.strip()class WebSearch(ToolBase):212 unmodified linesclass WebFetch(ToolBase):name = "WebFetch"description = "Fetch webpage content and return cleaned, range-bounded page text for the agent to inspect."parameters = {"type": "object","properties": {5 unmodified lines"minItems": 1,"description": "The URL(s) of the webpage(s) to visit. Can be a single URL or an array of URLs.",},"start_line": {"type": "integer","description": "Optional 1-based start line for partial reading. Default is 1.",},"end_line": {"type": "integer","description": "Optional 1-based end line for partial reading. If omitted, read to the end.",},"max_chars": {"type": "integer","description": "Maximum number of characters to return. Default is 30000 and the value must not exceed WEBFETCH_MAX_CHARS.",},},"required": ["url"],}def __init__(self, cfg: Optional[dict] = None):super().__init__(cfg)@staticmethoddef _remaining_budget_seconds(runtime_deadline: Optional[float]) -> Optional[float]:1 unmodified linereturn Nonereturn runtime_deadline - time.time()@staticmethoddef _webfetch_deadline(runtime_deadline: Optional[float]) -> float:tool_deadline = time.time() + webfetch_timeout_seconds()if runtime_deadline is None:return tool_deadlinereturn min(float(runtime_deadline), tool_deadline)@staticmethoddef _format_page_content(*,url: str,content: str,start_line: int,end_line: Optional[int],max_chars: int,) -> str:clean_content = _clean_webpage_text(content)lines = clean_content.splitlines()selected_lines = lines[start_line - 1:end_line]selected_content = "\n".join(selected_lines)truncated = len(selected_content) > max_charsreturned_content = selected_content[:max_chars] if truncated else selected_contenteffective_end_line = end_line if end_line is not None else len(lines)meta = [f"url: {url}","source_type: web",f"start_line: {start_line}",f"end_line: {effective_end_line}",f"total_lines: {len(lines)}",f"total_chars: {len(clean_content)}",f"max_chars: {max_chars}",f"returned_chars: {len(returned_content)}",f"truncated: {str(truncated).lower()}",]if truncated:meta.append("note: content was truncated by max_chars; use a narrower line range, or raise max_chars only up to WEBFETCH_MAX_CHARS if this call used a smaller value.")return "\n".join(meta) + "\ncontent:\n" + returned_contentdef call(self, params: Union[str, dict], **kwargs) -> str:try:params = self.parse_json_args(params)url = params["url"]except ValueError as exc:return f"[WebFetch] {exc}"try:start_line = int(params.get("start_line", 1))end_line_raw = params.get("end_line")end_line = int(end_line_raw) if end_line_raw is not None else Nonemax_chars_limit = webfetch_default_max_chars()max_chars_raw = params.get("max_chars")max_chars = int(max_chars_raw) if max_chars_raw is not None else max_chars_limitexcept (TypeError, ValueError):return "[WebFetch] start_line, end_line, and max_chars must be integers when provided."if start_line < 1:return "[WebFetch] start_line must be >= 1."if end_line is not None and end_line < start_line:return "[WebFetch] end_line must be >= start_line."if max_chars <= 0:return "[WebFetch] max_chars must be > 0."if max_chars > max_chars_limit:return f"[WebFetch] max_chars must be <= WEBFETCH_MAX_CHARS ({max_chars_limit}). Use a narrower line range to read more of the page."try:runtime_deadline = self._webfetch_deadline(kwargs.get("runtime_deadline"))except ValueError as exc:return f"[WebFetch] {exc}"if isinstance(url, str):response = self.readpage_jina(url,start_line=start_line,end_line=end_line,max_chars=max_chars,runtime_deadline=runtime_deadline,)elif isinstance(url, list):response = []for one_url in url:remaining = self._remaining_budget_seconds(runtime_deadline)if remaining is not None and remaining <= 0:cur_response = "[WebFetch] Failed to read page: agent runtime limit reached."response.append(cur_response)continuecur_response = self.readpage_jina(one_url,start_line=start_line,end_line=end_line,max_chars=max_chars,runtime_deadline=runtime_deadline,)response.append(cur_response)response = "\n=======\n".join(response)else:return "[WebFetch] 'url' must be a string or a list of strings."if visit_debug_enabled():print(f"WebFetch Length {len(response)}")return response.strip()def jina_readpage(self, url: str, runtime_deadline: Optional[float] = None) -> str:max_retries = 3timeout = 5045 unmodified linesdef readpage_jina(self,url: str,*,start_line: int = 1,end_line: Optional[int] = None,max_chars: int = DEFAULT_WEBFETCH_MAX_CHARS,runtime_deadline: Optional[float] = None,) -> str:content = self.html_readpage_jina(url, runtime_deadline=runtime_deadline)if not content or content.startswith("[WebFetch] Failed to read page:") or content == "[WebFetch] Empty content." or content.startswith("[document_parser]"):return "[WebFetch] Failed to read page: the provided webpage content could not be accessed. Please check the URL or file format."return self._format_page_content(url=url,content=content,start_line=start_line,end_line=end_line,max_chars=max_chars,)9 unmodified linesfetch_parser = subparsers.add_parser("fetch", help="Run WebFetch.")fetch_parser.add_argument("url")fetch_parser.add_argument("--start-line", type=int, default=1)fetch_parser.add_argument("--end-line", type=int)fetch_parser.add_argument("--max-chars", type=int)args = parser.parse_args(argv)load_dotenv(PROJECT_ROOT / ".env")3 unmodified lineselif args.tool == "scholar":result = ScholarSearch().call({"query": [" ".join(args.query)]})else:result = WebFetch().call({"url": args.url,"start_line": args.start_line,"end_line": args.end_line,"max_chars": args.max_chars if args.max_chars is not None else webfetch_default_max_chars(),})print(result)return 0
123 unmodified lines12412512612712812913084 unmodified lines215216217218219220221222223123 unmodified lines.topbar {position: sticky;top: 0;z-index: 4;display: flex;align-items: center;justify-content: space-between;84 unmodified linespadding: 8px 12px;}.model-select {min-width: 150px;padding: 8px 34px 8px 12px;}.plain:hover,123 unmodified lines12412512612712812913084 unmodified lines215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304123 unmodified lines.topbar {position: sticky;top: 0;z-index: 8;display: flex;align-items: center;justify-content: space-between;84 unmodified linespadding: 8px 12px;}.model-dropdown {position: relative;}.model-select {min-width: 150px;display: inline-flex;align-items: center;justify-content: space-between;gap: 12px;padding: 8px 12px;text-align: left;white-space: nowrap;}.model-select-caret {width: 7px;height: 7px;border-right: 2px solid var(--muted);border-bottom: 2px solid var(--muted);transform: translateY(-2px) rotate(45deg);transition: transform 0.18s ease;}.model-dropdown.open .model-select-caret {transform: translateY(2px) rotate(225deg);}.model-options {position: absolute;top: calc(100% + 8px);right: 0;z-index: 30;display: grid;gap: 4px;min-width: 220px;padding: 6px;border: 1px solid rgba(var(--glow-rgb), 0.18);border-radius: 18px;background: var(--panel-strong);box-shadow: 0 22px 70px rgba(0, 0, 0, 0.16);opacity: 0;pointer-events: none;transform: translateY(-6px) scale(0.98);transform-origin: top right;transition: opacity 0.16s ease, transform 0.16s ease;}.model-dropdown.open .model-options {opacity: 1;pointer-events: auto;transform: translateY(0) scale(1);}.model-option {border: 0;border-radius: 12px;background: transparent;color: var(--text);cursor: pointer;display: flex;align-items: center;justify-content: space-between;gap: 16px;font: inherit;font-weight: 850;padding: 9px 12px;text-align: left;white-space: nowrap;}.model-option:hover,.model-option:focus-visible,.model-option.selected {background: rgba(var(--glow-rgb), 0.1);}.model-option.selected::after {content: "";width: 7px;height: 7px;border-radius: 999px;background: currentColor;opacity: 0.72;}.plain:hover,
134 unmodified lines13513613713813914070 unmodified lines211212213214215216217218219220221222223224225226227228229230365 unmodified lines596597598599600601134 unmodified linesvar runBtn = document.getElementById("runBtn");var newBtn = document.getElementById("newBtn");var modelSelect = document.getElementById("modelSelect");var attachBtn = document.getElementById("attachBtn");var imageInput = document.getElementById("imageInput");var imagePreview = document.getElementById("imagePreview");70 unmodified linesstatusPill.className = "status " + (kind || "idle");}function updateComposerMode() {if (pendingAskId) {runBtn.disabled = false;runBtn.classList.remove("is-running");runBtn.textContent = "Reply";promptInput.placeholder = defaultPromptPlaceholder;if (modelSelect) modelSelect.disabled = true;return;}runBtn.disabled = running && interrupting;runBtn.classList.toggle("is-running", running);runBtn.textContent = running ? (interrupting ? "Stopping" : "Stop") : "Run";promptInput.placeholder = defaultPromptPlaceholder;if (modelSelect) modelSelect.disabled = running;}function setRunning(active, statusText) {365 unmodified lines});}runBtn.addEventListener("click", sendStart);timeline.addEventListener("scroll", syncTimelineFollowMode);timeline.addEventListener("wheel", function (event) {134 unmodified lines13513613713813914014114214314470 unmodified lines215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281365 unmodified lines647648649650651652653654134 unmodified linesvar runBtn = document.getElementById("runBtn");var newBtn = document.getElementById("newBtn");var modelSelect = document.getElementById("modelSelect");var modelDropdown = document.getElementById("modelDropdown");var modelDropdownButton = document.getElementById("modelDropdownButton");var modelSelectLabel = document.getElementById("modelSelectLabel");var modelOptions = document.getElementById("modelOptions");var attachBtn = document.getElementById("attachBtn");var imageInput = document.getElementById("imageInput");var imagePreview = document.getElementById("imagePreview");70 unmodified linesstatusPill.className = "status " + (kind || "idle");}function closeModelDropdown() {if (!modelDropdown || !modelDropdownButton) return;modelDropdown.classList.remove("open");modelDropdownButton.setAttribute("aria-expanded", "false");}function setModelValue(value) {if (!modelSelect || !value) return;modelSelect.value = value;if (modelSelectLabel) modelSelectLabel.textContent = value;if (!modelOptions) return;modelOptions.querySelectorAll(".model-option").forEach(function (option) {var selected = option.getAttribute("data-model-value") === value;option.classList.toggle("selected", selected);option.setAttribute("aria-selected", selected ? "true" : "false");});}function setModelControlDisabled(disabled) {if (modelSelect) modelSelect.disabled = disabled;if (modelDropdownButton) modelDropdownButton.disabled = disabled;if (disabled) closeModelDropdown();}function setupModelDropdown() {if (!modelDropdown || !modelDropdownButton || !modelOptions || !modelSelect) return;setModelValue(modelSelect.value || "gpt-5.5");modelDropdownButton.addEventListener("click", function () {if (modelDropdownButton.disabled) return;var shouldOpen = !modelDropdown.classList.contains("open");modelDropdown.classList.toggle("open", shouldOpen);modelDropdownButton.setAttribute("aria-expanded", shouldOpen ? "true" : "false");});modelOptions.querySelectorAll(".model-option").forEach(function (option) {option.addEventListener("click", function () {setModelValue(option.getAttribute("data-model-value"));closeModelDropdown();});});document.addEventListener("click", function (event) {if (!modelDropdown.contains(event.target)) closeModelDropdown();});document.addEventListener("keydown", function (event) {if (event.key === "Escape") closeModelDropdown();});}function updateComposerMode() {if (pendingAskId) {runBtn.disabled = false;runBtn.classList.remove("is-running");runBtn.textContent = "Reply";promptInput.placeholder = defaultPromptPlaceholder;setModelControlDisabled(true);return;}runBtn.disabled = running && interrupting;runBtn.classList.toggle("is-running", running);runBtn.textContent = running ? (interrupting ? "Stopping" : "Stop") : "Run";promptInput.placeholder = defaultPromptPlaceholder;setModelControlDisabled(running);}function setRunning(active, statusText) {365 unmodified lines});}setupModelDropdown();runBtn.addEventListener("click", sendStart);timeline.addEventListener("scroll", syncTimelineFollowMode);timeline.addEventListener("wheel", function (event) {
18 unmodified lines1920212223242526272818 unmodified lines</div></div><div class="top-actions"><select id="modelSelect" class="model-select" aria-label="Model"><option value="gpt-5.5">gpt-5.5</option><option value="claude-opus-4-7">claude-opus-4-7</option></select><button id="newBtn" class="plain" type="button">New chat</button></div></header>18 unmodified lines192021222324252627282930313233343518 unmodified lines</div></div><div class="top-actions"><div id="modelDropdown" class="model-dropdown"><button id="modelDropdownButton" class="model-select" type="button" aria-haspopup="listbox" aria-expanded="false"><span id="modelSelectLabel">gpt-5.5</span><span class="model-select-caret" aria-hidden="true"></span></button><input id="modelSelect" type="hidden" value="gpt-5.5" /><div id="modelOptions" class="model-options" role="listbox" aria-label="Model"><button class="model-option selected" type="button" role="option" aria-selected="true" data-model-value="gpt-5.5">gpt-5.5</button><button class="model-option" type="button" role="option" aria-selected="false" data-model-value="claude-opus-4-7">claude-opus-4-7</button></div></div><button id="newBtn" class="plain" type="button">New chat</button></div></header>
README.md+2
agent_base/prompt.py-12
agent_base/prompts/extractor.mdDeleted-19
agent_base/prompts/system_base.md+1
agent_base/tools/tool_web.py+132-249
frontend/static/app.css+83-2
frontend/static/app.js+55-2
frontend/static/index.html+11-4