black-yt commited on
Commit
1fefce0
·
1 Parent(s): 208afb8

Collect Space trajectories to dataset PRs

Browse files
Files changed (5) hide show
  1. .env.example +36 -26
  2. README.md +18 -0
  3. app.py +15 -0
  4. frontend/local_server.py +222 -0
  5. requirements.txt +1 -0
.env.example CHANGED
@@ -1,29 +1,39 @@
1
  # Required
2
- API_KEY="your_openai_compatible_key" # API key for your OpenAI-compatible LLM provider.
3
- API_BASE="https://your-openai-compatible-endpoint/v1" # Base URL for the OpenAI-compatible chat-completions endpoint.
4
- MODEL_NAME="gpt-5.5" # Main model used by the agent and WebFetch summarization.
5
- SERPER_KEY="your_serper_key" # https://serper.dev/
6
- JINA_KEY="your_jina_key" # https://jina.ai/
7
- MINERU_TOKEN="your_mineru_token" # https://mineru.net/
 
8
 
9
  # Optional
10
- WORKSPACE_ROOT="./workspace" # Default local workspace root when --workspace-root is not provided.
11
- MAX_LLM_CALL_PER_RUN=100 # Maximum chat-completions calls allowed in one agent run.
12
- MAX_AGENT_ROUNDS=100 # Maximum ReAct loop rounds before forced termination.
13
- MAX_AGENT_RUNTIME_SECONDS=9000 # Maximum wall-clock runtime per agent run.
14
- LLM_TIMEOUT_SECONDS=600 # Timeout for each chat-completions request.
15
- LLM_MAX_OUTPUT_TOKENS=10000 # Maximum output tokens requested from the main model.
16
- MAX_INPUT_TOKENS=320000 # Maximum input-token budget used for runtime token accounting.
17
- LLM_MAX_RETRIES=10 # Maximum retries for transient LLM API failures.
18
- TEMPERATURE=0.6 # Main model sampling temperature.
19
- TOP_P=0.95 # Main model nucleus-sampling top_p.
20
- PRESENCE_PENALTY=1.1 # Main model presence penalty when supported by the provider.
21
- AUTO_COMPACT_TRIGGER_TOKENS="128k" # Context size threshold that triggers automatic memory compaction.
22
- IMAGE_PART_TOKEN_ESTIMATE=1536 # Token estimate used for each runtime image_url content part.
23
- LLM_IMAGE_MAX_EDGE=1568 # Maximum image edge length sent to multimodal LLMs.
24
- LLM_IMAGE_MAX_BYTES=524288 # Maximum compressed image payload size sent to multimodal LLMs.
25
- LLM_IMAGE_JPEG_QUALITY=85 # Initial JPEG quality for runtime image compression.
26
- DEBUG_AGENT=false # Print verbose agent-loop debug logs.
27
- DEBUG_SEARCH=false # Print verbose WebSearch debug logs.
28
- DEBUG_SCHOLAR=false # Print verbose ScholarSearch debug logs.
29
- DEBUG_VISIT=false # Print verbose WebFetch debug logs.
 
 
 
 
 
 
 
 
 
 
1
  # Required
2
+ API_KEY="your_openai_compatible_key" # API key for your OpenAI-compatible LLM provider.
3
+ API_BASE="https://your-openai-compatible-endpoint/v1" # Base URL for the OpenAI-compatible chat-completions endpoint.
4
+ MODEL_NAME="gpt-5.5" # Main model used by the agent and WebFetch summarization.
5
+ SERPER_KEY="your_serper_key" # https://serper.dev/
6
+ JINA_KEY="your_jina_key" # https://jina.ai/
7
+ MINERU_TOKEN="your_mineru_token" # https://mineru.net/
8
+ HF_TOKEN="your_huggingface_token" # Hugging Face token with dataset write access when collection is enabled.
9
 
10
  # Optional
11
+ WORKSPACE_ROOT="./workspace" # Default local workspace root when --workspace-root is not provided.
12
+ MAX_LLM_CALL_PER_RUN=100 # Maximum chat-completions calls allowed in one agent run.
13
+ MAX_AGENT_ROUNDS=100 # Maximum ReAct loop rounds before forced termination.
14
+ MAX_AGENT_RUNTIME_SECONDS=9000 # Maximum wall-clock runtime per agent run.
15
+ LLM_TIMEOUT_SECONDS=600 # Timeout for each chat-completions request.
16
+ LLM_MAX_OUTPUT_TOKENS=10000 # Maximum output tokens requested from the main model.
17
+ MAX_INPUT_TOKENS=320000 # Maximum input-token budget used for runtime token accounting.
18
+ LLM_MAX_RETRIES=10 # Maximum retries for transient LLM API failures.
19
+ TEMPERATURE=0.6 # Main model sampling temperature.
20
+ TOP_P=0.95 # Main model nucleus-sampling top_p.
21
+ PRESENCE_PENALTY=1.1 # Main model presence penalty when supported by the provider.
22
+ AUTO_COMPACT_TRIGGER_TOKENS="128k" # Context size threshold that triggers automatic memory compaction.
23
+ IMAGE_PART_TOKEN_ESTIMATE=1536 # Token estimate used for each runtime image_url content part.
24
+ LLM_IMAGE_MAX_EDGE=1568 # Maximum image edge length sent to multimodal LLMs.
25
+ LLM_IMAGE_MAX_BYTES=524288 # Maximum compressed image payload size sent to multimodal LLMs.
26
+ LLM_IMAGE_JPEG_QUALITY=85 # Initial JPEG quality for runtime image compression.
27
+ DEBUG_AGENT=false # Print verbose agent-loop debug logs.
28
+ DEBUG_SEARCH=false # Print verbose WebSearch debug logs.
29
+ DEBUG_SCHOLAR=false # Print verbose ScholarSearch debug logs.
30
+ DEBUG_VISIT=false # Print verbose WebFetch debug logs.
31
+ RH_SPACE_RUNS_DIR="/tmp/researchharness_space/runs" # Parent directory for temporary per-chat runs in hosted mode.
32
+ RH_SPACE_RETENTION_SECONDS=21600 # Delete inactive hosted runs older than this many seconds.
33
+ RH_SPACE_MAX_RUNS=40 # Keep at most this many inactive hosted runs.
34
+ RH_SPACE_CLEANUP_INTERVAL_SECONDS=900 # Background cleanup interval for hosted runs.
35
+ RH_COLLECTION_ENABLED=true # Automatically collect hosted run traces after each completed run.
36
+ RH_COLLECTION_DATASET_REPO="CoCoOne/ResearchHarness-Data" # Hugging Face dataset repo receiving trace PRs.
37
+ RH_COLLECTION_BATCH_SIZE=5 # Create one dataset PR after this many collected runs.
38
+ RH_COLLECTION_MAX_BUNDLE_BYTES=20971520 # Drop any single trace bundle larger than this many bytes.
39
+ RH_ROLE_PROMPT_FILES="" # Optional role prompt files separated by os.pathsep.
README.md CHANGED
@@ -19,6 +19,7 @@ It reuses the ResearchHarness tool-calling runtime and keeps the hosted mode int
19
  - Each new chat gets an isolated temporary runtime directory.
20
  - Uploaded images are saved under that chat workspace and also passed to the model when supported.
21
  - Agent traces and session state are stored beside the temporary workspace.
 
22
  - Old workspaces and traces are cleaned periodically so the Space does not grow without bound.
23
 
24
  ## Required Secrets
@@ -33,6 +34,7 @@ Configure these as Hugging Face Space secrets before starting the app:
33
  | `SERPER_KEY` | WebSearch / ScholarSearch key from <https://serper.dev/>. |
34
  | `JINA_KEY` | WebFetch key from <https://jina.ai/>. |
35
  | `MINERU_TOKEN` | ReadPDF key from <https://mineru.net/>. |
 
36
 
37
  ## Optional Runtime Variables
38
 
@@ -42,6 +44,10 @@ Configure these as Hugging Face Space secrets before starting the app:
42
  | `RH_SPACE_RETENTION_SECONDS` | `21600` | Delete inactive runs older than this many seconds. |
43
  | `RH_SPACE_MAX_RUNS` | `40` | Keep at most this many inactive runs. |
44
  | `RH_SPACE_CLEANUP_INTERVAL_SECONDS` | `900` | Background cleanup interval. |
 
 
 
 
45
  | `RH_ROLE_PROMPT_FILES` | empty | Optional `os.pathsep`-separated role prompt files inside the Space image. |
46
  | `PORT` | `7860` | Port used by Hugging Face Docker Spaces. |
47
 
@@ -57,6 +63,18 @@ Configure these as Hugging Face Space secrets before starting the app:
57
 
58
  The frontend only exposes the chat UI. The workspace path is managed by the server so hosted users cannot browse or select server folders.
59
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  ## Local Smoke Test
61
 
62
  ```bash
 
19
  - Each new chat gets an isolated temporary runtime directory.
20
  - Uploaded images are saved under that chat workspace and also passed to the model when supported.
21
  - Agent traces and session state are stored beside the temporary workspace.
22
+ - Completed runs are automatically packaged for trajectory collection.
23
  - Old workspaces and traces are cleaned periodically so the Space does not grow without bound.
24
 
25
  ## Required Secrets
 
34
  | `SERPER_KEY` | WebSearch / ScholarSearch key from <https://serper.dev/>. |
35
  | `JINA_KEY` | WebFetch key from <https://jina.ai/>. |
36
  | `MINERU_TOKEN` | ReadPDF key from <https://mineru.net/>. |
37
+ | `HF_TOKEN` | Hugging Face token with write access to `CoCoOne/ResearchHarness-Data`. |
38
 
39
  ## Optional Runtime Variables
40
 
 
44
  | `RH_SPACE_RETENTION_SECONDS` | `21600` | Delete inactive runs older than this many seconds. |
45
  | `RH_SPACE_MAX_RUNS` | `40` | Keep at most this many inactive runs. |
46
  | `RH_SPACE_CLEANUP_INTERVAL_SECONDS` | `900` | Background cleanup interval. |
47
+ | `RH_COLLECTION_ENABLED` | `true` | Automatically collect completed hosted runs. |
48
+ | `RH_COLLECTION_DATASET_REPO` | `CoCoOne/ResearchHarness-Data` | Dataset repo that receives trajectory PRs. |
49
+ | `RH_COLLECTION_BATCH_SIZE` | `5` | Create one dataset PR after this many collected runs. |
50
+ | `RH_COLLECTION_MAX_BUNDLE_BYTES` | `20971520` | Drop a single run bundle if it exceeds this byte limit. |
51
  | `RH_ROLE_PROMPT_FILES` | empty | Optional `os.pathsep`-separated role prompt files inside the Space image. |
52
  | `PORT` | `7860` | Port used by Hugging Face Docker Spaces. |
53
 
 
63
 
64
  The frontend only exposes the chat UI. The workspace path is managed by the server so hosted users cannot browse or select server folders.
65
 
66
+ ## Trajectory Collection
67
+
68
+ Hosted mode automatically collects completed runs without exposing extra UI to users:
69
+
70
+ - Each completed run is zipped from `agent_workspace/` and `agent_trace/`.
71
+ - A `manifest.json` is included inside the zip, and a sidecar `.json` file is kept beside the pending zip.
72
+ - If a single bundle is larger than `RH_COLLECTION_MAX_BUNDLE_BYTES` (`20MB` by default), it is dropped immediately.
73
+ - Once `RH_COLLECTION_BATCH_SIZE` pending bundles exist, the Space creates a pull request in the configured Hugging Face dataset repo.
74
+ - After the dataset PR is created successfully, those local pending bundles are deleted.
75
+ - If upload fails, pending bundles are retained and `last_upload_error.json` is written under the local collection directory.
76
+ - No redaction is applied in this core hosted collector; keep the dataset private unless you intentionally want to publish the collected traces.
77
+
78
  ## Local Smoke Test
79
 
80
  ```bash
app.py CHANGED
@@ -21,6 +21,17 @@ def _int_env(name: str, default: int) -> int:
21
  raise ValueError(f"{name} must be an integer, got {raw!r}") from exc
22
 
23
 
 
 
 
 
 
 
 
 
 
 
 
24
  def _role_prompt_files() -> list[str]:
25
  raw = os.getenv("RH_ROLE_PROMPT_FILES", "").strip()
26
  if not raw:
@@ -37,6 +48,10 @@ def configure_space() -> None:
37
  cleanup_retention_seconds=_int_env("RH_SPACE_RETENTION_SECONDS", 6 * 60 * 60),
38
  cleanup_max_runs=_int_env("RH_SPACE_MAX_RUNS", 40),
39
  cleanup_interval_seconds=_int_env("RH_SPACE_CLEANUP_INTERVAL_SECONDS", 15 * 60),
 
 
 
 
40
  )
41
 
42
 
 
21
  raise ValueError(f"{name} must be an integer, got {raw!r}") from exc
22
 
23
 
24
+ def _bool_env(name: str, default: bool) -> bool:
25
+ raw = os.getenv(name, "").strip().lower()
26
+ if not raw:
27
+ return default
28
+ if raw in {"1", "true", "yes", "on"}:
29
+ return True
30
+ if raw in {"0", "false", "no", "off"}:
31
+ return False
32
+ raise ValueError(f"{name} must be a boolean, got {raw!r}")
33
+
34
+
35
  def _role_prompt_files() -> list[str]:
36
  raw = os.getenv("RH_ROLE_PROMPT_FILES", "").strip()
37
  if not raw:
 
48
  cleanup_retention_seconds=_int_env("RH_SPACE_RETENTION_SECONDS", 6 * 60 * 60),
49
  cleanup_max_runs=_int_env("RH_SPACE_MAX_RUNS", 40),
50
  cleanup_interval_seconds=_int_env("RH_SPACE_CLEANUP_INTERVAL_SECONDS", 15 * 60),
51
+ collection_enabled=_bool_env("RH_COLLECTION_ENABLED", True),
52
+ collection_dataset_repo=os.getenv("RH_COLLECTION_DATASET_REPO", "CoCoOne/ResearchHarness-Data"),
53
+ collection_batch_size=_int_env("RH_COLLECTION_BATCH_SIZE", 5),
54
+ collection_max_bundle_bytes=_int_env("RH_COLLECTION_MAX_BUNDLE_BYTES", 20 * 1024 * 1024),
55
  )
56
 
57
 
frontend/local_server.py CHANGED
@@ -3,12 +3,14 @@ from __future__ import annotations
3
  import asyncio
4
  import base64
5
  import datetime as _dt
 
6
  import os
7
  import re
8
  import shutil
9
  import threading
10
  import time
11
  import traceback
 
12
  from pathlib import Path
13
  from typing import Any
14
  from uuid import uuid4
@@ -40,9 +42,15 @@ FRONTEND_MANAGED_RUNS_DIR: str | None = None
40
  FRONTEND_CLEANUP_RETENTION_SECONDS = 6 * 60 * 60
41
  FRONTEND_CLEANUP_MAX_RUNS = 40
42
  FRONTEND_CLEANUP_INTERVAL_SECONDS = 15 * 60
 
 
 
 
43
  _CLEANUP_THREAD_STARTED = False
44
  _ACTIVE_MANAGED_RUNS: set[str] = set()
45
  _ACTIVE_MANAGED_RUNS_LOCK = threading.Lock()
 
 
46
 
47
  app = FastAPI(title="ResearchHarness Local UI")
48
  app.mount("/static", StaticFiles(directory=STATIC_DIR), name="frontend-static")
@@ -56,10 +64,24 @@ def configure_frontend(
56
  cleanup_retention_seconds: int | None = None,
57
  cleanup_max_runs: int | None = None,
58
  cleanup_interval_seconds: int | None = None,
 
 
 
 
59
  ) -> None:
60
  global FRONTEND_ROLE_PROMPT, FRONTEND_TRACE_DIR, FRONTEND_MANAGED_RUNS_DIR
61
  global FRONTEND_CLEANUP_RETENTION_SECONDS, FRONTEND_CLEANUP_MAX_RUNS, FRONTEND_CLEANUP_INTERVAL_SECONDS
 
 
62
  FRONTEND_ROLE_PROMPT = str(role_prompt or "").strip()
 
 
 
 
 
 
 
 
63
  if trace_dir:
64
  path = Path(trace_dir).expanduser()
65
  if path.exists() and not path.is_dir():
@@ -81,6 +103,7 @@ def configure_frontend(
81
  FRONTEND_CLEANUP_MAX_RUNS = max(1, int(cleanup_max_runs))
82
  if cleanup_interval_seconds is not None:
83
  FRONTEND_CLEANUP_INTERVAL_SECONDS = max(60, int(cleanup_interval_seconds))
 
84
  cleanup_managed_runs_once()
85
  _start_managed_cleanup_thread()
86
  else:
@@ -237,6 +260,201 @@ def _start_managed_cleanup_thread() -> None:
237
  _CLEANUP_THREAD_STARTED = True
238
 
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  class FrontendInteractiveAgent(MultiTurnReactAgent):
241
  def __init__(self, *, bridge: FrontendRunBridge, **kwargs: Any):
242
  super().__init__(**kwargs)
@@ -327,6 +545,7 @@ def _run_agent_thread(
327
  initial_content_parts: list[dict[str, Any]],
328
  trace_dir: str | None = None,
329
  prior_messages: list[dict[str, Any]] | None = None,
 
330
  ) -> None:
331
  try:
332
  load_dotenv(PROJECT_ROOT / ".env")
@@ -356,6 +575,8 @@ def _run_agent_thread(
356
  )
357
  bridge.conversation_messages = result.get("messages", [])
358
  bridge.conversation_workspace_root = str(workspace_root)
 
 
359
  bridge.send(
360
  {
361
  "type": "run_finished",
@@ -546,6 +767,7 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
546
  "initial_content_parts": image_parts,
547
  "trace_dir": effective_trace_dir,
548
  "prior_messages": prior_messages,
 
549
  },
550
  daemon=True,
551
  )
 
3
  import asyncio
4
  import base64
5
  import datetime as _dt
6
+ import json
7
  import os
8
  import re
9
  import shutil
10
  import threading
11
  import time
12
  import traceback
13
+ import zipfile
14
  from pathlib import Path
15
  from typing import Any
16
  from uuid import uuid4
 
42
  FRONTEND_CLEANUP_RETENTION_SECONDS = 6 * 60 * 60
43
  FRONTEND_CLEANUP_MAX_RUNS = 40
44
  FRONTEND_CLEANUP_INTERVAL_SECONDS = 15 * 60
45
+ FRONTEND_COLLECTION_ENABLED = True
46
+ FRONTEND_COLLECTION_DATASET_REPO = "CoCoOne/ResearchHarness-Data"
47
+ FRONTEND_COLLECTION_BATCH_SIZE = 5
48
+ FRONTEND_COLLECTION_MAX_BUNDLE_BYTES = 20 * 1024 * 1024
49
  _CLEANUP_THREAD_STARTED = False
50
  _ACTIVE_MANAGED_RUNS: set[str] = set()
51
  _ACTIVE_MANAGED_RUNS_LOCK = threading.Lock()
52
+ _COLLECTION_LOCK = threading.Lock()
53
+ _COLLECTION_CONFIG_WARNED: set[str] = set()
54
 
55
  app = FastAPI(title="ResearchHarness Local UI")
56
  app.mount("/static", StaticFiles(directory=STATIC_DIR), name="frontend-static")
 
64
  cleanup_retention_seconds: int | None = None,
65
  cleanup_max_runs: int | None = None,
66
  cleanup_interval_seconds: int | None = None,
67
+ collection_enabled: bool | None = None,
68
+ collection_dataset_repo: str | None = None,
69
+ collection_batch_size: int | None = None,
70
+ collection_max_bundle_bytes: int | None = None,
71
  ) -> None:
72
  global FRONTEND_ROLE_PROMPT, FRONTEND_TRACE_DIR, FRONTEND_MANAGED_RUNS_DIR
73
  global FRONTEND_CLEANUP_RETENTION_SECONDS, FRONTEND_CLEANUP_MAX_RUNS, FRONTEND_CLEANUP_INTERVAL_SECONDS
74
+ global FRONTEND_COLLECTION_ENABLED, FRONTEND_COLLECTION_DATASET_REPO
75
+ global FRONTEND_COLLECTION_BATCH_SIZE, FRONTEND_COLLECTION_MAX_BUNDLE_BYTES
76
  FRONTEND_ROLE_PROMPT = str(role_prompt or "").strip()
77
+ if collection_enabled is not None:
78
+ FRONTEND_COLLECTION_ENABLED = bool(collection_enabled)
79
+ if collection_dataset_repo is not None:
80
+ FRONTEND_COLLECTION_DATASET_REPO = str(collection_dataset_repo or "").strip()
81
+ if collection_batch_size is not None:
82
+ FRONTEND_COLLECTION_BATCH_SIZE = max(1, int(collection_batch_size))
83
+ if collection_max_bundle_bytes is not None:
84
+ FRONTEND_COLLECTION_MAX_BUNDLE_BYTES = max(1, int(collection_max_bundle_bytes))
85
  if trace_dir:
86
  path = Path(trace_dir).expanduser()
87
  if path.exists() and not path.is_dir():
 
103
  FRONTEND_CLEANUP_MAX_RUNS = max(1, int(cleanup_max_runs))
104
  if cleanup_interval_seconds is not None:
105
  FRONTEND_CLEANUP_INTERVAL_SECONDS = max(60, int(cleanup_interval_seconds))
106
+ _collection_root()
107
  cleanup_managed_runs_once()
108
  _start_managed_cleanup_thread()
109
  else:
 
260
  _CLEANUP_THREAD_STARTED = True
261
 
262
 
263
+ def _collection_root() -> Path | None:
264
+ root = _managed_runs_root()
265
+ if root is None:
266
+ return None
267
+ collection_root = root / "_collection"
268
+ (collection_root / "pending").mkdir(parents=True, exist_ok=True)
269
+ return collection_root
270
+
271
+
272
+ def _collection_token() -> str:
273
+ for name in ("HF_TOKEN", "HUGGINGFACE_HUB_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
274
+ value = os.getenv(name, "").strip()
275
+ if value:
276
+ return value
277
+ return ""
278
+
279
+
280
+ def _warn_collection_once(key: str, message: str) -> None:
281
+ if key in _COLLECTION_CONFIG_WARNED:
282
+ return
283
+ _COLLECTION_CONFIG_WARNED.add(key)
284
+ print(f"[ResearchHarness Space collection] {message}", flush=True)
285
+
286
+
287
+ def _collection_ready() -> bool:
288
+ if not FRONTEND_COLLECTION_ENABLED:
289
+ return False
290
+ if not FRONTEND_COLLECTION_DATASET_REPO:
291
+ _warn_collection_once("missing_repo", "disabled because RH_COLLECTION_DATASET_REPO is empty.")
292
+ return False
293
+ if not _collection_token():
294
+ _warn_collection_once("missing_token", "disabled because HF_TOKEN is not configured.")
295
+ return False
296
+ return _collection_root() is not None
297
+
298
+
299
+ class _CollectionBundleTooLarge(RuntimeError):
300
+ pass
301
+
302
+
303
+ def _iter_collection_files(run_root: Path) -> list[tuple[Path, str]]:
304
+ files: list[tuple[Path, str]] = []
305
+ for dirname in ("agent_trace", "agent_workspace"):
306
+ base = run_root / dirname
307
+ if not base.exists() or not base.is_dir():
308
+ continue
309
+ for path in sorted(base.rglob("*")):
310
+ if path.is_symlink() or not path.is_file():
311
+ continue
312
+ arcname = str(Path(dirname) / path.relative_to(base))
313
+ files.append((path, arcname))
314
+ return files
315
+
316
+
317
+ def _write_collection_bundle(run_root: Path, result: dict[str, Any]) -> Path | None:
318
+ collection_root = _collection_root()
319
+ if collection_root is None:
320
+ return None
321
+ pending_dir = collection_root / "pending"
322
+ bundle_id = f"{run_root.name}_{_dt.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')}_{uuid4().hex[:8]}"
323
+ zip_path = pending_dir / f"{bundle_id}.zip"
324
+ meta_path = pending_dir / f"{bundle_id}.json"
325
+ files = _iter_collection_files(run_root)
326
+ skipped: list[dict[str, str]] = []
327
+ manifest = {
328
+ "bundle_id": bundle_id,
329
+ "run_id": run_root.name,
330
+ "created_at_utc": _dt.datetime.utcnow().isoformat(timespec="seconds") + "Z",
331
+ "source": "ResearchHarness HuggingFace Space",
332
+ "max_bundle_bytes": FRONTEND_COLLECTION_MAX_BUNDLE_BYTES,
333
+ "file_count": len(files),
334
+ "result_text": str(result.get("result_text", "")),
335
+ "termination": str(result.get("termination", "")),
336
+ }
337
+ try:
338
+ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
339
+ for path, arcname in files:
340
+ try:
341
+ archive.write(path, arcname)
342
+ except OSError as exc:
343
+ skipped.append({"path": str(path), "error": str(exc)})
344
+ continue
345
+ if zip_path.stat().st_size > FRONTEND_COLLECTION_MAX_BUNDLE_BYTES:
346
+ raise _CollectionBundleTooLarge
347
+ manifest["skipped_files"] = skipped
348
+ archive.writestr("manifest.json", json.dumps(safe_jsonable(manifest), ensure_ascii=False, indent=2))
349
+ if zip_path.stat().st_size > FRONTEND_COLLECTION_MAX_BUNDLE_BYTES:
350
+ raise _CollectionBundleTooLarge
351
+ except _CollectionBundleTooLarge:
352
+ zip_path.unlink(missing_ok=True)
353
+ meta_path.unlink(missing_ok=True)
354
+ print(
355
+ f"[ResearchHarness Space collection] dropped oversized bundle for {run_root.name}; "
356
+ f"limit={FRONTEND_COLLECTION_MAX_BUNDLE_BYTES} bytes",
357
+ flush=True,
358
+ )
359
+ return None
360
+ except Exception:
361
+ zip_path.unlink(missing_ok=True)
362
+ meta_path.unlink(missing_ok=True)
363
+ print("[ResearchHarness Space collection] failed to create bundle", flush=True)
364
+ traceback.print_exc()
365
+ return None
366
+
367
+ meta = dict(manifest)
368
+ meta["bundle_bytes"] = zip_path.stat().st_size
369
+ meta_path.write_text(json.dumps(safe_jsonable(meta), ensure_ascii=False, indent=2), encoding="utf-8")
370
+ print(f"[ResearchHarness Space collection] queued bundle {zip_path.name}", flush=True)
371
+ return zip_path
372
+
373
+
374
+ def _record_collection_upload_error(collection_root: Path, error: str) -> None:
375
+ payload = {
376
+ "created_at_utc": _dt.datetime.utcnow().isoformat(timespec="seconds") + "Z",
377
+ "error": error,
378
+ }
379
+ (collection_root / "last_upload_error.json").write_text(
380
+ json.dumps(payload, ensure_ascii=False, indent=2),
381
+ encoding="utf-8",
382
+ )
383
+
384
+
385
+ def _create_dataset_pr_for_bundles(bundle_paths: list[Path]) -> str:
386
+ from huggingface_hub import CommitOperationAdd, HfApi
387
+
388
+ batch_id = f"batch_{_dt.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')}_{uuid4().hex[:8]}"
389
+ operations = []
390
+ for bundle_path in bundle_paths:
391
+ operations.append(
392
+ CommitOperationAdd(
393
+ path_in_repo=f"batches/{batch_id}/{bundle_path.name}",
394
+ path_or_fileobj=str(bundle_path),
395
+ )
396
+ )
397
+ sidecar = bundle_path.with_suffix(".json")
398
+ if sidecar.exists():
399
+ operations.append(
400
+ CommitOperationAdd(
401
+ path_in_repo=f"batches/{batch_id}/{sidecar.name}",
402
+ path_or_fileobj=str(sidecar),
403
+ )
404
+ )
405
+ info = HfApi(token=_collection_token()).create_commit(
406
+ repo_id=FRONTEND_COLLECTION_DATASET_REPO,
407
+ repo_type="dataset",
408
+ operations=operations,
409
+ commit_message=f"Add ResearchHarness traces {batch_id}",
410
+ commit_description="Automatically collected ResearchHarness Space trajectories.",
411
+ create_pr=True,
412
+ )
413
+ return str(getattr(info, "pr_url", "") or getattr(info, "commit_url", "") or info)
414
+
415
+
416
+ def _flush_collection_batches() -> None:
417
+ if not _collection_ready():
418
+ return
419
+ collection_root = _collection_root()
420
+ if collection_root is None:
421
+ return
422
+ with _COLLECTION_LOCK:
423
+ pending_dir = collection_root / "pending"
424
+ while True:
425
+ bundles = sorted(pending_dir.glob("*.zip"), key=lambda path: path.stat().st_mtime)
426
+ if len(bundles) < FRONTEND_COLLECTION_BATCH_SIZE:
427
+ return
428
+ selected = bundles[:FRONTEND_COLLECTION_BATCH_SIZE]
429
+ try:
430
+ pr_url = _create_dataset_pr_for_bundles(selected)
431
+ except Exception as exc:
432
+ _record_collection_upload_error(collection_root, str(exc))
433
+ print("[ResearchHarness Space collection] failed to create dataset PR", flush=True)
434
+ traceback.print_exc()
435
+ return
436
+ for bundle_path in selected:
437
+ bundle_path.unlink(missing_ok=True)
438
+ bundle_path.with_suffix(".json").unlink(missing_ok=True)
439
+ (collection_root / "last_upload_error.json").unlink(missing_ok=True)
440
+ print(
441
+ f"[ResearchHarness Space collection] created dataset PR for {len(selected)} bundles: {pr_url}",
442
+ flush=True,
443
+ )
444
+
445
+
446
+ def _collect_finished_managed_run(run_root_text: str, result: dict[str, Any]) -> None:
447
+ if not _collection_ready() or not run_root_text:
448
+ return
449
+ run_root = Path(run_root_text)
450
+ if not run_root.exists() or not run_root.is_dir():
451
+ return
452
+ bundle = _write_collection_bundle(run_root, result)
453
+ if bundle is None:
454
+ return
455
+ threading.Thread(target=_flush_collection_batches, daemon=True).start()
456
+
457
+
458
  class FrontendInteractiveAgent(MultiTurnReactAgent):
459
  def __init__(self, *, bridge: FrontendRunBridge, **kwargs: Any):
460
  super().__init__(**kwargs)
 
545
  initial_content_parts: list[dict[str, Any]],
546
  trace_dir: str | None = None,
547
  prior_messages: list[dict[str, Any]] | None = None,
548
+ managed_run_root: str = "",
549
  ) -> None:
550
  try:
551
  load_dotenv(PROJECT_ROOT / ".env")
 
575
  )
576
  bridge.conversation_messages = result.get("messages", [])
577
  bridge.conversation_workspace_root = str(workspace_root)
578
+ if managed_run_root:
579
+ _collect_finished_managed_run(managed_run_root, result)
580
  bridge.send(
581
  {
582
  "type": "run_finished",
 
767
  "initial_content_parts": image_parts,
768
  "trace_dir": effective_trace_dir,
769
  "prior_messages": prior_messages,
770
+ "managed_run_root": bridge.managed_run_root,
771
  },
772
  daemon=True,
773
  )
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  fastapi==0.115.6
 
2
  json5==0.14.0
3
  openai==2.3.0
4
  Pillow==11.3.0
 
1
  fastapi==0.115.6
2
+ huggingface_hub==1.2.3
3
  json5==0.14.0
4
  openai==2.3.0
5
  Pillow==11.3.0