devflow-toolkit 0.4.7__py3-none-any.whl → 0.4.8__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.
@@ -303,7 +303,7 @@ class AntigravityAdapter(HarnessAdapter):
303
303
  [
304
304
  "During interactive Discovery, call the `ask_question` tool "
305
305
  "once per round with every independent pending decision, and "
306
- "use it for assumption acceptance. Respect the batch size "
306
+ "use it to approve agent proposals. Respect the batch size "
307
307
  "from the task prompt instead of asking one question at a "
308
308
  "time. Present the recorded options in the dialog instead of "
309
309
  "asking in free-form prose, and wait for the user's selection "
@@ -21,6 +21,8 @@ from devflow.adapters.instructions import (
21
21
  write_text_managed,
22
22
  )
23
23
  from devflow.core.safe_files import WORKFLOW_STATE_FILES
24
+ from devflow.adapters.usage_readers import claude_usage
25
+ from devflow.core.ports import Usage
24
26
 
25
27
 
26
28
  class ClaudeCodeAdapter(HarnessAdapter):
@@ -111,6 +113,9 @@ class ClaudeCodeAdapter(HarnessAdapter):
111
113
  )
112
114
  return Invocation(argv=argv, cwd=root, interactive=False)
113
115
 
116
+ def read_usage(self, context: RunContext, started_at: float) -> Usage | None:
117
+ return claude_usage(context.session_id)
118
+
114
119
  def new_session_id(self) -> str:
115
120
  """Claude Code accepts a UUID chosen by the caller (--session-id)."""
116
121
  return str(uuid.uuid4())
devflow/adapters/codex.py CHANGED
@@ -10,6 +10,8 @@ from devflow.adapters.base import (
10
10
  SetupContext,
11
11
  SetupResult,
12
12
  )
13
+ from devflow.adapters.usage_readers import codex_usage
14
+ from devflow.core.ports import Usage
13
15
  from devflow.adapters.instructions import (
14
16
  render_agent_instructions,
15
17
  write_gitignore_entries,
@@ -102,6 +104,10 @@ class CodexAdapter(HarnessAdapter):
102
104
  output_path=context.output_path,
103
105
  )
104
106
 
107
+ def read_usage(self, context: RunContext, started_at: float) -> Usage | None:
108
+ """Codex writes one session log per run; read the newest in the project."""
109
+ return codex_usage(context.root, started_at)
110
+
105
111
  def permission_warnings(
106
112
  self,
107
113
  context: RunContext,
@@ -19,6 +19,8 @@ from devflow.adapters.base import (
19
19
  SetupResult,
20
20
  )
21
21
  from devflow.core.ports import ModelOption
22
+ from devflow.adapters.usage_readers import opencode_usage
23
+ from devflow.core.ports import Usage
22
24
  from devflow.core.safe_files import WORKFLOW_STATE_FILES
23
25
  from devflow.adapters.instructions import (
24
26
  MANAGED_MARKER,
@@ -159,6 +161,9 @@ class OpenCodeAdapter(HarnessAdapter):
159
161
  )
160
162
  return Invocation(argv=argv, cwd=root, interactive=False)
161
163
 
164
+ def read_usage(self, context: RunContext, started_at: float) -> Usage | None:
165
+ return opencode_usage(context.session_id)
166
+
162
167
  def new_session_id(self) -> str:
163
168
  """Return an id in OpenCode's format: ``ses_`` + 12 hex + 14 base62."""
164
169
  alphabet = string.ascii_letters + string.digits
@@ -254,7 +259,7 @@ class OpenCodeAdapter(HarnessAdapter):
254
259
  [
255
260
  "During interactive Discovery, call the `question` tool once "
256
261
  "per round with every independent pending decision, and use "
257
- "it for assumption acceptance. Respect the batch size from "
262
+ "it to approve agent proposals. Respect the batch size from "
258
263
  "the task prompt instead of asking one question at a time. "
259
264
  "Present the recorded options in the dialog instead of asking "
260
265
  "in free-form prose, and wait for the user's selection before "
@@ -0,0 +1,177 @@
1
+ """Read token usage from the local records each harness keeps.
2
+
3
+ Every reader is best effort: it only reads the harness's own files, never
4
+ starts the harness or contacts a provider, and returns None when the
5
+ data is missing or its format is not recognised.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import sqlite3
13
+ from pathlib import Path
14
+
15
+ from devflow.core.ports import Usage
16
+
17
+ MAX_LOG_BYTES = 50_000_000
18
+
19
+
20
+ def _home(variable: str, default: Path) -> Path:
21
+ value = os.environ.get(variable, "").strip()
22
+ return Path(value).expanduser() if value else default
23
+
24
+
25
+ def codex_usage(root: Path, started_at: float) -> Usage | None:
26
+ """Return the usage of the newest Codex session started in ``root``.
27
+
28
+ Codex writes one ``rollout-*.jsonl`` file per session under
29
+ ``$CODEX_HOME/sessions``; its last ``token_count`` event holds the
30
+ session total.
31
+ """
32
+ sessions = _home("CODEX_HOME", Path.home() / ".codex") / "sessions"
33
+ if not sessions.is_dir():
34
+ return None
35
+ target = str(root.resolve())
36
+ candidates: list[tuple[float, Path]] = []
37
+ for path in sessions.rglob("rollout-*.jsonl"):
38
+ try:
39
+ info = path.stat()
40
+ except OSError:
41
+ continue
42
+ if info.st_mtime >= started_at - 1 and info.st_size <= MAX_LOG_BYTES:
43
+ candidates.append((info.st_mtime, path))
44
+ for _, path in sorted(candidates, reverse=True):
45
+ usage = _codex_file_usage(path, target)
46
+ if usage is not None:
47
+ return usage
48
+ return None
49
+
50
+
51
+ def _codex_file_usage(path: Path, target: str) -> Usage | None:
52
+ total: dict[str, object] | None = None
53
+ try:
54
+ with path.open(encoding="utf-8") as handle:
55
+ for index, line in enumerate(handle):
56
+ try:
57
+ entry = json.loads(line)
58
+ except ValueError:
59
+ continue
60
+ payload = entry.get("payload") if isinstance(entry, dict) else None
61
+ if not isinstance(payload, dict):
62
+ continue
63
+ if index == 0:
64
+ cwd = payload.get("cwd")
65
+ if entry.get("type") != "session_meta" or not isinstance(cwd, str):
66
+ return None
67
+ if str(Path(cwd).resolve()) != target:
68
+ return None
69
+ continue
70
+ if payload.get("type") == "token_count":
71
+ info = payload.get("info")
72
+ if isinstance(info, dict) and isinstance(
73
+ info.get("total_token_usage"), dict
74
+ ):
75
+ total = info["total_token_usage"]
76
+ except OSError:
77
+ return None
78
+ if total is None:
79
+ return None
80
+ cached = _int(total.get("cached_input_tokens"))
81
+ return Usage(
82
+ input_tokens=max(_int(total.get("input_tokens")) - cached, 0),
83
+ cached_tokens=cached,
84
+ output_tokens=_int(total.get("output_tokens")),
85
+ reasoning_tokens=_int(total.get("reasoning_output_tokens")),
86
+ )
87
+
88
+
89
+ def claude_usage(session_id: str | None) -> Usage | None:
90
+ """Sum the usage of a Claude Code session transcript.
91
+
92
+ Transcripts live in ``$CLAUDE_CONFIG_DIR/projects/<project>/<id>.jsonl``.
93
+ Streaming can repeat an assistant message, so each message id counts
94
+ once.
95
+ """
96
+ if not session_id:
97
+ return None
98
+ projects = _home("CLAUDE_CONFIG_DIR", Path.home() / ".claude") / "projects"
99
+ if not projects.is_dir():
100
+ return None
101
+ messages: dict[str, dict[str, object]] = {}
102
+ found = False
103
+ for path in projects.glob(f"*/{session_id}.jsonl"):
104
+ found = True
105
+ try:
106
+ if path.stat().st_size > MAX_LOG_BYTES:
107
+ continue
108
+ lines = path.read_text(encoding="utf-8").splitlines()
109
+ except OSError:
110
+ continue
111
+ for number, line in enumerate(lines):
112
+ try:
113
+ entry = json.loads(line)
114
+ except ValueError:
115
+ continue
116
+ message = entry.get("message") if isinstance(entry, dict) else None
117
+ if not isinstance(message, dict) or not isinstance(
118
+ message.get("usage"), dict
119
+ ):
120
+ continue
121
+ key = str(message.get("id") or f"line-{number}")
122
+ messages[key] = message["usage"]
123
+ if not found:
124
+ return None
125
+ usage = Usage()
126
+ for item in messages.values():
127
+ usage = usage + Usage(
128
+ input_tokens=_int(item.get("input_tokens"))
129
+ + _int(item.get("cache_creation_input_tokens")),
130
+ cached_tokens=_int(item.get("cache_read_input_tokens")),
131
+ output_tokens=_int(item.get("output_tokens")),
132
+ )
133
+ return usage
134
+
135
+
136
+ def opencode_usage(session_id: str | None) -> Usage | None:
137
+ """Read the totals OpenCode stores for a session in its database."""
138
+ if not session_id:
139
+ return None
140
+ database = os.environ.get("OPENCODE_DB", "").strip()
141
+ data_home = _home("XDG_DATA_HOME", Path.home() / ".local" / "share")
142
+ if database and database != ":memory:":
143
+ path = Path(database).expanduser()
144
+ if not path.is_absolute():
145
+ path = data_home / "opencode" / path
146
+ else:
147
+ path = data_home / "opencode" / "opencode.db"
148
+ if not path.is_file():
149
+ return None
150
+ try:
151
+ connection = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True)
152
+ except sqlite3.Error:
153
+ return None
154
+ try:
155
+ row = connection.execute(
156
+ "select cost, tokens_input, tokens_output, tokens_reasoning, "
157
+ "tokens_cache_read, tokens_cache_write from session where id = ?",
158
+ (session_id,),
159
+ ).fetchone()
160
+ except sqlite3.Error:
161
+ return None
162
+ finally:
163
+ connection.close()
164
+ if row is None:
165
+ return None
166
+ cost, entered, output, reasoning, cache_read, cache_write = row
167
+ return Usage(
168
+ input_tokens=_int(entered) + _int(cache_write),
169
+ cached_tokens=_int(cache_read),
170
+ output_tokens=_int(output),
171
+ reasoning_tokens=_int(reasoning),
172
+ cost_usd=float(cost) if isinstance(cost, (int, float)) and cost else None,
173
+ )
174
+
175
+
176
+ def _int(value: object) -> int:
177
+ return value if isinstance(value, int) and value > 0 else 0
@@ -10,10 +10,19 @@ from rich.console import Console
10
10
  from rich.markup import escape
11
11
 
12
12
  from devflow.commands.security import offer_security_tools
13
+ from devflow.commands.ui import (
14
+ language_of,
15
+ print_next_steps,
16
+ print_notes,
17
+ print_summary,
18
+ usage_text,
19
+ )
13
20
  from devflow.core.artifacts.errors import ArtifactError
14
21
  from devflow.core.config import ConfigError, ConfigManager
15
22
  from devflow.core.discovery import DiscoveryError
23
+ from devflow.core.ports import Usage
16
24
  from devflow.core.project import ProjectDetector
25
+ from devflow.core.usage import UsageStore
17
26
  from devflow.core.state import (
18
27
  StateError,
19
28
  UnsupportedStageError,
@@ -59,6 +68,42 @@ def approve(
59
68
  raise typer.Exit(code=1) from error
60
69
 
61
70
 
71
+ _TEXTS = {
72
+ "en": {
73
+ "approved": "Specification {id} approved",
74
+ "already": "Specification {id} was already approved",
75
+ "change": "Change",
76
+ "file": "File",
77
+ "status": "Workflow status",
78
+ "by": "Approved by",
79
+ "usage": "Total usage",
80
+ "states": {},
81
+ "bound": "The approval is bound to the current spec.md and "
82
+ "discovery.yaml. Editing them later marks the approval stale.",
83
+ "implement": "Ask your coding agent to implement it",
84
+ "implement_prompt": "Implement {path}",
85
+ "change_later": "To change or extend it later",
86
+ "what_to_add": "what to add or change",
87
+ },
88
+ "es": {
89
+ "approved": "Especificación {id} aprobada",
90
+ "already": "La especificación {id} ya estaba aprobada",
91
+ "change": "Cambio",
92
+ "file": "Archivo",
93
+ "status": "Estado",
94
+ "by": "Aprobada por",
95
+ "usage": "Consumo total",
96
+ "states": {"spec_approved": "aprobada"},
97
+ "bound": "La aprobación queda ligada al spec.md y al discovery.yaml "
98
+ "actuales. Si los editas después, la aprobación deja de valer.",
99
+ "implement": "Pide a tu agente de código que la implemente",
100
+ "implement_prompt": "Implementa {path}",
101
+ "change_later": "Para cambiarla o ampliarla más adelante",
102
+ "what_to_add": "qué añadir o cambiar",
103
+ },
104
+ }
105
+
106
+
62
107
  def _approve(spec_id: str, path: Path, stage: str) -> None:
63
108
  normalized = stage.strip().lower()
64
109
  if normalized != "spec":
@@ -76,31 +121,43 @@ def _approve(spec_id: str, path: Path, stage: str) -> None:
76
121
  )
77
122
  location = WorkflowLocator(config.specifications_path).find(spec_id)
78
123
  result = manager.approve(location, normalized)
79
- for warning in result.warnings:
80
- console.print(f"[yellow]Warning:[/yellow] {escape(warning)}")
124
+ language = config.documentation_language
125
+ t = _TEXTS[language_of(language)]
126
+ print_notes(console, language, result.warnings)
81
127
 
82
- if not result.changed:
83
- console.print(
84
- f"[bold]{result.stage.capitalize()} stage is already approved "
85
- f"for {location.change}.[/bold] No changes were made."
86
- )
87
- else:
88
- console.print(
89
- f"[bold green]{result.stage.capitalize()} approved for "
90
- f"{location.change}.[/bold green]"
91
- )
92
- console.print(
93
- f"[bold]Workflow status:[/bold] {result.state.status}"
94
- )
95
- for kind, digest in sorted(result.approval.artifacts.items()):
96
- console.print(
97
- f"[bold]Approval digest:[/bold] {kind} {digest}",
98
- soft_wrap=True,
99
- )
100
- console.print(
101
- "[dim]Approval is bound to the artifact digests above. "
102
- "Changing an approved artifact marks it stale and blocks the "
103
- "workflow until it is validated again.[/dim]"
128
+ spec_path = location.directory / "spec.md"
129
+ usage = UsageStore(config.root).get(location.change)
130
+ rows = [
131
+ (t["change"], location.change),
132
+ (t["file"], spec_path.relative_to(config.root).as_posix()),
133
+ (t["status"], t["states"].get(result.state.status, result.state.status)),
134
+ (t["by"], f"{result.approval.by} · {result.approval.at}"),
135
+ ]
136
+ if usage:
137
+ total = sum(usage.values(), Usage())
138
+ rows.append((t["usage"], usage_text(total, language)))
139
+ title = t["approved"] if result.changed else t["already"]
140
+ print_summary(console, title.format(id=location.spec_id), rows)
141
+ console.print(f"[dim]{escape(t['bound'])}[/dim]", soft_wrap=True)
142
+ print_next_steps(
143
+ console,
144
+ language,
145
+ [
146
+ (
147
+ t["implement"],
148
+ [
149
+ t["implement_prompt"].format(
150
+ path=spec_path.relative_to(config.root).as_posix()
151
+ )
152
+ ],
153
+ ),
154
+ (
155
+ t["change_later"],
156
+ [
157
+ f'devflow reopen {location.spec_id} --add "{t["what_to_add"]}"',
158
+ ],
159
+ ),
160
+ ],
104
161
  )
105
162
  if result.changed:
106
163
  # Implementation starts after the first approval: this is when
@@ -9,6 +9,7 @@ import typer
9
9
  from rich.console import Console
10
10
  from rich.markup import escape
11
11
 
12
+ from devflow.commands.ui import language_of, print_next_steps, print_summary
12
13
  from devflow.core.artifacts.errors import ArtifactError
13
14
  from devflow.core.config import ConfigError, ConfigManager
14
15
  from devflow.core.discovery import DiscoveryError
@@ -71,6 +72,59 @@ def reopen(
71
72
  raise typer.Exit(code=1) from error
72
73
 
73
74
 
75
+ _TEXTS = {
76
+ "en": {
77
+ "reopened": "Reopened {id} · the spec approval was withdrawn",
78
+ "reopened_discovery": "Reopened Discovery of {id}",
79
+ "change": "Change",
80
+ "file": "File",
81
+ "status": "Workflow status",
82
+ "states": {
83
+ "draft": "draft",
84
+ "awaiting_clarification": "awaiting_clarification",
85
+ },
86
+ "approval": "Approval",
87
+ "withdrawn": "withdrawn",
88
+ "archived": "Approved spec archived",
89
+ "recorded": "Recorded what to add",
90
+ "step_answer": "Answer the agent's new questions (interactive mode)",
91
+ "step_write": "Run it again to write the updated spec",
92
+ "step_review_approve": "Review the spec and approve it",
93
+ "tip_discovery": "Tip: add --auto to answer and write the spec in "
94
+ "one run.",
95
+ "step_edit": "Edit the spec yourself",
96
+ "step_register": "Let DevFlow validate and register your edit",
97
+ "tip_edit": 'To have the agent extend it instead: devflow reopen {id} '
98
+ '--add "what to add"',
99
+ },
100
+ "es": {
101
+ "reopened": "{id} reabierta · se retiró la aprobación",
102
+ "reopened_discovery": "Discovery de {id} reabierto",
103
+ "change": "Cambio",
104
+ "file": "Archivo",
105
+ "status": "Estado",
106
+ "states": {
107
+ "draft": "borrador (sin aprobar)",
108
+ "awaiting_clarification": "esperando tus respuestas",
109
+ },
110
+ "approval": "Aprobación",
111
+ "withdrawn": "retirada",
112
+ "archived": "Spec aprobada archivada",
113
+ "recorded": "Lo que quieres añadir",
114
+ "step_answer": "Responde las nuevas preguntas del agente "
115
+ "(modo interactivo)",
116
+ "step_write": "Ejecútalo otra vez para escribir la spec actualizada",
117
+ "step_review_approve": "Revisa la spec y apruébala",
118
+ "tip_discovery": "Consejo: con --auto respondes y se escribe la spec "
119
+ "en una sola ejecución.",
120
+ "step_edit": "Edita la spec tú mismo",
121
+ "step_register": "Deja que DevFlow valide y registre tu edición",
122
+ "tip_edit": 'Para que el agente la amplíe: devflow reopen {id} '
123
+ '--add "qué añadir"',
124
+ },
125
+ }
126
+
127
+
74
128
  def _reopen(
75
129
  spec_id: str,
76
130
  path: Path,
@@ -105,39 +159,42 @@ def _reopen(
105
159
 
106
160
  result = manager.reopen(location, discovery=discovery, addition=add)
107
161
 
162
+ language = config.documentation_language
163
+ t = _TEXTS[language_of(language)]
108
164
  if result.approval_withdrawn:
109
- console.print(
110
- f"[bold green]Reopened {location.change}.[/bold green] "
111
- "The spec approval was withdrawn."
112
- )
165
+ title = t["reopened"].format(id=location.spec_id)
113
166
  else:
114
- console.print(
115
- f"[bold green]Reopened Discovery of {location.change}."
116
- "[/bold green]"
117
- )
167
+ title = t["reopened_discovery"].format(id=location.spec_id)
168
+ spec_path = (location.directory / "spec.md").relative_to(config.root)
169
+ rows = [
170
+ (t["change"], location.change),
171
+ (t["file"], spec_path.as_posix()),
172
+ (t["status"], t["states"].get(result.state.status, result.state.status)),
173
+ ]
174
+ if result.approval_withdrawn:
175
+ rows.append((t["approval"], t["withdrawn"]))
118
176
  if result.archived is not None:
119
- console.print(
120
- "Approved spec archived: "
121
- f"{manager.store.display_path(result.archived)}"
177
+ rows.append(
178
+ (t["archived"], manager.store.display_path(result.archived))
122
179
  )
123
180
  if add.strip():
124
- console.print(f"Recorded what to add: {escape(add.strip())}")
125
- console.print(f"Workflow status: {result.state.status}")
181
+ rows.append((t["recorded"], add.strip()))
182
+ print_summary(console, title, rows, style="cyan")
126
183
 
127
184
  continue_command = f"devflow spec --continue {location.spec_id}"
185
+ approve_command = f"devflow approve {location.spec_id}"
128
186
  if discovery:
129
- console.print(
130
- f"\n[bold]Next:[/bold] {continue_command}\n"
131
- "[dim]The agent asks you about the new decisions (interactive "
132
- "mode). Run the same command again to write the extended spec, "
133
- f"then approve it with devflow approve {location.spec_id}.[/dim]"
134
- )
187
+ steps = [
188
+ (t["step_answer"], [continue_command]),
189
+ (t["step_write"], [continue_command]),
190
+ (t["step_review_approve"], [approve_command]),
191
+ ]
192
+ tip = t["tip_discovery"]
135
193
  else:
136
- console.print(
137
- "\n[bold]Next:[/bold] edit spec.md yourself, then "
138
- f"{continue_command}\n"
139
- "[dim]DevFlow validates and registers your edited spec; approve it "
140
- f"again with devflow approve {location.spec_id}. To have the agent "
141
- f"extend it instead, run devflow reopen {location.spec_id} --add "
142
- '"what to add".[/dim]'
143
- )
194
+ steps = [
195
+ (t["step_edit"], [spec_path.as_posix()]),
196
+ (t["step_register"], [continue_command]),
197
+ (t["step_review_approve"], [approve_command]),
198
+ ]
199
+ tip = t["tip_edit"].format(id=location.spec_id)
200
+ print_next_steps(console, language, steps, tip=tip)