File size: 28,725 Bytes
33039e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
diff --git a/src/pier/agents/factory.py b/src/pier/agents/factory.py
index 665fadd..503a45d 100644
--- a/src/pier/agents/factory.py
+++ b/src/pier/agents/factory.py
@@ -6,6 +6,7 @@ from pier.agents.installed.antigravity_sdk import AntigravitySDK
 from pier.agents.installed.claude_code import ClaudeCode
 from pier.agents.installed.codex import Codex
 from pier.agents.installed.cursor_cli import CursorCli
+from pier.agents.installed.dsh_minimal import DshMinimal
 from pier.agents.installed.gemini_cli import GeminiCli
 from pier.agents.installed.mini_swe_agent import MiniSweAgent
 from pier.agents.installed.opencode import OpenCode
@@ -24,6 +25,7 @@ class AgentFactory:
         ClaudeCode,
         Codex,
         CursorCli,
+        DshMinimal,
         GeminiCli,
         MiniSweAgent,
         OpenCode,
diff --git a/src/pier/agents/installed/base.py b/src/pier/agents/installed/base.py
index 16f6a84..1fd1050 100644
--- a/src/pier/agents/installed/base.py
+++ b/src/pier/agents/installed/base.py
@@ -15,6 +15,18 @@ from pier.utils.env import parse_bool_env_value
 from pier.utils.templating import render_prompt_template
 
 
+RUNTIME_CONSTRAINTS = (
+    "\n## Runtime constraints\n"
+    "- Work in `/app`; do not modify files under `/tests`.\n"
+    "- No network or mirror access; use only dependencies already in the image.\n"
+)
+
+
+def with_runtime_constraints(instruction: str) -> str:
+    """Append the sandbox constraints to a task instruction."""
+    return instruction.rstrip("\n") + "\n" + RUNTIME_CONSTRAINTS
+
+
 class NonZeroAgentExitCodeError(RuntimeError):
     """Raised when the agent process exits with a non-zero exit code."""
 
@@ -394,12 +406,14 @@ class BaseInstalledAgent(BaseAgent, ABC):
         return instruction
 
     @abstractmethod
-    def install_spec(self) -> AgentInstallSpec:
-        """Declarative install steps executed at setup and inlined into Dockerfile builds."""
+    def install_spec(self) -> AgentInstallSpec | None:
+        """Declarative install steps executed at setup and inlined into Dockerfile
+        builds, or ``None`` for an agent already present in the environment."""
 
     async def install(self, environment: BaseEnvironment) -> None:
         """Run each step from :meth:`install_spec` with matching privilege."""
-        for step in self.install_spec().steps:
+        spec = self.install_spec()
+        for step in spec.steps if spec is not None else ():
             if step.user == "root":
                 await self.exec_as_root(environment, command=step.run, env=step.env)
             else:
diff --git a/src/pier/agents/installed/dsh_minimal.py b/src/pier/agents/installed/dsh_minimal.py
new file mode 100644
index 0000000..c84a1b1
--- /dev/null
+++ b/src/pier/agents/installed/dsh_minimal.py
@@ -0,0 +1,131 @@
+import shlex
+from pathlib import Path
+from typing import Any, override
+
+from pier.agents.installed.base import (
+    BaseInstalledAgent,
+    with_prompt_template,
+    with_runtime_constraints,
+)
+from pier.agents.network import allowlist_from_urls
+from pier.environments.base import BaseEnvironment
+from pier.models.agent.context import AgentContext
+from pier.models.agent.name import AgentName
+from pier.models.agent.network import NetworkAllowlist
+from pier.models.trajectories import Trajectory
+from pier.utils.trajectory_metrics import populate_context_from_final_metrics
+
+DIST = "/opt/dsh-minimal"
+DEFAULT_MODEL = "deepseek-flash"
+DEFAULT_BASE_URL = "https://api.deepseek.com"
+REASONING_EFFORTS = ("low", "high", "max")
+
+
+class DshMinimal(BaseInstalledAgent):
+    """DeepSeek Harness `sdk-minimal` profile driven through its Python SDK.
+
+    The SDK and its bundled runtime executable come from a `pip install --target`
+    tree bind-mounted read-only at ``DIST``, so no trial installs anything.
+    """
+
+    SUPPORTS_ATIF = True
+    _TRAJECTORY = "trajectory.json"
+    # The distribution mount is read-only, so the runner lands beside it.
+    _RUNNER = "/tmp/dsh-minimal-runner.py"
+
+    def __init__(
+        self, *args: Any, reasoning_effort: str = "max", **kwargs: Any
+    ) -> None:
+        if reasoning_effort not in REASONING_EFFORTS:
+            raise ValueError(
+                f"reasoning_effort must be one of {REASONING_EFFORTS}, "
+                f"got {reasoning_effort!r}"
+            )
+        self._reasoning_effort = reasoning_effort
+        kwargs["model_name"] = kwargs.get("model_name") or DEFAULT_MODEL
+        super().__init__(*args, **kwargs)
+
+    @staticmethod
+    @override
+    def name() -> str:
+        return AgentName.DSH_MINIMAL.value
+
+    @override
+    def install_spec(self) -> None:
+        """The distribution is bind-mounted, so no image layer is needed."""
+        return None
+
+    @override
+    def get_version_command(self) -> str:
+        return f"sed -n 's/^Version: //p' {DIST}/deepseek_harness_sdk-*.dist-info/METADATA"
+
+    @override
+    async def setup(self, environment: BaseEnvironment) -> None:
+        await super().setup(environment)
+        runner = Path(__file__).with_name("dsh_minimal_runner.py")
+        await environment.upload_file(runner, self._RUNNER)
+        await self.exec_as_root(environment, f"chmod a+r {self._RUNNER}")
+
+    def _base_url(self) -> str:
+        return self._get_env("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL
+
+    @override
+    def network_allowlist(self) -> NetworkAllowlist:
+        return allowlist_from_urls([self._base_url()])
+
+    @override
+    def populate_context_post_run(self, context: AgentContext) -> None:
+        path = self.logs_dir / self._TRAJECTORY
+        if not path.exists():
+            self.logger.debug("No dsh-minimal trajectory found at %s", path)
+            return
+        try:
+            trajectory = Trajectory.model_validate_json(path.read_text())
+        except (OSError, ValueError):
+            self.logger.exception("Failed to parse dsh-minimal trajectory")
+            return
+        if trajectory.final_metrics is not None:
+            populate_context_from_final_metrics(context, trajectory.final_metrics)
+        context.n_agent_steps = sum(step.source == "agent" for step in trajectory.steps)
+
+    @override
+    @with_prompt_template
+    async def run(
+        self,
+        instruction: str,
+        environment: BaseEnvironment,
+        context: AgentContext,
+    ) -> None:
+        api_key = self._get_env("DEEPSEEK_API_KEY")
+        if not api_key:
+            raise ValueError("DEEPSEEK_API_KEY environment variable must be set")
+
+        instruction = with_runtime_constraints(instruction)
+        agent_dir = environment.env_paths.agent_dir.as_posix()
+        env = self.build_process_env(
+            {
+                "DEEPSEEK_API_KEY": api_key,
+                "DEEPSEEK_BASE_URL": self._base_url(),
+                # The Node runtime reaches the model only through Pier's egress
+                # proxy, and its fetch ignores the proxy variables without this.
+                "NODE_USE_ENV_PROXY": "1",
+                "PYTHONPATH": DIST,
+                "DSH_MODEL": self._parsed_model_name,
+                "DSH_REASONING_EFFORT": self._reasoning_effort,
+                # Required, and kept off the /logs bind mount: it materializes many
+                # files the host cannot read anyway. `trajectory.json` is the record.
+                "DSH_HOME": "/tmp/dsh-home",
+                "SESSION_ID": environment.session_id,
+            }
+        )
+
+        await self.exec_as_agent(
+            environment,
+            command=(
+                f"python3 {self._RUNNER} "
+                f"--instruction {shlex.quote(instruction)} "
+                f"--trajectory-path {agent_dir}/{self._TRAJECTORY} "
+                f"2>&1 </dev/null | stdbuf -oL tee {agent_dir}/dsh-minimal.txt"
+            ),
+            env=env,
+        )
diff --git a/src/pier/agents/installed/dsh_minimal_runner.py b/src/pier/agents/installed/dsh_minimal_runner.py
new file mode 100644
index 0000000..8b69d7d
--- /dev/null
+++ b/src/pier/agents/installed/dsh_minimal_runner.py
@@ -0,0 +1,307 @@
+"""Run the DeepSeek Harness `sdk-minimal` profile and persist its stream as ATIF v1.7."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import traceback
+from datetime import datetime, timezone
+from importlib.metadata import PackageNotFoundError, version
+from pathlib import Path
+from typing import Any
+
+from deepseek_harness import DeepSeekHarness
+from deepseek_harness.models import Notification
+
+PROVIDER = "deepseek-official"
+
+
+def _iso(epoch_ms: Any) -> str | None:
+    if not isinstance(epoch_ms, (int, float)):
+        return None
+    return datetime.fromtimestamp(epoch_ms / 1000, tz=timezone.utc).isoformat()
+
+
+def _text(blocks: Any, kind: str) -> str:
+    if not isinstance(blocks, list):
+        return ""
+    return "".join(
+        str(block.get("text") or "")
+        for block in blocks
+        if isinstance(block, dict) and block.get("type") == kind
+    )
+
+
+def _flatten(blocks: Any) -> str:
+    if isinstance(blocks, str):
+        return blocks
+    if not isinstance(blocks, list):
+        return json.dumps(blocks, ensure_ascii=False)
+    return "".join(
+        str(block.get("text") or "")
+        if isinstance(block, dict) and block.get("type") == "text"
+        else json.dumps(block, ensure_ascii=False)
+        for block in blocks
+    )
+
+
+def _arguments(raw: Any) -> dict[str, Any]:
+    """ATIF wants an object; the wire carries the model's raw argument string."""
+    if isinstance(raw, dict):
+        return raw
+    if isinstance(raw, str):
+        try:
+            parsed = json.loads(raw)
+        except json.JSONDecodeError:
+            return {"_unparsed_arguments": raw}
+        return parsed if isinstance(parsed, dict) else {"_arguments": parsed}
+    return {}
+
+
+def _metrics(usage: dict[str, Any]) -> dict[str, Any]:
+    """The adapter reports disjoint counts, so the cache legs rejoin prompt tokens."""
+    cache_read = usage.get("cacheReadTokens") or 0
+    cache_write = usage.get("cacheWriteTokens") or 0
+    metrics = {
+        "prompt_tokens": (usage.get("inputTokens") or 0) + cache_read + cache_write,
+        "completion_tokens": usage.get("outputTokens") or 0,
+        "cached_tokens": cache_read,
+    }
+    if usage.get("reasoningTokens") is not None:
+        metrics["extra"] = {"reasoning_tokens": usage["reasoningTokens"]}
+    return metrics
+
+
+class Collector:
+    """Fold root-session events into one ATIF step per model call."""
+
+    def __init__(self, instruction: str, model: str, effort: str, session: str) -> None:
+        self.model = model
+        self.effort = effort
+        self.session = session
+        self.steps: list[dict[str, Any]] = [
+            {
+                "step_id": 1,
+                "timestamp": datetime.now(tz=timezone.utc).isoformat(),
+                "source": "user",
+                "message": instruction,
+            }
+        ]
+        # (turn, step) identifies one model call; callId maps a later `tool/result`
+        # back to the step that issued it, which is never the step it arrives in.
+        self._by_call: dict[tuple[int, int], dict[str, Any]] = {}
+        self._by_call_id: dict[str, dict[str, Any]] = {}
+        self.turn_end_reasons: list[dict[str, Any]] = []
+        self.llm_retries = 0
+
+    def _step(self, turn: Any, step: Any, timestamp: str | None) -> dict[str, Any]:
+        key = (int(turn or 0), int(step or 0))
+        if key not in self._by_call:
+            created = {
+                "step_id": len(self.steps) + 1,
+                "timestamp": timestamp,
+                "source": "agent",
+                "message": "",
+                "model_name": self.model,
+                "reasoning_effort": self.effort,
+                "llm_call_count": 1,
+            }
+            self.steps.append(created)
+            self._by_call[key] = created
+        return self._by_call[key]
+
+    def _tool_call(self, step: dict[str, Any], call_id: Any, name: Any, raw: Any) -> None:
+        if not isinstance(call_id, str) or not call_id:
+            return
+        calls = step.setdefault("tool_calls", [])
+        entry = {
+            "tool_call_id": call_id,
+            "function_name": str(name),
+            "arguments": _arguments(raw),
+        }
+        for index, existing in enumerate(calls):
+            if existing["tool_call_id"] == call_id:
+                calls[index] = entry
+                break
+        else:
+            calls.append(entry)
+        self._by_call_id[call_id] = step
+
+    def record(self, event: dict[str, Any]) -> None:
+        kind = event.get("type")
+        data = event.get("data") if isinstance(event.get("data"), dict) else {}
+        timestamp = _iso(event.get("time"))
+
+        if kind == "assistant/message":
+            step = self._step(data.get("turn"), data.get("step"), timestamp)
+            message = data.get("message") if isinstance(data.get("message"), dict) else {}
+            content = message.get("content")
+            step["message"] = _text(content, "text")
+            if reasoning := _text(content, "reasoning"):
+                step["reasoning_content"] = reasoning
+            source = message.get("source")
+            if isinstance(source, dict) and isinstance(source.get("model"), str):
+                step["model_name"] = source["model"]
+            if isinstance(data.get("usage"), dict):
+                step["metrics"] = _metrics(data["usage"])
+            if data.get("interrupted"):
+                step.setdefault("extra", {})["interrupted"] = True
+            for block in content if isinstance(content, list) else []:
+                if isinstance(block, dict) and block.get("type") == "tool-call":
+                    self._tool_call(
+                        step, block.get("id"), block.get("name"), block.get("arguments")
+                    )
+        elif kind == "tool/call":
+            step = self._step(data.get("turn"), data.get("step"), timestamp)
+            self._tool_call(
+                step, data.get("callId"), data.get("name"), data.get("arguments")
+            )
+        elif kind == "tool/result":
+            self._result(data)
+        elif kind == "turn/end":
+            reason = data.get("reason")
+            self.turn_end_reasons.append(reason if isinstance(reason, dict) else {})
+        elif kind == "llm/retry":
+            self.llm_retries += 1
+
+    def _result(self, data: dict[str, Any]) -> None:
+        message = data.get("message") if isinstance(data.get("message"), dict) else {}
+        for block in message.get("content") or []:
+            if not isinstance(block, dict) or block.get("type") != "tool-result":
+                continue
+            step = self._by_call_id.get(block.get("toolCallId"))
+            if step is None:
+                continue
+            entry: dict[str, Any] = {
+                "source_call_id": block["toolCallId"],
+                "content": _flatten(block.get("content")),
+            }
+            if block.get("isError"):
+                entry["extra"] = {"is_error": True, "error": data.get("error")}
+            results = step.setdefault("observation", {"results": []})["results"]
+            for index, existing in enumerate(results):
+                if existing["source_call_id"] == entry["source_call_id"]:
+                    results[index] = entry
+                    break
+            else:
+                results.append(entry)
+
+    def trajectory(self, finish_reason: str | None, failure: str | None) -> dict[str, Any]:
+        prompt = completion = cached = peak = 0
+        for step in self.steps:
+            metrics = step.get("metrics")
+            if not isinstance(metrics, dict):
+                continue
+            prompt += metrics["prompt_tokens"]
+            completion += metrics["completion_tokens"]
+            cached += metrics["cached_tokens"]
+            peak = max(peak, metrics["prompt_tokens"])
+        extra = {
+            "finish_reason": finish_reason,
+            "turn_end_reasons": self.turn_end_reasons,
+            "llm_retry_count": self.llm_retries,
+        }
+        if failure is not None:
+            extra["failure"] = failure
+        return {
+            "schema_version": "ATIF-v1.7",
+            "session_id": self.session,
+            "agent": {"name": "dsh-minimal", "version": _version(), "model_name": self.model},
+            "steps": self.steps,
+            "final_metrics": {
+                "total_prompt_tokens": prompt,
+                "total_completion_tokens": completion,
+                "total_cached_tokens": cached,
+                "total_steps": len(self.steps),
+                # The sdk-minimal profile has no compaction, so no summary step
+                # can replace a transcript prefix.
+                "extra": {"peak_context_tokens": peak, "summarization_count": 0},
+            },
+            "extra": extra,
+        }
+
+
+def _version() -> str:
+    try:
+        return version("deepseek-harness-sdk")
+    except PackageNotFoundError:
+        return "unknown"
+
+
+def _write(path: Path, value: Any) -> None:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    temporary = path.with_suffix(f"{path.suffix}.tmp")
+    temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n")
+    temporary.replace(path)
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--instruction", required=True)
+    parser.add_argument("--trajectory-path", required=True)
+    args = parser.parse_args()
+
+    # Task images can leave the agent user on a 077 umask; the session log and
+    # trajectory have to stay readable to the host user that collects /logs.
+    os.umask(0o022)
+
+    model = os.environ["DSH_MODEL"]
+    effort = os.environ.get("DSH_REASONING_EFFORT", "max")
+    session = os.environ.get("SESSION_ID") or "pier-session"
+    path = Path(args.trajectory_path)
+    collector = Collector(args.instruction, model, effort, session)
+    state: dict[str, Any] = {"finish_reason": None, "failure": None}
+
+    def checkpoint() -> None:
+        _write(path, collector.trajectory(state["finish_reason"], state["failure"]))
+
+    def on_notification(notification: Notification) -> None:
+        payload = notification.payload
+        event = payload.get("event") if isinstance(payload, dict) else None
+        if (
+            notification.method != "session.event"
+            or not isinstance(event, dict)
+            # Token deltas repeat what their `assistant/message` already carries.
+            or event.get("type") == "assistant/chunk"
+            or payload.get("sessionId") != session
+        ):
+            return
+        collector.record(event)
+        checkpoint()
+
+    checkpoint()
+    print(f"dsh-minimal: model={model} effort={effort} session={session}")
+    try:
+        with DeepSeekHarness(
+            profile="sdk-minimal",
+            provider=PROVIDER,
+            model=model,
+            reasoning_effort=effort,
+            cwd=os.getcwd(),
+            dsh_home=os.environ["DSH_HOME"],
+        ) as harness:
+            result = harness.run(
+                args.instruction, session_id=session, on_notification=on_notification
+            )
+        state["finish_reason"] = result.finish_reason
+        print(f"dsh-minimal: finish_reason={result.finish_reason}")
+        print(f"dsh-minimal: final_response={result.final_response}")
+    except Exception as error:  # noqa: BLE001 - the trajectory must survive any failure
+        state["failure"] = f"{type(error).__name__}: {error}"
+        traceback.print_exc()
+    finally:
+        checkpoint()
+
+    # `max-tokens` is a bounded model outcome the verifier can still grade; anything
+    # else non-terminal means the harness never produced a usable turn.
+    if state["failure"] is not None or state["finish_reason"] not in (
+        "completed",
+        "max-tokens",
+    ):
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/src/pier/agents/installed/mini_swe_agent.py b/src/pier/agents/installed/mini_swe_agent.py
index 75d25b6..d283f66 100644
--- a/src/pier/agents/installed/mini_swe_agent.py
+++ b/src/pier/agents/installed/mini_swe_agent.py
@@ -11,6 +11,7 @@ from pier.agents.installed.base import (
     BaseInstalledAgent,
     CliFlag,
     with_prompt_template,
+    with_runtime_constraints,
 )
 from pier.agents.network import allowlist_from_urls, collect_url_values
 from pier.agents.utils import get_api_key_var_names_from_model_name
@@ -821,7 +822,7 @@ mini-swe-agent --help
     async def run(
         self, instruction: str, environment: BaseEnvironment, context: AgentContext
     ) -> None:
-        augmented_instruction = instruction
+        augmented_instruction = with_runtime_constraints(instruction)
         if self.mcp_servers:
             mcp_info = "\n\nMCP Servers:\nThe following MCP servers are available for this task.\n"
             for s in self.mcp_servers:
diff --git a/src/pier/environments/docker/__init__.py b/src/pier/environments/docker/__init__.py
index 4bb8f11..04a8c6e 100644
--- a/src/pier/environments/docker/__init__.py
+++ b/src/pier/environments/docker/__init__.py
@@ -25,6 +25,9 @@ def write_resources_compose_file(
     *,
     cpu_request: int | None = None,
     cpu_limit: int | None = None,
+    environment: dict[str, str] | None = None,
+    sysctls: dict[str, str] | None = None,
+    volumes: list[str] | None = None,
     memory_request_mb: int | None = None,
     memory_limit_mb: int | None = None,
 ) -> Path:
@@ -46,7 +49,13 @@ def write_resources_compose_file(
     if reservations:
         resources["reservations"] = reservations
 
-    main = {"deploy": {"resources": resources}} if resources else {}
+    main: dict[str, object] = {"deploy": {"resources": resources}} if resources else {}
+    if environment:
+        main["environment"] = dict(environment)
+    if sysctls:
+        main["sysctls"] = dict(sysctls)
+    if volumes:
+        main["volumes"] = list(volumes)
     compose = {"services": {"main": main}}
     path.parent.mkdir(parents=True, exist_ok=True)
     path.write_text(json.dumps(compose, indent=2))
diff --git a/src/pier/environments/docker/docker.py b/src/pier/environments/docker/docker.py
index 2ed4e92..bc671be 100644
--- a/src/pier/environments/docker/docker.py
+++ b/src/pier/environments/docker/docker.py
@@ -31,6 +31,11 @@ from pier.environments.docker import (
     write_mounts_compose_file,
     write_resources_compose_file,
 )
+from pier.environments.docker.parallelism import (
+    CPU_CLAMP_PATH,
+    cpu_clamp_source,
+    parallelism_env,
+)
 from pier.models.environment_type import EnvironmentType
 from pier.models.task.config import EnvironmentConfig, TaskOS
 from pier.models.trial.config import ResourceMode, ServiceVolumeConfig
@@ -102,6 +107,11 @@ class DockerEnvironment(BaseEnvironment):
 
     _DOCKER_COMPOSE_WINDOWS_KEEPALIVE_PATH = COMPOSE_WINDOWS_KEEPALIVE_PATH
 
+    # Docker leaves IPv6 off in the container netns, so loopback has no ::1 and
+    # suites that bind it skip where a real Linux host passes. These environments
+    # always get their own netns, which is what net.* sysctls require.
+    _LINUX_SYSCTLS = {"net.ipv6.conf.all.disable_ipv6": "0"}
+
     # Class-level lock per image name to prevent parallel builds of the same image.
     _image_build_locks: dict[str, asyncio.Lock] = {}
 
@@ -160,6 +170,7 @@ class DockerEnvironment(BaseEnvironment):
         task_env_config: EnvironmentConfig,
         keep_containers: bool = False,
         mounts_json: list[ServiceVolumeConfig] | None = None,
+        mounts_override: list[ServiceVolumeConfig] | None = None,
         *args,
         **kwargs,
     ):
@@ -193,8 +204,13 @@ class DockerEnvironment(BaseEnvironment):
             self._windows_container_name: str | None = None
             self._platform = UnixOps(self)
 
+        # Configured mounts are additive so the default /logs binds survive and
+        # agent logs and artifacts stay host-visible. A separate verifier
+        # environment must not share those directories, so it overrides the set.
         self._mounts_json = (
-            mounts_json if mounts_json is not None else self._default_log_mounts()
+            [*self._default_log_mounts(), *(mounts_json or [])]
+            if mounts_override is None
+            else mounts_override
         )
         self._mounts_compose_path: Path | None = None
         self._resources_compose_temp_dir: tempfile.TemporaryDirectory | None = None
@@ -427,12 +443,16 @@ class DockerEnvironment(BaseEnvironment):
             Path(self._resources_compose_temp_dir.name)
             / f"{self.session_id}-{RESOURCES_COMPOSE_NAME}"
         )
+        cpu_limit = self._resource_limit_value("cpu", auto_mode=ResourceMode.LIMIT)
         return write_resources_compose_file(
             path,
+            environment=parallelism_env(cpu_limit),
+            volumes=self._write_cpu_clamp(path.parent, cpu_limit),
+            sysctls=None if self._is_windows_container else self._LINUX_SYSCTLS,
             cpu_request=self._resource_request_value(
                 "cpu", auto_mode=ResourceMode.LIMIT
             ),
-            cpu_limit=self._resource_limit_value("cpu", auto_mode=ResourceMode.LIMIT),
+            cpu_limit=cpu_limit,
             memory_request_mb=self._resource_request_value(
                 "memory", auto_mode=ResourceMode.LIMIT
             ),
@@ -441,6 +461,15 @@ class DockerEnvironment(BaseEnvironment):
             ),
         )
 
+    def _write_cpu_clamp(self, directory: Path, cpu_limit: int | None) -> list[str]:
+        """Mount the preload that `parallelism_env` points NODE_OPTIONS at."""
+        if not cpu_limit or self._is_windows_container:
+            return []
+        source = directory / "pier-node-cpu-clamp.js"
+        source.write_text(cpu_clamp_source(cpu_limit))
+        source.chmod(0o644)
+        return [f"{source}:{CPU_CLAMP_PATH}:ro"]
+
     def _cleanup_resources_compose_file(self) -> None:
         if self._resources_compose_temp_dir is None:
             return
diff --git a/src/pier/environments/docker/parallelism.py b/src/pier/environments/docker/parallelism.py
new file mode 100644
index 0000000..b21ae7c
--- /dev/null
+++ b/src/pier/environments/docker/parallelism.py
@@ -0,0 +1,34 @@
+"""Tell test runners how many CPUs the container actually gets.
+
+Docker's ``--cpus`` is a bandwidth quota, so ``nproc`` still reports every host
+core and runner worker pools oversubscribe the container.
+"""
+
+from __future__ import annotations
+
+CPU_CLAMP_PATH = "/opt/pier-node-cpu-clamp.js"
+
+
+def cpu_clamp_source(cpus: int) -> str:
+    """A ``node --require`` preload; the Node runners take no cap from the environment."""
+    return (
+        "const os = require('node:os')\n"
+        f"const limit = {cpus}\n"
+        "const cpus = os.cpus\n"
+        "os.cpus = () => cpus.call(os).slice(0, limit)\n"
+        "os.availableParallelism = () => limit\n"
+    )
+
+
+def parallelism_env(cpus: int | None) -> dict[str, str]:
+    """Worker-count caps for the test runners, derived from the CPU limit."""
+    if not cpus or cpus < 1:
+        return {}
+    n = str(cpus)
+    return {
+        "GOMAXPROCS": n,
+        "CARGO_BUILD_JOBS": n,
+        "NEXTEST_TEST_THREADS": n,
+        "PYTEST_XDIST_AUTO_NUM_WORKERS": n,
+        "NODE_OPTIONS": f"--require {CPU_CLAMP_PATH}",
+    }
diff --git a/src/pier/models/agent/name.py b/src/pier/models/agent/name.py
index d84516a..41ac147 100644
--- a/src/pier/models/agent/name.py
+++ b/src/pier/models/agent/name.py
@@ -8,6 +8,7 @@ class AgentName(str, Enum):
     ANTIGRAVITY_SDK = "antigravity-sdk"
     CODEX = "codex"
     CURSOR_CLI = "cursor-cli"
+    DSH_MINIMAL = "dsh-minimal"
     GEMINI_CLI = "gemini-cli"
     MINI_SWE_AGENT = "mini-swe-agent"
     SWE_AGENT = "swe-agent"
diff --git a/src/pier/trial/trial.py b/src/pier/trial/trial.py
index fd5d4a2..126f0fa 100644
--- a/src/pier/trial/trial.py
+++ b/src/pier/trial/trial.py
@@ -402,7 +402,7 @@ class Trial:
             trial_paths=self._trial_paths,
             task_env_config=env_config,
             logger=self._logger,
-            mounts_json=self._verifier_env_mounts(env_config),
+            mounts_override=self._verifier_env_mounts(env_config),
             agent_install_spec=None,
             network_allowlist=None,
             default_user=(