Repository navigation
Expand file tree
/
Copy pathenvironment.py
More file actions
443 lines (368 loc) · 15.8 KB
/
Copy pathenvironment.py
File metadata and controls
443 lines (368 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""Workspace + input preparation for the multi-agent research pipeline.
This module owns all of the housekeeping that *used* to be scattered across
``agent_orchestration_engine.py`` Phase 0 (mkdir), Phase 1
(``_process_input_source``), and the head of Phase 2 (resume detection +
PDF→MD inlining):
* deciding where ``deepcode_lab`` lives (env > yaml > cwd default)
* normalising the user-supplied input string (``file://``, ``~``, URL
decoding, Windows backslash, relative→absolute)
* validating it (existence, file size, extension whitelist) so we fail
*before* the LLM bill starts
* detecting "user re-fed an existing paper directory" → resume mode
* allocating an isolated ``papers/<task_id>/`` directory using a UUID so
concurrent tasks cannot collide on the old ``max+1`` scheme
* re-pointing the ``filesystem`` MCP server at the resolved workspace
*and* ``cwd`` (the previous three entry-point patches all did this
inline; now exactly one place owns it)
The single public entry point is :func:`prepare_workflow_environment`.
Every helper is a private ``_xxx`` so the contract stays small.
"""
from __future__ import annotations
import os
import shutil
import uuid
from pathlib import Path
from typing import Any, Awaitable, Callable
from urllib.parse import unquote, urlparse
from loguru import logger as default_logger
from core.compat.runtime import get_runtime
from workflows.workflow_context import (
EXTENSION_TO_KIND,
InputKind,
TASK_KIND_PREFIX,
TASKS_DIRNAME,
TaskKind,
WorkflowContext,
resolve_workspace_root,
)
ProgressCallback = Callable[[int, str], Any]
"""Same shape as the legacy ``progress_callback(progress, message)`` hook."""
_DEFAULT_MAX_INPUT_MB = 100
"""Default upper bound on input file size; override via yaml ``workspace.max_input_mb``."""
_LOW_DISK_THRESHOLD_BYTES = 500 * 1024 * 1024
"""Warn (do not fail) if the workspace volume has less than 500 MB free."""
# ---------------------------------------------------------------------------
# public API
# ---------------------------------------------------------------------------
async def prepare_workflow_environment(
raw_input: str,
*,
enable_indexing: bool,
task_kind: TaskKind = "paper2code",
task_id: str | None = None,
progress_cb: ProgressCallback | None = None,
logger: Any | None = None,
workspace_root: Path | str | None = None,
) -> WorkflowContext:
"""Run all non-LLM workspace + input housekeeping in one place.
Returns a fully-populated :class:`WorkflowContext` ready for Phase 2.
Raises :class:`ValueError` (with a human-readable reason) if the input
is missing, oversized, or has a disallowed extension; caller should
catch it and mark the task failed without spending any LLM tokens.
The on-disk task directory is named
``deepcode_lab/tasks/<prefix>_<task_id>/`` where ``<prefix>`` is
derived from ``task_kind`` (``paper`` / ``chat`` / ``web`` …). Old
``deepcode_lab/papers/<id>/`` directories created by previous releases
are **not** auto-resumed; users who want to continue an old run need
to re-submit the input.
"""
log = logger or default_logger
_maybe_progress(progress_cb, 1, "🔧 Resolving workspace and validating input...")
yaml_root, max_input_mb = _load_workspace_config()
resolved_workspace_root = (
Path(workspace_root).expanduser().resolve()
if workspace_root is not None
else resolve_workspace_root(yaml_root)
)
normalized, kind = _normalize_input(raw_input)
_validate_input(normalized, kind, max_input_mb, log)
prefix = TASK_KIND_PREFIX[task_kind]
existing_dir, detected_kind, is_resume = _detect_resume(
normalized, resolved_workspace_root
)
if is_resume and existing_dir is not None:
# Resume preserves the existing directory name (and therefore its
# original modality) regardless of what the caller passed in. The
# alternative — silently relocating an in-progress task — would
# break MCP allowed-roots and on-disk references.
full_dirname = existing_dir.name
chosen_id = _strip_known_prefix(full_dirname, detected_kind)
if detected_kind is not None and detected_kind != task_kind:
log.info(
"Resume: caller asked for task_kind={} but existing task_dir is {} (kind={}); "
"honouring the on-disk kind.",
task_kind,
full_dirname,
detected_kind,
)
task_kind = detected_kind
prefix = TASK_KIND_PREFIX[task_kind]
task_dir = existing_dir
else:
chosen_id = (task_id or uuid.uuid4().hex[:8]).strip()
if not chosen_id:
chosen_id = uuid.uuid4().hex[:8]
task_dir = resolved_workspace_root / TASKS_DIRNAME / f"{prefix}_{chosen_id}"
_ensure_workspace(
resolved_workspace_root, task_dir, allow_existing=is_resume, logger=log
)
_register_workspace_for_filesystem_mcp(resolved_workspace_root, log)
paper_path: Path | None = None
if is_resume and kind != "url":
candidate = Path(normalized)
if candidate.is_file():
paper_path = candidate
log.info(
"🗂️ Workspace={} task_kind={} task_dir={} kind={} resume={}",
resolved_workspace_root,
task_kind,
task_dir.name,
kind,
is_resume,
)
# Hand the per-task log directory to the observability bus so any
# subsequent loguru call carrying this task_id (set by the entry
# layer via bind_task) is tee'd into <task_dir>/logs/system.jsonl.
try:
from core.observability import set_task_dir as _obs_set_task_dir
_obs_set_task_dir(chosen_id, task_dir)
except Exception as exc: # pragma: no cover - observability never fatal
log.debug("observability.set_task_dir failed: {}", exc)
# If a session is bound on the contextvar, persist the task → session
# link so the listing UI / CLI can show the new task immediately.
try:
from core.observability import current_session_id as _current_session_id
from core.sessions import get_default_store as _get_session_store
active_session = _current_session_id()
if active_session:
_get_session_store().attach_task(
active_session,
chosen_id,
task_kind=task_kind,
task_dir=str(task_dir),
status="running",
)
except Exception as exc: # pragma: no cover - never fatal
log.debug("session.attach_task failed: {}", exc)
_maybe_progress(progress_cb, 4, f"📁 Task workspace ready: {task_dir.name}")
return WorkflowContext(
task_id=chosen_id,
input_source=normalized,
input_kind=kind,
workspace_root=resolved_workspace_root,
task_dir=task_dir,
enable_indexing=enable_indexing,
task_kind=task_kind,
skip_research_analysis=is_resume,
paper_path=paper_path,
)
def _strip_known_prefix(dirname: str, detected_kind: TaskKind | None) -> str:
"""Return the bare task_id portion of a ``<prefix>_<id>`` directory name.
Falls back to the full name if no known prefix matches (e.g. user
manually named the directory).
"""
if detected_kind is not None:
prefix = TASK_KIND_PREFIX[detected_kind] + "_"
if dirname.startswith(prefix):
return dirname[len(prefix) :]
return dirname
# ---------------------------------------------------------------------------
# private helpers (one job each)
# ---------------------------------------------------------------------------
def _maybe_progress(cb: ProgressCallback | None, pct: int, msg: str) -> None:
"""Best-effort progress notification; never raises into the caller."""
if cb is None:
return
try:
result = cb(pct, msg)
# Accept both sync and awaitable callbacks; legacy code uses both.
if isinstance(result, Awaitable): # type: ignore[arg-type]
# Schedule but do not await - caller's event loop will pick it up.
# Fire-and-forget keeps prepare_workflow_environment cheap.
import asyncio
asyncio.ensure_future(result) # noqa: RUF006
except Exception as exc: # pragma: no cover - cosmetic
default_logger.debug("progress callback failed: {}", exc)
def _load_workspace_config() -> tuple[str | None, int]:
"""Read ``workspace.{root,maxInputMb}`` from the active deepcode_config.json."""
try:
runtime = get_runtime()
except Exception as exc: # pragma: no cover - defensive
default_logger.warning("Could not load DeepCode runtime config: {}", exc)
return None, _DEFAULT_MAX_INPUT_MB
workspace = runtime.config.workspace
cfg_root = str(workspace.root) if workspace.root else None
try:
max_mb = max(1, int(workspace.max_input_mb))
except (TypeError, ValueError):
default_logger.warning(
"Invalid workspace.maxInputMb={!r}; falling back to {}MB",
workspace.max_input_mb,
_DEFAULT_MAX_INPUT_MB,
)
max_mb = _DEFAULT_MAX_INPUT_MB
return cfg_root, max_mb
def _normalize_input(raw_input: str) -> tuple[str, InputKind]:
"""Return ``(normalized_path_or_url, detected_kind)``.
Normalisation:
* trim whitespace
* ``http(s)://`` → kind == "url" (returned verbatim, no further fs work)
* ``file://`` decoded to a real local path
* ``~`` expanded, relative paths resolved against ``cwd``
* Windows: forward slashes preserved as-is, but the resulting Path is
absolute and uses the platform separator after ``Path.resolve()``.
"""
if not isinstance(raw_input, str) or not raw_input.strip():
raise ValueError("input is empty")
text = raw_input.strip()
lower = text.lower()
if lower.startswith(("http://", "https://")):
return text, "url"
if lower.startswith("file://"):
parsed = urlparse(text)
local = unquote(parsed.path)
# On Windows, ``file:///C:/foo`` parses to ``/C:/foo`` -> strip the leading slash.
if os.name == "nt" and len(local) >= 3 and local[0] == "/" and local[2] == ":":
local = local[1:]
text = local
expanded = os.path.expanduser(text)
abs_path = Path(expanded).resolve()
suffix = abs_path.suffix.lower()
kind = EXTENSION_TO_KIND.get(suffix)
if kind is None:
raise ValueError(
f"input '{raw_input}': unsupported extension '{suffix or '(none)'}'. "
f"Allowed: {sorted(set(EXTENSION_TO_KIND))}"
)
return str(abs_path), kind
def _validate_input(normalized: str, kind: InputKind, max_mb: int, log: Any) -> None:
"""Cheap, deterministic checks before any LLM call."""
if kind == "url":
# We *could* HEAD the URL, but many origins (incl. arXiv) reject HEAD
# or rate-limit it; trying to verify here would create flaky failures.
# Phase 2's downloader is the right place to surface URL errors.
return
path = Path(normalized)
if not path.exists():
raise ValueError(f"input '{normalized}': file does not exist")
if not path.is_file():
raise ValueError(f"input '{normalized}': is not a regular file")
size_bytes = path.stat().st_size
size_mb = size_bytes / (1024 * 1024)
if size_mb > max_mb:
raise ValueError(
f"input '{normalized}': size {size_mb:.1f}MB exceeds limit {max_mb}MB "
f"(raise workspace.maxInputMb in deepcode_config.json to override)"
)
suffix = path.suffix.lower()
if EXTENSION_TO_KIND.get(suffix) != kind:
raise ValueError(
f"input '{normalized}': extension/kind mismatch ({suffix} vs {kind})"
)
log.debug("input validated: {} ({:.2f} MB, kind={})", path, size_mb, kind)
def _detect_resume(
normalized: str, workspace_root: Path
) -> tuple[Path | None, TaskKind | None, bool]:
"""Detect when the user re-fed a file already inside ``tasks/<prefix>_<id>/``.
Returns ``(existing_task_dir, detected_kind, True)`` on a hit, where
``detected_kind`` is inferred from the directory's prefix
(``paper_`` → ``"paper2code"`` etc.). Returns ``(None, None, False)``
otherwise. A resume reuses the existing ``task_id`` and skips Phase 2.
Old-style ``deepcode_lab/papers/<id>/`` paths are intentionally **not**
resumed — the user opted out of legacy migration, so they must
re-submit the input to get a fresh ``tasks/paper_<uuid>/`` directory.
"""
if normalized.startswith(("http://", "https://")):
return None, None, False
try:
candidate = Path(normalized).resolve()
except OSError:
return None, None, False
tasks_root = (workspace_root / TASKS_DIRNAME).resolve()
try:
rel = candidate.relative_to(tasks_root)
except ValueError:
return None, None, False
parts = rel.parts
if not parts:
return None, None, False
task_dir = tasks_root / parts[0]
if not task_dir.is_dir():
return None, None, False
detected_kind: TaskKind | None = None
for kind, prefix in TASK_KIND_PREFIX.items():
if parts[0].startswith(prefix + "_"):
detected_kind = kind
break
return task_dir, detected_kind, True
def _ensure_workspace(
workspace_root: Path,
task_dir: Path,
*,
allow_existing: bool,
logger: Any,
) -> None:
"""Create the workspace tree and fail loudly on permission/disk issues."""
workspace_root.mkdir(parents=True, exist_ok=True)
(workspace_root / TASKS_DIRNAME).mkdir(parents=True, exist_ok=True)
probe = workspace_root / ".deepcode_write_probe"
try:
probe.write_text("ok", encoding="utf-8")
except OSError as exc:
raise ValueError(
f"workspace '{workspace_root}' is not writable: {exc}"
) from exc
finally:
try:
probe.unlink(missing_ok=True)
except OSError:
pass
try:
free_bytes = shutil.disk_usage(workspace_root).free
if free_bytes < _LOW_DISK_THRESHOLD_BYTES:
logger.warning(
"Workspace '{}' has only {:.0f} MB free (< {:.0f} MB threshold)",
workspace_root,
free_bytes / (1024 * 1024),
_LOW_DISK_THRESHOLD_BYTES / (1024 * 1024),
)
except OSError:
# Some networked filesystems do not report free space; ignore.
pass
if allow_existing:
task_dir.mkdir(parents=True, exist_ok=True)
return
try:
task_dir.mkdir(parents=True, exist_ok=False)
except FileExistsError as exc:
raise ValueError(
f"task directory '{task_dir}' already exists; pick a different task_id"
) from exc
def _register_workspace_for_filesystem_mcp(workspace_root: Path, log: Any) -> None:
"""Make sure the ``filesystem`` MCP server is rooted at the workspace.
The DeepCode ``filesystem`` MCP server takes its allowed roots as
trailing positional ``args``. We keep the entries that already point
at the project tree (``.``) and append the resolved workspace + cwd
if either is missing. This is the single owner of that wiring;
legacy entry points used to do it inline.
"""
try:
runtime = get_runtime()
except Exception as exc: # pragma: no cover - defensive
log.warning("Could not register filesystem MCP root: {}", exc)
return
fs = runtime.config.mcp_servers.get("filesystem")
if fs is None:
log.debug("No 'filesystem' MCP server configured; skip allowed-dir sync")
return
cwd = os.getcwd()
wanted = [str(workspace_root), cwd]
existing = list(fs.args)
appended = False
for entry in wanted:
if entry not in existing:
existing.append(entry)
appended = True
if appended:
fs.args = existing
log.debug("filesystem MCP allowed-dirs updated: {}", existing)