tempergraph 0.7.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"""The session launcher: the one place a model session's process is started (EXI-B2, EXI-B20, EXI-B21, EXI-B22, EXI-B23, EXI-B15, SEC-B7).
|
|
2
|
+
|
|
3
|
+
It owns what the engine must not delegate to a CLI: list argv, the prompt on stdin written right after
|
|
4
|
+
spawn (EXI-B2), the wall-clock timeout (EXI-B3), the idle watchdog (EXI-B4), the process tree's lifetime
|
|
5
|
+
(EXI-B5), the stop contract (EXI-B15), the prompt-gap record (EXI-B13), the caller variables (PRV-B5, PRV-B18, PRV-B17, PRV-B14, PRV-B13, PRV-B19, PRV-B15)
|
|
6
|
+
and the raw stream files under the session folder (LOS-B7, LOS-B8, LOS-B9). It also runs the executors' model-free
|
|
7
|
+
probes and the host-speed timing (EXI-B14), so every executor launch stays at this one site.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import queue
|
|
16
|
+
import signal
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
from collections.abc import Callable, Mapping
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import IO, Any, Literal
|
|
25
|
+
|
|
26
|
+
from tempergraph.contracts import Event, EventSink
|
|
27
|
+
|
|
28
|
+
CALLER_VARS = ("TEMPERGRAPH_SUPERVISOR_TOKEN", "TEMPERGRAPH_CALLER", "TEMPERGRAPH_CALLER_APP")
|
|
29
|
+
SESSION_KEY_VAR = "TEMPERGRAPH_SESSION_KEY"
|
|
30
|
+
IDLE_FLOOR_TOOL_S = 900
|
|
31
|
+
GRACE_S = 10.0
|
|
32
|
+
PROMPT_GAP_WARN_S = 1.0
|
|
33
|
+
PROMPT_WINDOW_S = 30.0 # the prompt must be taken within this window, or the session is stopped
|
|
34
|
+
HOST_SPEED_FLOOR_S = 3.0
|
|
35
|
+
HOST_WALK_LIMIT = 2000
|
|
36
|
+
RELEASE_AFTER_EXIT_S = 2.0
|
|
37
|
+
|
|
38
|
+
KillReason = Literal["timeout", "idle", "signal", "stop"]
|
|
39
|
+
Clock = Callable[[], float]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, kw_only=True)
|
|
43
|
+
class LaunchSpec:
|
|
44
|
+
argv: list[str]
|
|
45
|
+
stdin_payload: bytes
|
|
46
|
+
workdir: Path
|
|
47
|
+
timeout_s: int
|
|
48
|
+
session_key: str
|
|
49
|
+
idle_s: int | None = None
|
|
50
|
+
idle_floor_tool_s: int = IDLE_FLOOR_TOOL_S
|
|
51
|
+
env_overlay: Mapping[str, str] = field(default_factory=dict)
|
|
52
|
+
env_drop: tuple[str, ...] = () # names beginning with one of these are left out of the inherited environment
|
|
53
|
+
env_keep: tuple[str, ...] = () # exact names that the drop prefixes never remove
|
|
54
|
+
session_dir: Path | None = None
|
|
55
|
+
grace_s: float = GRACE_S
|
|
56
|
+
prompt_window_s: float = PROMPT_WINDOW_S
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(kw_only=True)
|
|
60
|
+
class RawOutcome:
|
|
61
|
+
exit_code: int | None = None
|
|
62
|
+
killed: bool = False # the tree was killed after the grace period
|
|
63
|
+
stop_reason: KillReason | None = None # why a stop was sent, killed or not
|
|
64
|
+
spawn_error: OSError | None = None
|
|
65
|
+
broken_pipe: bool = False
|
|
66
|
+
prompt_delivered: bool = False
|
|
67
|
+
prompt_timeout: bool = False # the CLI did not take the prompt within its window
|
|
68
|
+
prompt_gap_s: float | None = None
|
|
69
|
+
lines: int = 0
|
|
70
|
+
line_times: list[float] = field(default_factory=list)
|
|
71
|
+
events: list[Event] = field(default_factory=list)
|
|
72
|
+
unparsable: int = 0
|
|
73
|
+
duration_s: float = 0.0
|
|
74
|
+
warnings: list[str] = field(default_factory=list)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class StopRequest:
|
|
78
|
+
"""A drain or signal request the launcher polls; set from a signal handler or another thread."""
|
|
79
|
+
|
|
80
|
+
def __init__(self) -> None:
|
|
81
|
+
self._event = threading.Event()
|
|
82
|
+
self.reason: KillReason = "stop"
|
|
83
|
+
|
|
84
|
+
def request(self, reason: KillReason = "stop") -> None:
|
|
85
|
+
self.reason = reason
|
|
86
|
+
self._event.set()
|
|
87
|
+
|
|
88
|
+
def is_set(self) -> bool:
|
|
89
|
+
return self._event.is_set()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def idle_action(age_s: float, tool_open: bool, idle_s: int | None, floor_s: int = IDLE_FLOOR_TOOL_S
|
|
93
|
+
) -> Literal["wait", "kill"]:
|
|
94
|
+
"""EXI-B4: the watchdog's decision for one tick."""
|
|
95
|
+
if idle_s is None:
|
|
96
|
+
return "wait"
|
|
97
|
+
limit = max(idle_s, floor_s) if tool_open else idle_s
|
|
98
|
+
return "kill" if age_s > limit else "wait"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def session_env(overlay: Mapping[str, str], session_key: str, base: Mapping[str, str] | None = None,
|
|
102
|
+
drop: tuple[str, ...] = (), keep: tuple[str, ...] = ()) -> dict[str, str]:
|
|
103
|
+
env = {k: v for k, v in (os.environ if base is None else base).items()
|
|
104
|
+
if k not in CALLER_VARS and (k in keep or not (drop and k.startswith(drop)))}
|
|
105
|
+
env.update(overlay) # laid after the filter, so the engine's own names always arrive
|
|
106
|
+
env[SESSION_KEY_VAR] = session_key
|
|
107
|
+
return env
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _popen_kwargs() -> dict[str, object]:
|
|
111
|
+
if os.name == "posix":
|
|
112
|
+
return {"start_new_session": True}
|
|
113
|
+
return {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _signal_group(proc: subprocess.Popen[bytes], hard: bool) -> None:
|
|
117
|
+
if os.name == "posix":
|
|
118
|
+
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
119
|
+
os.killpg(proc.pid, signal.SIGKILL if hard else signal.SIGTERM)
|
|
120
|
+
elif hard: # Windows: end the whole tree (EXI-B5); the job-object form is the next step there
|
|
121
|
+
with contextlib.suppress(OSError):
|
|
122
|
+
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True, check=False)
|
|
123
|
+
else:
|
|
124
|
+
with contextlib.suppress(OSError, ValueError):
|
|
125
|
+
proc.send_signal(getattr(signal, "CTRL_BREAK_EVENT", signal.SIGTERM))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _open_raw(session_dir: Path | None) -> tuple[IO[bytes] | None, IO[bytes] | int]:
|
|
129
|
+
if session_dir is None:
|
|
130
|
+
return None, subprocess.DEVNULL
|
|
131
|
+
session_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
132
|
+
raw = open(session_dir / "raw.jsonl", "ab") # noqa: SIM115 - closed in launch()'s finally
|
|
133
|
+
err = open(session_dir / "stderr.log", "ab") # noqa: SIM115
|
|
134
|
+
for name in ("raw.jsonl", "stderr.log"):
|
|
135
|
+
os.chmod(session_dir / name, 0o600)
|
|
136
|
+
return raw, err
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
PS_ARGV = ("ps", "-A", "-o", "pgid=,rss=,time=") # constant argv: no field of the session reaches it
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def process_listing() -> str:
|
|
143
|
+
"""The read-only process listing behind a session's `resources` line (EVT-B17, EVT-B18, EVT-B7, EVT-B19); empty on failure."""
|
|
144
|
+
try:
|
|
145
|
+
return subprocess.run(list(PS_ARGV), capture_output=True, text=True, timeout=5, check=False).stdout
|
|
146
|
+
except (OSError, subprocess.SubprocessError):
|
|
147
|
+
return ""
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def launch(spec: LaunchSpec, parse_line: Callable[[bytes], list[Event]], sink: EventSink, *,
|
|
151
|
+
stop: StopRequest | None = None, clock: Clock = time.monotonic, poll_s: float = 0.05) -> RawOutcome:
|
|
152
|
+
"""Run one session to its end and return what was observed. Never raises for a session failure."""
|
|
153
|
+
out = RawOutcome()
|
|
154
|
+
raw, err = _open_raw(spec.session_dir)
|
|
155
|
+
try:
|
|
156
|
+
t0 = clock()
|
|
157
|
+
try:
|
|
158
|
+
proc = subprocess.Popen( # noqa: S603 - list argv from executor constants (SEC-B5, SEC-B6)
|
|
159
|
+
spec.argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err, cwd=spec.workdir,
|
|
160
|
+
env=session_env(spec.env_overlay, spec.session_key, drop=spec.env_drop, keep=spec.env_keep),
|
|
161
|
+
**_popen_kwargs()) # type: ignore[call-overload]
|
|
162
|
+
except OSError as exc:
|
|
163
|
+
out.spawn_error = exc
|
|
164
|
+
return out
|
|
165
|
+
assert proc.stdin is not None and proc.stdout is not None
|
|
166
|
+
stdin, stdout = proc.stdin, proc.stdout
|
|
167
|
+
started = getattr(sink, "process_started", None) # the group id, for `resources` lines (EVT-B17, EVT-B18, EVT-B7, EVT-B19)
|
|
168
|
+
if os.name == "posix" and callable(started):
|
|
169
|
+
with contextlib.suppress(Exception):
|
|
170
|
+
started(proc.pid)
|
|
171
|
+
|
|
172
|
+
def write_prompt() -> None: # started before the reader (EXI-B2)
|
|
173
|
+
try:
|
|
174
|
+
stdin.write(spec.stdin_payload)
|
|
175
|
+
stdin.flush()
|
|
176
|
+
stdin.close()
|
|
177
|
+
out.prompt_delivered = True
|
|
178
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
179
|
+
out.broken_pipe = True
|
|
180
|
+
except (OSError, ValueError):
|
|
181
|
+
pass
|
|
182
|
+
out.prompt_gap_s = clock() - t0
|
|
183
|
+
|
|
184
|
+
writer = threading.Thread(target=write_prompt, name="prompt-writer", daemon=True)
|
|
185
|
+
writer.start()
|
|
186
|
+
lines: queue.Queue[tuple[float, bytes] | None] = queue.Queue()
|
|
187
|
+
|
|
188
|
+
def read_stream() -> None:
|
|
189
|
+
for line in iter(stdout.readline, b""):
|
|
190
|
+
lines.put((clock(), line))
|
|
191
|
+
lines.put(None)
|
|
192
|
+
|
|
193
|
+
reader = threading.Thread(target=read_stream, name="stream-reader", daemon=True)
|
|
194
|
+
reader.start()
|
|
195
|
+
|
|
196
|
+
open_tools: set[str] = set()
|
|
197
|
+
last = t0
|
|
198
|
+
eof = False
|
|
199
|
+
saw_result = False
|
|
200
|
+
stop_sent_at: float | None = None
|
|
201
|
+
exited_at: float | None = None
|
|
202
|
+
|
|
203
|
+
def send_stop(reason: KillReason) -> None:
|
|
204
|
+
nonlocal stop_sent_at
|
|
205
|
+
if stop_sent_at is None:
|
|
206
|
+
out.stop_reason = reason
|
|
207
|
+
stop_sent_at = clock()
|
|
208
|
+
_signal_group(proc, hard=False)
|
|
209
|
+
|
|
210
|
+
while True:
|
|
211
|
+
try:
|
|
212
|
+
item = lines.get(timeout=poll_s)
|
|
213
|
+
except queue.Empty:
|
|
214
|
+
item = () # type: ignore[assignment]
|
|
215
|
+
if item is None:
|
|
216
|
+
eof = True
|
|
217
|
+
elif item:
|
|
218
|
+
ts, line = item
|
|
219
|
+
last = ts
|
|
220
|
+
out.lines += 1
|
|
221
|
+
out.line_times.append(ts - t0)
|
|
222
|
+
if raw is not None:
|
|
223
|
+
raw.write(line if line.endswith(b"\n") else line + b"\n")
|
|
224
|
+
try:
|
|
225
|
+
events = parse_line(line)
|
|
226
|
+
except Exception: # noqa: BLE001 - an unparsable line never fails the session (EXI-B6)
|
|
227
|
+
out.unparsable += 1
|
|
228
|
+
events = []
|
|
229
|
+
for ev in events:
|
|
230
|
+
ev = Event(kind=ev.kind, data=ev.data, ts=ts - t0)
|
|
231
|
+
if ev.kind == "tool_started":
|
|
232
|
+
open_tools.add(str(ev.data.get("call_id", "")))
|
|
233
|
+
elif ev.kind == "tool_finished":
|
|
234
|
+
open_tools.discard(str(ev.data.get("call_id", "")))
|
|
235
|
+
elif ev.kind == "result":
|
|
236
|
+
saw_result = True
|
|
237
|
+
out.events.append(ev)
|
|
238
|
+
sink.push(ev)
|
|
239
|
+
continue # drain every queued line before judging the clock
|
|
240
|
+
now = clock()
|
|
241
|
+
if proc.poll() is not None:
|
|
242
|
+
if eof:
|
|
243
|
+
break
|
|
244
|
+
exited_at = exited_at if exited_at is not None else now
|
|
245
|
+
if now - exited_at > RELEASE_AFTER_EXIT_S:
|
|
246
|
+
break # the leader ended by itself; what it left running is left alone (EXI-B5)
|
|
247
|
+
if not out.prompt_delivered and not out.broken_pipe and now - t0 > spec.prompt_window_s:
|
|
248
|
+
out.prompt_timeout = True
|
|
249
|
+
send_stop("stop")
|
|
250
|
+
if stop is not None and stop.is_set():
|
|
251
|
+
send_stop(stop.reason)
|
|
252
|
+
if not saw_result and now - t0 > spec.timeout_s:
|
|
253
|
+
send_stop("timeout")
|
|
254
|
+
if idle_action(now - last, bool(open_tools), spec.idle_s, spec.idle_floor_tool_s) == "kill":
|
|
255
|
+
send_stop("idle")
|
|
256
|
+
if stop_sent_at is not None and not out.killed and now - stop_sent_at >= spec.grace_s \
|
|
257
|
+
and proc.poll() is None:
|
|
258
|
+
_signal_group(proc, hard=True)
|
|
259
|
+
out.killed = True
|
|
260
|
+
if eof and out.killed:
|
|
261
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
262
|
+
proc.wait(timeout=spec.grace_s)
|
|
263
|
+
break
|
|
264
|
+
if out.killed:
|
|
265
|
+
_signal_group(proc, hard=True) # anything left in the group once the leader is gone
|
|
266
|
+
elif stop_sent_at is not None and proc.poll() is None:
|
|
267
|
+
_signal_group(proc, hard=True)
|
|
268
|
+
out.killed = True
|
|
269
|
+
out.exit_code = proc.wait()
|
|
270
|
+
writer.join(timeout=1.0)
|
|
271
|
+
out.duration_s = clock() - t0
|
|
272
|
+
if out.prompt_gap_s is not None and out.prompt_gap_s > PROMPT_GAP_WARN_S:
|
|
273
|
+
out.warnings.append(f"prompt_gap: {out.prompt_gap_s:.2f} s")
|
|
274
|
+
return out
|
|
275
|
+
finally:
|
|
276
|
+
if raw is not None:
|
|
277
|
+
raw.close()
|
|
278
|
+
if not isinstance(err, int):
|
|
279
|
+
err.close()
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ---------------------------------------------------------------------------------------------
|
|
283
|
+
# Model-free probes and host speed
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@dataclass(frozen=True, kw_only=True)
|
|
287
|
+
class ProbeRun:
|
|
288
|
+
exit_code: int | None
|
|
289
|
+
stdout: str
|
|
290
|
+
stderr: str
|
|
291
|
+
error: str = ""
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def run_probe(argv: list[str], *, timeout_s: float = 20.0, cwd: Path | None = None) -> ProbeRun:
|
|
295
|
+
"""Run one read-only, model-free probe command (``--version``, ``auth status``, ``--help``)."""
|
|
296
|
+
try:
|
|
297
|
+
done = subprocess.run( # noqa: S603 - constant argv from an executor module
|
|
298
|
+
argv, stdin=subprocess.DEVNULL, capture_output=True, timeout=timeout_s, cwd=cwd, check=False,
|
|
299
|
+
env=session_env({}, "probe"))
|
|
300
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
301
|
+
return ProbeRun(exit_code=None, stdout="", stderr="", error=type(exc).__name__)
|
|
302
|
+
return ProbeRun(exit_code=done.returncode, stdout=done.stdout.decode("utf-8", "replace"),
|
|
303
|
+
stderr=done.stderr.decode("utf-8", "replace"))
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def first_message(argv: list[str], payload: bytes, workdir: Path, overlay: Mapping[str, str],
|
|
307
|
+
wanted: Callable[[Mapping[str, Any]], bool], *, drop: tuple[str, ...] = (),
|
|
308
|
+
keep: tuple[str, ...] = (), timeout_s: float = 60.0) -> dict[str, Any] | None:
|
|
309
|
+
"""Launch a session, read its stream to the first JSON message ``wanted`` accepts, then end the whole process
|
|
310
|
+
group; None when the stream ends or the time runs out first (ECC-B25 reads `system/init` this way)."""
|
|
311
|
+
found: list[dict[str, Any] | None] = [None]
|
|
312
|
+
try:
|
|
313
|
+
proc = subprocess.Popen( # noqa: S603 - list argv from an executor module
|
|
314
|
+
argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=workdir,
|
|
315
|
+
env=session_env(overlay, "first-message", drop=drop, keep=keep),
|
|
316
|
+
**_popen_kwargs()) # type: ignore[call-overload]
|
|
317
|
+
except OSError:
|
|
318
|
+
return None
|
|
319
|
+
|
|
320
|
+
def read() -> None:
|
|
321
|
+
assert proc.stdout is not None
|
|
322
|
+
for line in proc.stdout:
|
|
323
|
+
try:
|
|
324
|
+
msg = json.loads(line)
|
|
325
|
+
except ValueError:
|
|
326
|
+
continue
|
|
327
|
+
if isinstance(msg, dict) and wanted(msg):
|
|
328
|
+
found[0] = msg
|
|
329
|
+
return
|
|
330
|
+
|
|
331
|
+
reader = threading.Thread(target=read, daemon=True)
|
|
332
|
+
reader.start()
|
|
333
|
+
with contextlib.suppress(OSError):
|
|
334
|
+
assert proc.stdin is not None
|
|
335
|
+
proc.stdin.write(payload)
|
|
336
|
+
proc.stdin.close()
|
|
337
|
+
reader.join(timeout_s)
|
|
338
|
+
_signal_group(proc, hard=True)
|
|
339
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
340
|
+
proc.wait(timeout=10)
|
|
341
|
+
return found[0]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
@dataclass(frozen=True, kw_only=True)
|
|
345
|
+
class HostSpeed:
|
|
346
|
+
spawn_s: float
|
|
347
|
+
walk_s: float
|
|
348
|
+
entries: int
|
|
349
|
+
slow: bool
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def host_speed(workdir: Path, *, floor_s: float = HOST_SPEED_FLOOR_S, clock: Clock = time.monotonic) -> HostSpeed:
|
|
353
|
+
"""EXI-B14: time one interpreter spawn and a bounded file walk of the workspace."""
|
|
354
|
+
t0 = clock()
|
|
355
|
+
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
|
|
356
|
+
subprocess.run([sys.executable, "-c", ""], stdin=subprocess.DEVNULL, capture_output=True, # noqa: S603
|
|
357
|
+
timeout=60, check=False)
|
|
358
|
+
spawn = clock() - t0
|
|
359
|
+
t1 = clock()
|
|
360
|
+
entries = 0
|
|
361
|
+
for _root, dirs, files in os.walk(workdir):
|
|
362
|
+
dirs[:] = [d for d in dirs if d not in (".git", ".tempergraph")]
|
|
363
|
+
entries += len(files) + len(dirs)
|
|
364
|
+
if entries >= HOST_WALK_LIMIT:
|
|
365
|
+
break
|
|
366
|
+
walk = clock() - t1
|
|
367
|
+
return HostSpeed(spawn_s=spawn, walk_s=walk, entries=entries, slow=spawn + walk > floor_s)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
@dataclass(frozen=True, kw_only=True)
|
|
371
|
+
class ShellTiming:
|
|
372
|
+
login_s: float
|
|
373
|
+
plain_s: float
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def shell_timing(budget_s: float) -> ShellTiming | None:
|
|
377
|
+
"""The audit's host-speed probe (ARC `slow-host`): `$SHELL -lc true` against `$SHELL -c true`, each under
|
|
378
|
+
the budget; None when the shell cannot start."""
|
|
379
|
+
shell = os.environ.get("SHELL") or "/bin/sh"
|
|
380
|
+
|
|
381
|
+
def timed(argv: list[str]) -> float | None:
|
|
382
|
+
t0 = time.monotonic()
|
|
383
|
+
try:
|
|
384
|
+
subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, timeout=budget_s, # noqa: S603
|
|
385
|
+
check=False)
|
|
386
|
+
except subprocess.TimeoutExpired:
|
|
387
|
+
return budget_s
|
|
388
|
+
except OSError:
|
|
389
|
+
return None
|
|
390
|
+
return time.monotonic() - t0
|
|
391
|
+
|
|
392
|
+
plain = timed([shell, "-c", "true"])
|
|
393
|
+
login = timed([shell, "-lc", "true"])
|
|
394
|
+
return None if plain is None or login is None else ShellTiming(login_s=login, plain_s=plain)
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""The operator's MCP servers and the judge's private proxy configuration (ECC-B3, ECC-B15, SEC-B3, SEC-B12, WSP-B5).
|
|
2
|
+
|
|
3
|
+
A judge reaches an MCP server only through the engine's filtering proxy (`mcpproxy`), which fronts a local (stdio)
|
|
4
|
+
server of the operator's own MCP configuration: the user scope of `.claude.json` (and the local scope the operator
|
|
5
|
+
set for the workspace). A repository's own `.mcp.json` grants a judge nothing (SEC-B3). A server that is not there,
|
|
6
|
+
one defined by a URL and one that does not start are out of reach for the attempt.
|
|
7
|
+
|
|
8
|
+
A step's private configuration instead holds the servers it declares, as the operator defines them (ECC-B19).
|
|
9
|
+
|
|
10
|
+
The private configuration holds the server's own environment values, so it lives in an owner-only folder under the
|
|
11
|
+
state root's scratch folder, one per session, is removed on every exit path and is named in no log or error text.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import shutil
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
from collections.abc import Iterable, Iterator, Mapping, Sequence
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import tempergraph
|
|
27
|
+
from tempergraph.executors.mcpproxy import server_starts
|
|
28
|
+
|
|
29
|
+
PROXY_MODULE = "tempergraph.executors.mcpproxy"
|
|
30
|
+
CONFIG_NAME = "mcp.json"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def claude_json_path(env: Mapping[str, str] | None = None) -> Path:
|
|
34
|
+
env = os.environ if env is None else env
|
|
35
|
+
folder = env.get("CLAUDE_CONFIG_DIR")
|
|
36
|
+
return (Path(folder) if folder else Path.home()) / ".claude.json"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _servers_of(block: object) -> dict[str, Any]:
|
|
40
|
+
if not isinstance(block, dict):
|
|
41
|
+
return {}
|
|
42
|
+
return {str(k): v for k, v in block.items() if isinstance(v, dict)}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def operator_servers(workdir: Path | None = None, env: Mapping[str, str] | None = None) -> dict[str, Any]:
|
|
46
|
+
"""The servers the operator's own configuration defines: user scope, then the workspace's local scope. An
|
|
47
|
+
unreadable file defines none."""
|
|
48
|
+
try:
|
|
49
|
+
data = json.loads(claude_json_path(env).read_text(encoding="utf-8"))
|
|
50
|
+
except (OSError, ValueError):
|
|
51
|
+
return {}
|
|
52
|
+
if not isinstance(data, dict):
|
|
53
|
+
return {}
|
|
54
|
+
servers: dict[str, Any] = {}
|
|
55
|
+
projects = data.get("projects")
|
|
56
|
+
if workdir is not None and isinstance(projects, dict):
|
|
57
|
+
local = projects.get(str(workdir)) or projects.get(str(Path(workdir).resolve()))
|
|
58
|
+
if isinstance(local, dict):
|
|
59
|
+
servers.update(_servers_of(local.get("mcpServers")))
|
|
60
|
+
servers.update(_servers_of(data.get("mcpServers"))) # user scope wins over the local one
|
|
61
|
+
return servers
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def classify(name: str, servers: Mapping[str, Any]) -> str:
|
|
65
|
+
"""`proxiable` (a stdio server with a command), `remote` (defined by a URL or a remote type) or `missing`."""
|
|
66
|
+
entry = servers.get(name)
|
|
67
|
+
if not isinstance(entry, dict):
|
|
68
|
+
return "missing"
|
|
69
|
+
kind = entry.get("type")
|
|
70
|
+
if entry.get("url") or kind in ("http", "sse", "ws"):
|
|
71
|
+
return "remote"
|
|
72
|
+
if kind in (None, "stdio") and isinstance(entry.get("command"), str) and entry["command"]:
|
|
73
|
+
return "proxiable"
|
|
74
|
+
return "missing"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def viewed_servers(tool_names: Iterable[str]) -> dict[str, tuple[str, ...]]:
|
|
78
|
+
"""`mcp__<server>__<tool>` names grouped by server, in first-seen order."""
|
|
79
|
+
grouped: dict[str, list[str]] = {}
|
|
80
|
+
for name in tool_names:
|
|
81
|
+
parts = name.split("__", 2)
|
|
82
|
+
if len(parts) == 3 and parts[0] == "mcp" and parts[1] and parts[2]:
|
|
83
|
+
grouped.setdefault(parts[1], []).append(parts[2])
|
|
84
|
+
return {s: tuple(dict.fromkeys(t)) for s, t in grouped.items()}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _proxy_entry(entry: Mapping[str, Any], allowed: Sequence[str]) -> dict[str, Any]:
|
|
88
|
+
args: list[str] = ["-m", PROXY_MODULE]
|
|
89
|
+
for tool in allowed:
|
|
90
|
+
args += ["--allow", tool]
|
|
91
|
+
args += ["--", str(entry["command"]), *[str(a) for a in entry.get("args") or []]]
|
|
92
|
+
env = {str(k): str(v) for k, v in (entry.get("env") or {}).items()} if isinstance(entry.get("env"), dict) else {}
|
|
93
|
+
env.setdefault("PYTHONPATH", str(Path(tempergraph.__file__).resolve().parent.parent))
|
|
94
|
+
return {"command": sys.executable, "args": args, "env": env}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def declared_servers(tools: Iterable[str]) -> dict[str, tuple[str, ...]]:
|
|
98
|
+
"""`mcp:<server>/<tool>` capabilities of a step grouped by server, in first-seen order; others are ignored."""
|
|
99
|
+
grouped: dict[str, list[str]] = {}
|
|
100
|
+
for cap in tools:
|
|
101
|
+
if not cap.startswith("mcp:"):
|
|
102
|
+
continue
|
|
103
|
+
server, sep, tool = cap[4:].partition("/")
|
|
104
|
+
if sep and server and tool:
|
|
105
|
+
grouped.setdefault(server, []).append(tool)
|
|
106
|
+
return {s: tuple(dict.fromkeys(t)) for s, t in grouped.items()}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def build_config(viewed: Mapping[str, Sequence[str]], servers: Mapping[str, Any], *,
|
|
110
|
+
direct: bool = False) -> dict[str, Any]:
|
|
111
|
+
"""One proxy entry per viewed server, each offering only that server's viewed tools; with `direct` (a step,
|
|
112
|
+
ECC-B19) each entry is the operator's own definition of the server."""
|
|
113
|
+
if direct:
|
|
114
|
+
return {"mcpServers": {name: dict(servers[name]) for name in viewed}}
|
|
115
|
+
return {"mcpServers": {name: _proxy_entry(servers[name], tools) for name, tools in viewed.items()}}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@contextlib.contextmanager
|
|
119
|
+
def private_config(viewed: Mapping[str, Sequence[str]], servers: Mapping[str, Any], base: Path, *,
|
|
120
|
+
direct: bool = False) -> Iterator[Path]:
|
|
121
|
+
"""Write the private strict configuration into a new owner-only folder under `base` and remove it on every exit."""
|
|
122
|
+
base.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
123
|
+
folder = Path(tempfile.mkdtemp(prefix="mcp-", dir=base))
|
|
124
|
+
try:
|
|
125
|
+
os.chmod(folder, 0o700)
|
|
126
|
+
path = folder / CONFIG_NAME
|
|
127
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
128
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
129
|
+
json.dump(build_config(viewed, servers, direct=direct), fh)
|
|
130
|
+
yield path
|
|
131
|
+
finally:
|
|
132
|
+
shutil.rmtree(folder, ignore_errors=True)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def scratch_base(session_dir: Path | None) -> Path | None:
|
|
136
|
+
"""The state root's scratch folder above a session folder (WSP-B5), or nothing when there is none."""
|
|
137
|
+
if session_dir is None:
|
|
138
|
+
return None
|
|
139
|
+
for parent in Path(session_dir).parents:
|
|
140
|
+
if (parent / "scratch").is_dir():
|
|
141
|
+
return parent / "scratch"
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def unreachable(tool_names: Iterable[str], workdir: Path, env: Mapping[str, str] | None = None,
|
|
146
|
+
timeout_s: float = 10.0) -> dict[str, str]:
|
|
147
|
+
"""The viewed servers with no working proxy, each with its reason: `missing`, `remote` or `start_failed`."""
|
|
148
|
+
servers = operator_servers(workdir, env)
|
|
149
|
+
out: dict[str, str] = {}
|
|
150
|
+
for name in viewed_servers(tool_names):
|
|
151
|
+
kind = classify(name, servers)
|
|
152
|
+
if kind != "proxiable":
|
|
153
|
+
out[name] = kind
|
|
154
|
+
elif not server_starts(servers[name], workdir, timeout_s):
|
|
155
|
+
out[name] = "start_failed"
|
|
156
|
+
return out
|