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
tempergraph/run/log.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
"""The run log, cost rules and the live progress file (OBS-B7, OBS-B1, OBS-B8, OBS-B9, OBS-B10 to OBS-B13, OBS-B14, EVT-B10 to EVT-B16; OVR-B4).
|
|
2
|
+
|
|
3
|
+
Every write is best effort: a failing write is counted and never changes the run.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from tempergraph.constants import SCHEMA
|
|
18
|
+
from tempergraph.contracts import Event, EventSink, Usage
|
|
19
|
+
from tempergraph.docs import append_jsonl, write_json
|
|
20
|
+
from tempergraph.security.scrub import clip, scrub
|
|
21
|
+
from tempergraph.store.layout import now_iso
|
|
22
|
+
|
|
23
|
+
# Engine default prices, USD per million tokens, by model family, for the current generation that the tier
|
|
24
|
+
# aliases resolve to (first-party list prices as of 2026-11; OBS-B10 to OBS-B13). The binding table overrides per model.
|
|
25
|
+
# A row without `cache_read` prices cache reads at CACHE_READ_FACTOR of input.
|
|
26
|
+
DEFAULT_PRICES: dict[str, dict[str, float]] = {
|
|
27
|
+
"haiku": {"input": 0.10, "output": 0.50},
|
|
28
|
+
"sonnet": {"input": 2.0, "output": 10.0, "cache_read": 0.10},
|
|
29
|
+
"opus": {"input": 4.0, "output": 20.0, "cache_read": 0.20},
|
|
30
|
+
}
|
|
31
|
+
CACHE_READ_FACTOR = 0.1
|
|
32
|
+
CACHE_WRITE_FACTOR = 1.25
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def family(model: str | None) -> str | None:
|
|
36
|
+
m = (model or "").lower()
|
|
37
|
+
return next((f for f in DEFAULT_PRICES if f in m), None)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def estimate(usage: Usage, model: str | None, prices: Mapping[str, Mapping[str, float]] | None = None
|
|
41
|
+
) -> float | None:
|
|
42
|
+
"""The engine's own estimate for a session with tokens; None when unmeasured (OBS-B10 to OBS-B13)."""
|
|
43
|
+
if not usage.has_tokens():
|
|
44
|
+
return None
|
|
45
|
+
row = (prices or {}).get(model or "") or DEFAULT_PRICES.get(family(model) or "")
|
|
46
|
+
if row is None:
|
|
47
|
+
return None
|
|
48
|
+
pin, pout = row["input"], row["output"]
|
|
49
|
+
total = (usage.input_tokens or 0) * pin + (usage.output_tokens or 0) * pout
|
|
50
|
+
total += (usage.cache_read_tokens or 0) * row.get("cache_read", pin * CACHE_READ_FACTOR)
|
|
51
|
+
total += (usage.cache_write_tokens or 0) * pin * CACHE_WRITE_FACTOR
|
|
52
|
+
return round(total / 1_000_000, 6)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(kw_only=True)
|
|
56
|
+
class CostTotals:
|
|
57
|
+
"""Run cost so far: reported and estimated kept apart (OBS-B10 to OBS-B13)."""
|
|
58
|
+
|
|
59
|
+
reported: float = 0.0
|
|
60
|
+
estimated: float = 0.0
|
|
61
|
+
estimated_only: float = 0.0 # estimates of sessions that reported nothing
|
|
62
|
+
sessions: int = 0
|
|
63
|
+
reported_sessions: int = 0
|
|
64
|
+
estimated_sessions: int = 0
|
|
65
|
+
unmeasured: int = 0
|
|
66
|
+
|
|
67
|
+
def add(self, usage: Usage) -> None:
|
|
68
|
+
self.sessions += 1
|
|
69
|
+
if usage.reported_cost_usd is not None:
|
|
70
|
+
self.reported += usage.reported_cost_usd
|
|
71
|
+
self.reported_sessions += 1
|
|
72
|
+
if usage.estimated_cost_usd is not None:
|
|
73
|
+
self.estimated += usage.estimated_cost_usd
|
|
74
|
+
self.estimated_sessions += 1
|
|
75
|
+
if usage.reported_cost_usd is None:
|
|
76
|
+
self.estimated_only += usage.estimated_cost_usd
|
|
77
|
+
if usage.reported_cost_usd is None and usage.estimated_cost_usd is None:
|
|
78
|
+
self.unmeasured += 1
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def completeness(self) -> str:
|
|
82
|
+
if self.unmeasured:
|
|
83
|
+
return "incomplete"
|
|
84
|
+
return "complete" if self.reported_sessions == self.sessions else "estimated"
|
|
85
|
+
|
|
86
|
+
def figure(self) -> float:
|
|
87
|
+
"""The run line's figure: reported where present, else estimated, per session (BUD-B8, BUD-B9)."""
|
|
88
|
+
return round(self.reported + self.estimated_only, 6)
|
|
89
|
+
|
|
90
|
+
def to_json(self) -> dict[str, Any]:
|
|
91
|
+
return {"reported": round(self.reported, 6) if self.reported_sessions else None,
|
|
92
|
+
"estimated": round(self.estimated, 6) if self.estimated_sessions else None,
|
|
93
|
+
"incomplete": self.completeness == "incomplete", "completeness": self.completeness,
|
|
94
|
+
"counters": {k: getattr(self, k) for k in ("reported", "estimated", "estimated_only", "sessions",
|
|
95
|
+
"reported_sessions", "estimated_sessions", "unmeasured")}}
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def from_json(cls, d: Mapping[str, Any] | None) -> CostTotals:
|
|
99
|
+
t = cls()
|
|
100
|
+
for k, v in ((d or {}).get("counters") or {}).items():
|
|
101
|
+
if k in cls.__dataclass_fields__ and isinstance(v, int | float):
|
|
102
|
+
setattr(t, k, v)
|
|
103
|
+
return t
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
ENVELOPE_OPTIONAL = ("unit", "item", "attempt", "session_key")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cost_so_far(cost: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
110
|
+
"""EVT-B10 to EVT-B16 `cost_so_far`: reported, estimated and the completeness flag for the thread so far."""
|
|
111
|
+
t = CostTotals.from_json(cost)
|
|
112
|
+
j = t.to_json()
|
|
113
|
+
return {"reported": j["reported"], "estimated": j["estimated"], "completeness": t.completeness}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class RunLog:
|
|
117
|
+
"""`runs/<workflow>/<task_id>/run.jsonl`; the first line carries the schema.
|
|
118
|
+
|
|
119
|
+
Every record carries the envelope of EVT-B8, EVT-B9: `seq` continues across instances and segments,
|
|
120
|
+
`segment` counts process lifetimes (0 at the start, +1 per resume), `thread_id` comes from the path,
|
|
121
|
+
and `unit`, `item`, `attempt` and `session_key` are present, null when the record has no unit.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, path: Path, observers: Any = None) -> None:
|
|
125
|
+
self.path = path
|
|
126
|
+
self.failures = 0
|
|
127
|
+
self.seq = last_seq(path) # seq continues across segments (EVT-B2)
|
|
128
|
+
self.thread_id = f"{path.parent.parent.name}/{path.parent.name}"
|
|
129
|
+
self.segment: int | None = None
|
|
130
|
+
self.checked_tail = False
|
|
131
|
+
self.observers = observers # an ObserverHub (run/events.py) or None; enabled in operator config only
|
|
132
|
+
self._lock = threading.RLock() # branches of a parallel block write from their own threads (research `rationale-carried-from-the-engine-specs` WSP)
|
|
133
|
+
|
|
134
|
+
def _segment(self) -> int:
|
|
135
|
+
"""This process's segment: the one after the log's last `run_started`, or 0 for a new thread."""
|
|
136
|
+
if self.segment is None:
|
|
137
|
+
prev = last_record(self.path, "run_started")
|
|
138
|
+
last = (prev or {}).get("segment")
|
|
139
|
+
self.segment = 0 if prev is None else (last + 1 if isinstance(last, int) else 1)
|
|
140
|
+
return self.segment
|
|
141
|
+
|
|
142
|
+
def write(self, record: str, /, **fields: Any) -> int:
|
|
143
|
+
with self._lock:
|
|
144
|
+
return self._write(record, **fields)
|
|
145
|
+
|
|
146
|
+
def _write(self, record: str, /, **fields: Any) -> int:
|
|
147
|
+
self.seq += 1
|
|
148
|
+
try:
|
|
149
|
+
segment = self._segment()
|
|
150
|
+
except Exception: # noqa: BLE001 - C2
|
|
151
|
+
segment = 0
|
|
152
|
+
rec = {**fields, "kind": record, "ts": now_iso(), "seq": self.seq, "thread_id": self.thread_id,
|
|
153
|
+
"segment": segment}
|
|
154
|
+
if "kind" in fields:
|
|
155
|
+
rec["session_kind"] = fields["kind"]
|
|
156
|
+
for key in ENVELOPE_OPTIONAL:
|
|
157
|
+
rec.setdefault(key, None)
|
|
158
|
+
if rec["session_key"] and (rec["unit"] is None or rec["attempt"] is None):
|
|
159
|
+
unit, item, attempt = split_session_key(str(rec["session_key"]))
|
|
160
|
+
for k, v in (("unit", unit), ("item", item), ("attempt", attempt)):
|
|
161
|
+
if rec[k] is None:
|
|
162
|
+
rec[k] = v
|
|
163
|
+
out = _jsonable(rec)
|
|
164
|
+
try:
|
|
165
|
+
if not self.path.exists():
|
|
166
|
+
append_jsonl(self.path, {"kind": "schema", "schema": SCHEMA["run_log"]})
|
|
167
|
+
elif not self.checked_tail:
|
|
168
|
+
_end_cut_line(self.path)
|
|
169
|
+
self.checked_tail = True
|
|
170
|
+
append_jsonl(self.path, out)
|
|
171
|
+
except Exception: # noqa: BLE001 - observability never changes the run (OVR-B4)
|
|
172
|
+
self.failures += 1
|
|
173
|
+
return self.seq
|
|
174
|
+
if self.observers is not None:
|
|
175
|
+
self.observers.on_record(out)
|
|
176
|
+
for name, error in self.observers.take_errors(): # EVT-B5: recorded once, the run goes on
|
|
177
|
+
self.write("engine_error", scope="observer", observer=name, error=error)
|
|
178
|
+
if record in ("run_started", "run_exit"):
|
|
179
|
+
self._rows(record, segment)
|
|
180
|
+
self._beat(record)
|
|
181
|
+
self._hooks(out)
|
|
182
|
+
return self.seq
|
|
183
|
+
|
|
184
|
+
def _hooks(self, rec: Mapping[str, Any]) -> None:
|
|
185
|
+
"""Lifecycle hooks for the record's event (HOK-B1 to HOK-B6); best effort, never changes the run (OVR-B4)."""
|
|
186
|
+
try:
|
|
187
|
+
from tempergraph.observe import hooks
|
|
188
|
+
|
|
189
|
+
hooks.on_record(self.path, rec)
|
|
190
|
+
except Exception: # noqa: BLE001
|
|
191
|
+
self.failures += 1
|
|
192
|
+
|
|
193
|
+
def _beat(self, record: str) -> None:
|
|
194
|
+
"""The heartbeat to configured sinks, at most every 60 s and at the run's ends (CST-B9); best effort."""
|
|
195
|
+
try:
|
|
196
|
+
from tempergraph.observe import sinks
|
|
197
|
+
|
|
198
|
+
sinks.on_record(self.path, record)
|
|
199
|
+
except Exception: # noqa: BLE001
|
|
200
|
+
self.failures += 1
|
|
201
|
+
|
|
202
|
+
def _rows(self, record: str, segment: int) -> None:
|
|
203
|
+
"""The machine index at `run_started` and the stats row at `run_exit` (CST-B8, CST-B9); best effort (OVR-B4)."""
|
|
204
|
+
try:
|
|
205
|
+
from tempergraph.observe import rows
|
|
206
|
+
|
|
207
|
+
if record == "run_started":
|
|
208
|
+
rows.on_run_started(self.path)
|
|
209
|
+
else:
|
|
210
|
+
rows.on_run_exit(self.path, segment)
|
|
211
|
+
except Exception: # noqa: BLE001
|
|
212
|
+
self.failures += 1
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class ChildLog(RunLog):
|
|
216
|
+
"""SWF-B8: the writer a child's nodes use. Every record goes to the parent's `run.jsonl`, carrying `child: <unit>`
|
|
217
|
+
and the child's own `unit`; a session key reads `<unit>/<child unit>.<attempt>.<kind>`, and the child's own part of it
|
|
218
|
+
names the record's unit, item and attempt. Everything else is the parent's log: it holds no state of its own, so any
|
|
219
|
+
attribute of a log that is not set here is read from the parent."""
|
|
220
|
+
|
|
221
|
+
def __init__(self, parent: RunLog, unit: str) -> None: # the parent's `__init__` is not called: it would reopen the file
|
|
222
|
+
self.parent = parent
|
|
223
|
+
self.unit = unit
|
|
224
|
+
|
|
225
|
+
def write(self, record: str, /, **fields: Any) -> int:
|
|
226
|
+
fields.setdefault("child", self.unit)
|
|
227
|
+
key = fields.get("session_key")
|
|
228
|
+
if key and fields.get("unit") is None:
|
|
229
|
+
prefix = f"{self.unit}/"
|
|
230
|
+
unit, item, attempt = split_session_key(str(key)[len(prefix):] if str(key).startswith(prefix) else str(key))
|
|
231
|
+
for k, v in (("unit", unit), ("item", item), ("attempt", attempt)):
|
|
232
|
+
if fields.get(k) is None:
|
|
233
|
+
fields[k] = v
|
|
234
|
+
return self.parent.write(record, **fields)
|
|
235
|
+
|
|
236
|
+
def __getattr__(self, name: str) -> Any:
|
|
237
|
+
return getattr(self.parent, name)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def split_costs(records: Iterable[Mapping[str, Any]]) -> dict[str | None, dict[str, Any]]:
|
|
241
|
+
"""SWF-B4: the money of the `agent_run` records by the sub-workflow unit that spent it, `None` for the run's own
|
|
242
|
+
steps. A child's spend counts in the run total and the daily total, and is never summed into the parent's own."""
|
|
243
|
+
out: dict[str | None, dict[str, Any]] = {}
|
|
244
|
+
for r in records:
|
|
245
|
+
if r.get("kind") != "agent_run":
|
|
246
|
+
continue
|
|
247
|
+
row = out.setdefault(r.get("child"), {"reported": 0.0, "estimated": 0.0, "sessions": 0})
|
|
248
|
+
usage = r.get("usage") or {}
|
|
249
|
+
row["sessions"] += 1
|
|
250
|
+
for k, field_ in (("reported", "reported_cost_usd"), ("estimated", "estimated_cost_usd")):
|
|
251
|
+
if isinstance(usage.get(field_), int | float):
|
|
252
|
+
row[k] += float(usage[field_])
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _end_cut_line(path: Path) -> None:
|
|
257
|
+
"""A process that died mid-line leaves a partial last line; end it so the next record is whole."""
|
|
258
|
+
with open(path, "rb") as fh:
|
|
259
|
+
fh.seek(0, os.SEEK_END)
|
|
260
|
+
if fh.tell() == 0:
|
|
261
|
+
return
|
|
262
|
+
fh.seek(-1, os.SEEK_END)
|
|
263
|
+
last = fh.read(1)
|
|
264
|
+
if last != b"\n":
|
|
265
|
+
with open(path, "ab") as fh:
|
|
266
|
+
fh.write(b"\n")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def split_session_key(key: str) -> tuple[str | None, str | None, int | None]:
|
|
270
|
+
"""`<unit>[.<item>].<attempt>.<kind>[.<n>]` back into unit, item and attempt (EVT-B8, EVT-B9)."""
|
|
271
|
+
parts = key.split(".")
|
|
272
|
+
for i in range(len(parts) - 2, 0, -1):
|
|
273
|
+
if parts[i].isdigit() and not parts[i + 1].isdigit():
|
|
274
|
+
head = parts[:i]
|
|
275
|
+
unit = head[0] if head else None
|
|
276
|
+
item = ".".join(head[1:]) or None
|
|
277
|
+
return unit, item, int(parts[i])
|
|
278
|
+
return None, None, None
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def last_seq(path: Path) -> int:
|
|
282
|
+
"""The `seq` of the last record of a run log, 0 when there is none; reads only the file's tail."""
|
|
283
|
+
try:
|
|
284
|
+
with open(path, "rb") as fh:
|
|
285
|
+
fh.seek(0, os.SEEK_END)
|
|
286
|
+
fh.seek(max(0, fh.tell() - 65536))
|
|
287
|
+
lines = fh.read().splitlines()
|
|
288
|
+
except OSError:
|
|
289
|
+
return 0
|
|
290
|
+
for line in reversed(lines):
|
|
291
|
+
try:
|
|
292
|
+
seq = json.loads(line).get("seq")
|
|
293
|
+
except (ValueError, AttributeError):
|
|
294
|
+
continue
|
|
295
|
+
if isinstance(seq, int):
|
|
296
|
+
return seq
|
|
297
|
+
return 0
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def last_record(path: Path, kind: str, **match: Any) -> dict[str, Any] | None:
|
|
301
|
+
"""The last run-log record of `kind` whose fields match; None when there is none."""
|
|
302
|
+
found = None
|
|
303
|
+
try:
|
|
304
|
+
with open(path, encoding="utf-8") as fh:
|
|
305
|
+
for line in fh:
|
|
306
|
+
try:
|
|
307
|
+
rec = json.loads(line)
|
|
308
|
+
except ValueError:
|
|
309
|
+
continue
|
|
310
|
+
if rec.get("kind") == kind and all(rec.get(k) == v for k, v in match.items()):
|
|
311
|
+
found = rec
|
|
312
|
+
except OSError:
|
|
313
|
+
return None
|
|
314
|
+
return found
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def legacy_dry_run(path: Path) -> bool:
|
|
318
|
+
"""LFS-B3: the log holds a `run_started` with `dry_run` and no `settings_resolved` row for `run.loop_dry_run`: a
|
|
319
|
+
thread the engine started dry or one written before the setting. A missing file is false."""
|
|
320
|
+
dry = False
|
|
321
|
+
try:
|
|
322
|
+
with open(path, encoding="utf-8") as fh:
|
|
323
|
+
for line in fh:
|
|
324
|
+
try:
|
|
325
|
+
rec = json.loads(line)
|
|
326
|
+
except ValueError:
|
|
327
|
+
continue
|
|
328
|
+
if not isinstance(rec, dict):
|
|
329
|
+
continue
|
|
330
|
+
if rec.get("kind") == "run_started" and rec.get("dry_run"):
|
|
331
|
+
dry = True
|
|
332
|
+
elif rec.get("kind") == "settings_resolved" and any(
|
|
333
|
+
isinstance(r, dict) and r.get("key") == "run.loop_dry_run" for r in rec.get("rows") or ()):
|
|
334
|
+
return False
|
|
335
|
+
except OSError:
|
|
336
|
+
return False
|
|
337
|
+
return dry
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _jsonable(v: Any) -> Any:
|
|
341
|
+
if isinstance(v, Usage):
|
|
342
|
+
return v.to_json()
|
|
343
|
+
if isinstance(v, Mapping):
|
|
344
|
+
return {str(k): _jsonable(x) for k, x in v.items()}
|
|
345
|
+
if isinstance(v, list | tuple):
|
|
346
|
+
return [_jsonable(x) for x in v]
|
|
347
|
+
if isinstance(v, str | int | float | bool) or v is None:
|
|
348
|
+
return v
|
|
349
|
+
return str(v)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
JOURNAL_MAX_LINES = 20_000
|
|
353
|
+
JOURNAL_MAX_BYTES = 8 * 1024 * 1024
|
|
354
|
+
# The journal cap's drop order (EVT-B17, EVT-B18, EVT-B7, EVT-B19): past half the cap `model_delta` lines are dropped, past three
|
|
355
|
+
# quarters `text` lines too, and past 95 % everything but tool lines; the last slot is the `truncated` line.
|
|
356
|
+
_DROP_STAGES: tuple[tuple[float, frozenset[str] | None], ...] = (
|
|
357
|
+
(0.95, None), (0.75, frozenset({"model_delta", "text"})), (0.5, frozenset({"model_delta"})))
|
|
358
|
+
_TOOL_EVENTS = frozenset({"tool_started", "tool_finished"})
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class LiveSink(EventSink):
|
|
362
|
+
"""The live progress file (OBS-B14, RDD-B12) and the activity journal (EVT-B17, EVT-B18, EVT-B7, EVT-B19).
|
|
363
|
+
|
|
364
|
+
The journal is buffered and flushed at most once a second and at session end; the live file is replaced
|
|
365
|
+
at most once a second. `opened` is called once with the `session_started` data, so the caller writes
|
|
366
|
+
`session_opened`; `observers` get every journal line after it is written. Every write is best effort.
|
|
367
|
+
"""
|
|
368
|
+
|
|
369
|
+
def __init__(self, session_dir: Path | None, clock: Any = time.monotonic, *,
|
|
370
|
+
opened: Callable[[dict[str, Any]], None] | None = None, observers: Any = None,
|
|
371
|
+
session_key: str = "", tool_inputs: bool = True,
|
|
372
|
+
max_lines: int = JOURNAL_MAX_LINES, max_bytes: int = JOURNAL_MAX_BYTES) -> None:
|
|
373
|
+
super().__init__()
|
|
374
|
+
self.dir = session_dir
|
|
375
|
+
self.clock = clock
|
|
376
|
+
self.opened = opened
|
|
377
|
+
self.observers = observers
|
|
378
|
+
self.session_key = session_key or (session_dir.name if session_dir else "")
|
|
379
|
+
self.tool_inputs = tool_inputs
|
|
380
|
+
self.max_lines, self.max_bytes = max_lines, max_bytes
|
|
381
|
+
self.last_write = float("-inf")
|
|
382
|
+
self.last_flush = float("-inf")
|
|
383
|
+
self.recent: list[dict[str, Any]] = []
|
|
384
|
+
self.open_tool: dict[str, Any] | None = None
|
|
385
|
+
self.open_calls: dict[str, dict[str, Any]] = {}
|
|
386
|
+
self.last_text = ""
|
|
387
|
+
self.last_event_at: str | None = None
|
|
388
|
+
self.tokens_so_far: int | None = None
|
|
389
|
+
self.turns_so_far: int | None = None
|
|
390
|
+
self.pgid: int | None = None
|
|
391
|
+
self.sampler: Any = None
|
|
392
|
+
self.samples: list[dict[str, Any]] = [] # `resources` lines from the sampler thread, journaled on push
|
|
393
|
+
self.n = 0
|
|
394
|
+
self.lines = 0
|
|
395
|
+
self.bytes = 0
|
|
396
|
+
self.dropped: dict[str, int] = {}
|
|
397
|
+
self.buffer: list[dict[str, Any]] = []
|
|
398
|
+
self.failures = 0
|
|
399
|
+
self.disabled = False
|
|
400
|
+
self.closed = False
|
|
401
|
+
|
|
402
|
+
# -- the journal -------------------------------------------------------------------------------
|
|
403
|
+
|
|
404
|
+
def _keep(self, ev: str) -> bool:
|
|
405
|
+
used = max(self.lines / self.max_lines, self.bytes / self.max_bytes)
|
|
406
|
+
if self.lines >= self.max_lines - 1 or self.bytes >= self.max_bytes:
|
|
407
|
+
return False
|
|
408
|
+
for threshold, drop in _DROP_STAGES:
|
|
409
|
+
if used >= threshold:
|
|
410
|
+
return ev in _TOOL_EVENTS if drop is None else ev not in drop
|
|
411
|
+
return True
|
|
412
|
+
|
|
413
|
+
def _journal(self, row: dict[str, Any]) -> None:
|
|
414
|
+
if self.dir is None or self.disabled:
|
|
415
|
+
return
|
|
416
|
+
ev = str(row.get("ev"))
|
|
417
|
+
if not self._keep(ev):
|
|
418
|
+
self.dropped[ev] = self.dropped.get(ev, 0) + 1
|
|
419
|
+
return
|
|
420
|
+
row = _jsonable(row)
|
|
421
|
+
self.lines += 1
|
|
422
|
+
self.bytes += len(json.dumps(row, ensure_ascii=False)) + 1
|
|
423
|
+
self.buffer.append(row)
|
|
424
|
+
|
|
425
|
+
def flush(self) -> None:
|
|
426
|
+
if self.dir is None or not self.buffer or self.disabled:
|
|
427
|
+
self.buffer.clear()
|
|
428
|
+
return
|
|
429
|
+
rows, self.buffer = self.buffer, []
|
|
430
|
+
try:
|
|
431
|
+
path = self.dir / "activity.jsonl"
|
|
432
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
433
|
+
with open(path, "a", encoding="utf-8") as fh:
|
|
434
|
+
for row in rows:
|
|
435
|
+
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
436
|
+
os.chmod(path, 0o600)
|
|
437
|
+
except Exception: # noqa: BLE001 - EVT-B25: journal off for this session, the session goes on
|
|
438
|
+
self.failures += 1
|
|
439
|
+
self.disabled = True
|
|
440
|
+
return
|
|
441
|
+
self.last_flush = self.clock()
|
|
442
|
+
if self.observers is not None:
|
|
443
|
+
for row in rows:
|
|
444
|
+
self.observers.on_activity(self.session_key, row)
|
|
445
|
+
|
|
446
|
+
# -- events --------------------------------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
def push(self, event: Event) -> None:
|
|
449
|
+
super().push(event)
|
|
450
|
+
if self.dir is None:
|
|
451
|
+
return
|
|
452
|
+
self.n += 1
|
|
453
|
+
d = {k: v for k, v in dict(event.data).items() if k != "usage"}
|
|
454
|
+
self.last_event_at = now_iso()
|
|
455
|
+
self._drain_samples()
|
|
456
|
+
if event.kind == "session_started":
|
|
457
|
+
self._opened({**({"pgid": self.pgid} if self.pgid is not None else {}), **dict(event.data)})
|
|
458
|
+
elif event.kind == "tool_started":
|
|
459
|
+
if not self.tool_inputs:
|
|
460
|
+
d["input_summary"] = None
|
|
461
|
+
call: dict[str, Any] = {"name": d.get("name"), "capability": d.get("capability"),
|
|
462
|
+
"input_summary": d.get("input_summary"), "started_at": self.last_event_at, "t": event.ts}
|
|
463
|
+
self.open_calls[str(d.get("call_id", ""))] = call
|
|
464
|
+
self.open_tool = call
|
|
465
|
+
elif event.kind == "tool_finished":
|
|
466
|
+
done_call = self.open_calls.pop(str(d.get("call_id", "")), None)
|
|
467
|
+
if done_call is not None:
|
|
468
|
+
call = done_call
|
|
469
|
+
d["duration_s"] = round(max(0.0, event.ts - float(call.get("t") or 0.0)), 3)
|
|
470
|
+
done = {"name": call["name"], "input_summary": call["input_summary"], "ok": d.get("ok"),
|
|
471
|
+
"duration_s": d["duration_s"]}
|
|
472
|
+
self.recent = (self.recent + [done])[-10:]
|
|
473
|
+
self.open_tool = next(reversed(self.open_calls.values()), None)
|
|
474
|
+
elif event.kind == "text":
|
|
475
|
+
self.last_text = clip(scrub(str(d.get("last_line", ""))), 200)
|
|
476
|
+
elif event.kind == "result":
|
|
477
|
+
usage = event.data.get("usage")
|
|
478
|
+
if isinstance(usage, Usage):
|
|
479
|
+
tokens = [x for x in (usage.input_tokens, usage.output_tokens) if x is not None]
|
|
480
|
+
self.tokens_so_far = sum(tokens) if tokens else None
|
|
481
|
+
self.turns_so_far = usage.turns
|
|
482
|
+
if "pgid" in d and isinstance(d.get("pgid"), int):
|
|
483
|
+
self.pgid = d["pgid"]
|
|
484
|
+
self._journal({"t": round(event.ts, 3), "n": self.n, "ev": event.kind, **d})
|
|
485
|
+
now = self.clock()
|
|
486
|
+
if now - self.last_flush >= 1.0 or event.kind == "result":
|
|
487
|
+
self.flush()
|
|
488
|
+
if now - self.last_write >= 1.0 or event.kind == "result":
|
|
489
|
+
self.last_write = now
|
|
490
|
+
self._live()
|
|
491
|
+
|
|
492
|
+
def process_started(self, pgid: int, *, listing: Any = None, every_s: float | None = None) -> None:
|
|
493
|
+
"""The launcher's group id (EVT-B17, EVT-B18, EVT-B7, EVT-B19): kept for `session_opened` and sampled for `resources` lines."""
|
|
494
|
+
from tempergraph.run.resources import EVERY_S, Sampler
|
|
495
|
+
|
|
496
|
+
self.pgid = pgid
|
|
497
|
+
if self.dir is not None and self.sampler is None:
|
|
498
|
+
self.sampler = Sampler(pgid, self.samples.append, every_s=every_s or EVERY_S, listing=listing,
|
|
499
|
+
clock=self.clock).start()
|
|
500
|
+
|
|
501
|
+
def _drain_samples(self) -> None:
|
|
502
|
+
while self.samples:
|
|
503
|
+
row = self.samples.pop(0)
|
|
504
|
+
self.n += 1
|
|
505
|
+
self._journal({"n": self.n, **row})
|
|
506
|
+
|
|
507
|
+
def write_meta(self, **fields: Any) -> None:
|
|
508
|
+
"""`meta.json` of the session (LOS-B7, LOS-B8, LOS-B9), merged field by field; best effort (OVR-B4)."""
|
|
509
|
+
if self.dir is None or self.disabled:
|
|
510
|
+
return
|
|
511
|
+
path = self.dir / "meta.json"
|
|
512
|
+
try:
|
|
513
|
+
held = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"schema_version": 1}
|
|
514
|
+
held.update(_jsonable(fields))
|
|
515
|
+
write_json(path, held)
|
|
516
|
+
except Exception: # noqa: BLE001
|
|
517
|
+
self.failures += 1
|
|
518
|
+
|
|
519
|
+
def _opened(self, data: dict[str, Any]) -> None:
|
|
520
|
+
if self.opened is None:
|
|
521
|
+
return
|
|
522
|
+
try:
|
|
523
|
+
self.opened(data)
|
|
524
|
+
except Exception: # noqa: BLE001 - C2
|
|
525
|
+
self.failures += 1
|
|
526
|
+
self.opened = None
|
|
527
|
+
|
|
528
|
+
def _live(self) -> None:
|
|
529
|
+
if self.dir is None:
|
|
530
|
+
return
|
|
531
|
+
open_tool = None
|
|
532
|
+
if self.open_tool is not None:
|
|
533
|
+
open_tool = {k: v for k, v in self.open_tool.items() if k != "t"}
|
|
534
|
+
try:
|
|
535
|
+
write_json(self.dir / "live.json", {
|
|
536
|
+
"schema_version": SCHEMA["activity"], "session_key": self.session_key, "open_tool": open_tool,
|
|
537
|
+
"recent": self.recent, "last_text": self.last_text, "tokens_so_far": self.tokens_so_far,
|
|
538
|
+
"turns_so_far": self.turns_so_far, "pgid": self.pgid, "last_event_at": self.last_event_at,
|
|
539
|
+
"updated_at": now_iso(), "pid": os.getpid(), "ended": self.closed})
|
|
540
|
+
except Exception: # noqa: BLE001
|
|
541
|
+
self.failures += 1
|
|
542
|
+
|
|
543
|
+
def close(self) -> None:
|
|
544
|
+
"""Session end: the `truncated` line when lines were dropped, the last flush and live file."""
|
|
545
|
+
if self.closed:
|
|
546
|
+
return
|
|
547
|
+
self.closed = True
|
|
548
|
+
if self.sampler is not None:
|
|
549
|
+
self.sampler.stop()
|
|
550
|
+
self._drain_samples()
|
|
551
|
+
if self.dropped and self.dir is not None and not self.disabled:
|
|
552
|
+
self.n += 1
|
|
553
|
+
self.buffer.append({"t": None, "n": self.n, "ev": "truncated", "dropped": dict(self.dropped)})
|
|
554
|
+
self.flush()
|
|
555
|
+
self.open_tool = None
|
|
556
|
+
self.write_meta(ended_at=now_iso())
|
|
557
|
+
if self.dir is not None: # LOS-B7, LOS-B8, LOS-B9: the live file is removed at session end
|
|
558
|
+
try:
|
|
559
|
+
(self.dir / "live.json").unlink(missing_ok=True)
|
|
560
|
+
except OSError:
|
|
561
|
+
self.failures += 1
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def session_sink(log: RunLog, req: Any, executor: str, *, tool_inputs: bool = True) -> LiveSink:
|
|
565
|
+
"""The sink for one session: journal and live file in its folder, `session_opened` into the run log."""
|
|
566
|
+
raw = (req.session_dir / "raw.jsonl") if req.session_dir is not None else None
|
|
567
|
+
|
|
568
|
+
transcript = {"engine": str(raw) if raw else None, "native": None, "native_kind": None}
|
|
569
|
+
|
|
570
|
+
def opened(data: dict[str, Any]) -> None:
|
|
571
|
+
log.write("session_opened", session_key=req.session_key, kind=req.kind, executor=executor,
|
|
572
|
+
alias=req.alias, model=data.get("model"), session_id=data.get("session_id"),
|
|
573
|
+
transcript=transcript, pgid=data.get("pgid"))
|
|
574
|
+
sink.write_meta(session_id=data.get("session_id"), model=data.get("model"), pgid=data.get("pgid"),
|
|
575
|
+
cli_version=data.get("cli_version"))
|
|
576
|
+
|
|
577
|
+
sink = LiveSink(req.session_dir, opened=opened, observers=log.observers, session_key=req.session_key,
|
|
578
|
+
tool_inputs=tool_inputs)
|
|
579
|
+
sink.write_meta(session_key=req.session_key, kind=req.kind, executor=executor, alias=req.alias,
|
|
580
|
+
transcript=transcript, started_at=now_iso(), ended_at=None)
|
|
581
|
+
return sink
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
@dataclass(kw_only=True)
|
|
585
|
+
class Ledger:
|
|
586
|
+
"""`<state root>/ledger.jsonl`: one metadata-only row per run segment and per intervention."""
|
|
587
|
+
|
|
588
|
+
path: Path
|
|
589
|
+
failures: int = 0
|
|
590
|
+
rows: list[dict[str, Any]] = field(default_factory=list)
|
|
591
|
+
|
|
592
|
+
def append(self, row: dict[str, Any]) -> None:
|
|
593
|
+
try:
|
|
594
|
+
append_jsonl(self.path, _jsonable({"ts": now_iso(), **row}))
|
|
595
|
+
except Exception: # noqa: BLE001
|
|
596
|
+
self.failures += 1
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def dumps(v: Any) -> str:
|
|
600
|
+
return json.dumps(_jsonable(v), ensure_ascii=False)
|