overcode 0.6.4__py3-none-any.whl → 0.6.5__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.
Files changed (110) hide show
  1. overcode/agent_identity.py +5 -0
  2. overcode/backends/grok_stats.py +2 -2
  3. overcode/budget_gate.py +27 -3
  4. overcode/bundled_skills.py +26 -0
  5. overcode/child_lifecycle.py +38 -15
  6. overcode/claude_bg.py +11 -0
  7. overcode/cli/__init__.py +2 -0
  8. overcode/cli/_shared.py +16 -0
  9. overcode/cli/agent.py +81 -5
  10. overcode/cli/budget.py +112 -5
  11. overcode/cli/doctor.py +7 -0
  12. overcode/cli/gateway.py +463 -0
  13. overcode/cli/spend.py +428 -0
  14. overcode/columns/column.py +12 -0
  15. overcode/columns/context.py +38 -0
  16. overcode/columns/hover.py +47 -0
  17. overcode/columns/layout.py +3 -1
  18. overcode/columns/registry.py +113 -9
  19. overcode/columns/render_usage.py +86 -2
  20. overcode/columns/render_virtual.py +24 -0
  21. overcode/config.py +233 -2
  22. overcode/daemon_housekeeping.py +80 -0
  23. overcode/docs/README.md +34 -15
  24. overcode/docs/backends.md +1 -1
  25. overcode/docs/children.md +10 -0
  26. overcode/docs/claude-session-files.md +1 -1
  27. overcode/docs/cli-reference.md +8 -0
  28. overcode/docs/configuration.md +30 -8
  29. overcode/docs/design/483-484/00_overview.md +1 -1
  30. overcode/docs/design/README.md +58 -84
  31. overcode/docs/design/agent-agnostic-backends-opencode.md +4 -4
  32. overcode/docs/design/agent-backends-codex-grok.md +8 -8
  33. overcode/docs/design/{acp-agent-integration-analysis.md → archive/acp-agent-integration-analysis.md} +3 -1
  34. overcode/docs/design/{bakeoffs → archive/bakeoffs}/README.md +2 -0
  35. overcode/docs/design/{bakeoffs → archive/bakeoffs}/SYNTHESIS.md +2 -0
  36. overcode/docs/design/{bakeoffs → archive/bakeoffs}/candidates.md +2 -0
  37. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-bernstein.md +2 -0
  38. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-bobbit.md +2 -0
  39. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-ccmanager.md +2 -0
  40. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-claude-squad.md +3 -1
  41. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-cmux.md +2 -0
  42. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-composio.md +2 -0
  43. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-dmux.md +2 -0
  44. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-gastown.md +2 -0
  45. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-kagan.md +2 -0
  46. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-orca.md +2 -0
  47. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-superset.md +2 -0
  48. overcode/docs/design/{bakeoffs → archive/bakeoffs}/overcode-vs-vibe-kanban.md +2 -0
  49. overcode/docs/design/{bakeoffs → archive/bakeoffs}/zellij-vs-tmux.md +2 -0
  50. overcode/docs/design/archive/budget-columns-review.md +97 -0
  51. overcode/docs/design/archive/code-quality-audit-2026-03.md +596 -0
  52. overcode/docs/design/{opencode-parity.md → archive/opencode-parity.md} +2 -0
  53. overcode/docs/design/{opencode-stats-reader-performance.md → archive/opencode-stats-reader-performance.md} +2 -0
  54. overcode/docs/design/{quality-review-2026-10.md → archive/quality-review-2026-10.md} +2 -0
  55. overcode/docs/design/{scaling-audit-2026-09-22.md → archive/scaling-audit-2026-09-22/scaling-audit-2026-09-22.md} +3 -1
  56. overcode/docs/{tui-refactoring-plan.md → design/archive/tui-refactoring-plan.md} +2 -0
  57. overcode/docs/{ux-performance-analysis-2026-03-09.md → design/archive/ux-performance-analysis-2026-03-09.md} +2 -0
  58. overcode/docs/design/billing-code-ids.md +2 -2
  59. overcode/docs/design/cost-model-0.6.1.md +1 -1
  60. overcode/docs/design/e2e-devcontainer-testing.md +3 -3
  61. overcode/docs/design/experiment-billing.md +408 -0
  62. overcode/docs/experiment-billing.md +290 -0
  63. overcode/docs/release-notes-0.6.1.md +6 -47
  64. overcode/docs/{release-notes-0.5.1.md → releases/release-notes-0.5.1.md} +1 -1
  65. overcode/docs/{release-notes-0.6.0.md → releases/release-notes-0.6.0.md} +1 -1
  66. overcode/docs/releases/release-notes-0.6.1.md +49 -0
  67. overcode/docs/releases/release-notes-0.6.5.md +33 -0
  68. overcode/docs/tui-guide.md +19 -4
  69. overcode/doctor.py +53 -0
  70. overcode/ext_spend_view.py +99 -0
  71. overcode/external_spend.py +586 -0
  72. overcode/gateway.py +559 -0
  73. overcode/gateway_server.py +908 -0
  74. overcode/gateway_supervisor.py +262 -0
  75. overcode/job_launcher.py +11 -1
  76. overcode/launcher.py +20 -4
  77. overcode/ledger.py +80 -28
  78. overcode/monitor_daemon.py +40 -4
  79. overcode/monitor_daemon_state.py +12 -2
  80. overcode/secrets_store.py +185 -0
  81. overcode/session_manager.py +32 -4
  82. overcode/settings.py +5 -0
  83. overcode/spend_client.py +211 -0
  84. overcode/swarm.py +111 -5
  85. overcode/swarm_publisher.py +5 -1
  86. overcode/tui.py +1 -0
  87. overcode/tui_actions/view.py +5 -5
  88. overcode/tui_engine.py +3 -2
  89. overcode/tui_widgets/daemon_status_bar.py +7 -2
  90. overcode/tui_widgets/summary_config_modal.py +1 -1
  91. overcode/upgrade_consent.py +2 -2
  92. overcode/wrapper.py +8 -2
  93. {overcode-0.6.4.dist-info → overcode-0.6.5.dist-info}/METADATA +1 -1
  94. {overcode-0.6.4.dist-info → overcode-0.6.5.dist-info}/RECORD +110 -95
  95. /overcode/docs/{release-notes-0.3.0.md → releases/release-notes-0.3.0.md} +0 -0
  96. /overcode/docs/{release-notes-0.4.2.md → releases/release-notes-0.4.2.md} +0 -0
  97. /overcode/docs/{release-notes-0.5.2.md → releases/release-notes-0.5.2.md} +0 -0
  98. /overcode/docs/{release-notes-0.5.3.md → releases/release-notes-0.5.3.md} +0 -0
  99. /overcode/docs/{release-notes-0.5.4.md → releases/release-notes-0.5.4.md} +0 -0
  100. /overcode/docs/{release-notes-0.5.5.md → releases/release-notes-0.5.5.md} +0 -0
  101. /overcode/docs/{release-notes-0.5.6.md → releases/release-notes-0.5.6.md} +0 -0
  102. /overcode/docs/{release-notes-0.5.7.md → releases/release-notes-0.5.7.md} +0 -0
  103. /overcode/docs/{release-notes-0.5.8.md → releases/release-notes-0.5.8.md} +0 -0
  104. /overcode/docs/{release-notes-0.6.2.md → releases/release-notes-0.6.2.md} +0 -0
  105. /overcode/docs/{release-notes-0.6.3.md → releases/release-notes-0.6.3.md} +0 -0
  106. /overcode/docs/{release-notes-0.6.4.md → releases/release-notes-0.6.4.md} +0 -0
  107. {overcode-0.6.4.dist-info → overcode-0.6.5.dist-info}/WHEEL +0 -0
  108. {overcode-0.6.4.dist-info → overcode-0.6.5.dist-info}/entry_points.txt +0 -0
  109. {overcode-0.6.4.dist-info → overcode-0.6.5.dist-info}/licenses/LICENSE +0 -0
  110. {overcode-0.6.4.dist-info → overcode-0.6.5.dist-info}/top_level.txt +0 -0
@@ -27,6 +27,11 @@ def env_agent_name(env: Optional[Mapping[str, str]] = None) -> Optional[str]:
27
27
  # the agent (its reports, hooks and state access are its own).
28
28
  JOB_OWNER_VAR = "OVERCODE_JOB_OWNER_ID"
29
29
 
30
+ # The agent spend recorded from this process bills to (experiment billing,
31
+ # ``external_spend``): set by an agent's ``overcode bash`` job, or by hand.
32
+ # Cleared from launch lines: an agent bills its own evals.
33
+ BILL_TO_VAR = "OVERCODE_BILL_TO"
34
+
30
35
 
31
36
  def env_job_owner_id(env: Optional[Mapping[str, str]] = None) -> Optional[str]:
32
37
  """The id of the agent whose job this process runs in, or None."""
@@ -13,7 +13,7 @@ needs across a few files inside one per-session directory:
13
13
  tagged with the owning session id
14
14
 
15
15
  Two things §3.4 flagged as unconfirmed were determined empirically against a
16
- real 413-message session (``01a015cb-...`` under the xway project dir) before
16
+ real 413-message session (``01a015cb-...`` under a real project dir) before
17
17
  this reader was written, and are recorded here rather than left as a Phase 4
18
18
  guess:
19
19
 
@@ -167,7 +167,7 @@ class _UpdatesFold:
167
167
  return
168
168
 
169
169
  # `_meta` sits inside `params`, not at the envelope's top level —
170
- # confirmed against the real xway session file (413-message,
170
+ # confirmed against the real session file (413-message,
171
171
  # module docstring), which has zero top-level `_meta` keys.
172
172
  params = entry.get("params")
173
173
  meta = params.get("_meta") if isinstance(params, dict) else None
overcode/budget_gate.py CHANGED
@@ -40,14 +40,38 @@ PERMIT_SECONDS = 120.0
40
40
  REJECTED_ACTIVITY = "Prompt blocked: over its cost budget"
41
41
 
42
42
 
43
+ def _amount(stats, key: str) -> float:
44
+ if stats is None:
45
+ return 0.0
46
+ value = stats.get(key, 0.0) if isinstance(stats, dict) else getattr(stats, key, 0.0)
47
+ try:
48
+ return float(value or 0.0)
49
+ except (TypeError, ValueError):
50
+ return 0.0
51
+
52
+
53
+ def external_cost(stats) -> float:
54
+ """What an agent is charged for evals and sims it ran (``external_spend``)."""
55
+ return _amount(stats, "external_cost_usd")
56
+
57
+
58
+ def charged_cost(stats) -> float:
59
+ """What an agent's budget is charged: its own estimated cost plus its
60
+ external spend (evals and sims it ran, ``external_spend``).
61
+
62
+ ``stats`` is a ``SessionStats`` or its dict (a sessions.json record's).
63
+ """
64
+ return _amount(stats, "estimated_cost_usd") + external_cost(stats)
65
+
66
+
43
67
  def is_budget_exceeded(session, stats=None) -> bool:
44
- """Whether ``session``'s estimated cost has reached its budget (#173).
68
+ """Whether ``session``'s charged cost (own plus external) has reached its budget (#173).
45
69
 
46
70
  ``stats`` defaults to the session's own.
47
71
  """
48
72
  try:
49
73
  budget = session.cost_budget_usd
50
- cost = (stats if stats is not None else session.stats).estimated_cost_usd
74
+ cost = charged_cost(stats if stats is not None else session.stats)
51
75
  return isinstance(budget, (int, float)) and budget > 0 and cost >= budget
52
76
  except (AttributeError, TypeError):
53
77
  return False
@@ -76,7 +100,7 @@ def refusal(session, sessions=None) -> Optional[str]:
76
100
  return None # its own host's overcode gates it
77
101
  if not is_budget_exceeded(session):
78
102
  return None
79
- cost = session.stats.estimated_cost_usd
103
+ cost = charged_cost(session.stats)
80
104
  budget = session.cost_budget_usd
81
105
  return (f"'{session.name}' is over its cost budget (${cost:.2f} of ${budget:.2f}): "
82
106
  f"not sent. Raise it with: {raise_hint(session, sessions)}")
@@ -125,6 +125,25 @@ output), not a hand-rolled `until … grep …; do sleep N; done` loop: `wait`
125
125
  returns when the job ends, so it can't poll forever on a job that failed or
126
126
  never started.
127
127
 
128
+ ## Spend outside your conversation (evals, rentals)
129
+
130
+ When overcode runs a spend gateway, your gateway token is in your env
131
+ (`$OVERCODE_GATEWAY_TOKEN`, and `OPENAI_API_KEY` on Claude Code): evals you
132
+ start inherit it and are billed to you and your budget.
133
+ - Run evals with `overcode spend run -- python eval.py`: it sets the
134
+ gateway's variables (OpenAI SDKs: `OPENAI_BASE_URL`, `OPENAI_API_KEY`) for
135
+ that command, and works from cron, nohup or a container too
136
+ (`overcode spend run --agent <you> -- …`).
137
+ - Giving a subagent eval work? Tell it to run them with
138
+ `overcode spend run --sub <label> -- …`, or run `overcode spend token --sub <label>`
139
+ and put the token in its prompt as its `OPENAI_API_KEY`.
140
+ - Renting something (GPU, box) that bills by time? Schedule
141
+ `overcode spend record --resource … --rate 2.40/h --period <start>/1h --category compute`
142
+ once per period while it runs, and stop when you release it. A repeated
143
+ period is a no-op.
144
+ - A 429 `overcode_budget_exceeded`, or `spend record` exiting 3, means you are
145
+ out of budget: stop spending (and release rentals), or ask for more.
146
+
128
147
  ## If you are a child
129
148
 
130
149
  Do the task in your prompt, then run the `overcode report` line it gave you, or
@@ -132,6 +151,13 @@ Do the task in your prompt, then run the `overcode report` line it gave you, or
132
151
  may be blocked waiting on you and can't answer questions, so make reasonable
133
152
  calls yourself and mention them in `--reason`.
134
153
 
154
+ Report last, as the final step of your turn: a report says you are finished.
155
+ Before it, wait for (or kill) every child agent, overcode job and background
156
+ shell you started. `overcode report` refuses while your own children or jobs
157
+ are still running; `--force` only for ones meant to outlive you. If you are
158
+ given more work after reporting, you go back to running and the report is set
159
+ aside: report again when that work is done.
160
+
135
161
  ## More
136
162
 
137
163
  `overcode <command> --help` documents every command and flag.
@@ -15,6 +15,7 @@ Either way the child is *at rest* (⚪): the light says it stopped, and
15
15
 
16
16
  import json
17
17
  import os
18
+ import time
18
19
  from typing import Iterable, Optional, Tuple
19
20
 
20
21
  from .paths import agent_path
@@ -122,12 +123,19 @@ def settled_child_status(session, stopped: Optional[bool] = None) -> Optional[st
122
123
  return status if status != session.status else None
123
124
 
124
125
 
125
- def done_since(session) -> Optional[float]:
126
+ def done_since(session, now: Optional[float] = None) -> Optional[float]:
126
127
  """When a done child finished (epoch seconds), or None if unknown.
127
128
 
128
- Its report's mtime, or the oversight deadline that expired; the later
129
- of the two when both exist.
129
+ ``done_at``, stamped when it went done. A record from before that stamp
130
+ falls back to its report's mtime, or the oversight deadline once it has
131
+ expired; the later of the two. A deadline still ahead is not when it
132
+ finished: a reported child keeps its deadline, and taking a future one
133
+ hid every event until it passed (a done child at work for hours).
130
134
  """
135
+ done_at = getattr(session, "done_at", None)
136
+ if done_at:
137
+ return float(done_at)
138
+ now = time.time() if now is None else now
131
139
  times = []
132
140
  report_file = agent_path(session.tmux_session, session.id, session.name, "report",
133
141
  base=get_session_dir(session.tmux_session))
@@ -136,28 +144,43 @@ def done_since(session) -> Optional[float]:
136
144
  except OSError:
137
145
  pass
138
146
  deadline_at = getattr(session, "oversight_deadline_at", None)
139
- if deadline_at:
147
+ if deadline_at and float(deadline_at) <= now:
140
148
  times.append(float(deadline_at))
141
149
  return max(times) if times else None
142
150
 
143
151
 
144
- def resumed_after_done(session, hook_state: Optional[dict]) -> bool:
152
+ def _resume_at(event: object) -> Optional[float]:
153
+ """The timestamp of a hook event that means work, or None."""
154
+ if not isinstance(event, dict) or event.get("event") not in RESUME_EVENTS:
155
+ return None
156
+ try:
157
+ return float(event["timestamp"])
158
+ except (KeyError, TypeError, ValueError):
159
+ return None
160
+
161
+
162
+ def resumed_after_done(session, hook_state: Optional[dict],
163
+ recent_events: Iterable[dict] = (),
164
+ now: Optional[float] = None) -> bool:
145
165
  """True if a done child is at work again (#556).
146
166
 
147
- ``hook_state`` is the child's last hook event. A done child settled on a
148
- Stop, so a prompt or tool event newer than the moment it finished means
149
- it was given more work (``overcode send``, or typed into its pane).
167
+ A prompt or tool event newer than the moment it went done means it was
168
+ given more work (``overcode send``, or typed into its pane). ``hook_state``
169
+ is its last hook event; ``recent_events`` the tail of its event log, so a
170
+ turn that started and ended between two daemon ticks (last event a Stop
171
+ again) still counts. The log is read only with ``done_at``: before it,
172
+ the moment is the report's mtime, and the report's own tool call and
173
+ the rest of that turn come after it.
150
174
  """
151
175
  if session.parent_session_id is None or session.status != "done":
152
176
  return False
153
- if not isinstance(hook_state, dict) or hook_state.get("event") not in RESUME_EVENTS:
154
- return False
155
- try:
156
- at = float(hook_state["timestamp"])
157
- except (KeyError, TypeError, ValueError):
177
+ since = done_since(session, now)
178
+ if since is None:
158
179
  return False
159
- since = done_since(session)
160
- return since is not None and at > since
180
+ events = [hook_state]
181
+ if getattr(session, "done_at", None):
182
+ events.extend(recent_events or ())
183
+ return any((at := _resume_at(e)) is not None and at > since for e in events)
161
184
 
162
185
 
163
186
  def task_result(session, status: Optional[str] = None) -> Tuple[Optional[str], str]:
overcode/claude_bg.py CHANGED
@@ -243,6 +243,12 @@ class FleetAgent:
243
243
  branch: Optional[str] = None
244
244
  billing_code: Optional[str] = None # what its 🌙 rows' spend is billed to (the name)
245
245
  billing_code_id: Optional[str] = None # ... and the code's id
246
+ # Whether a session may be given to it by place alone (its directory or
247
+ # repository). False for a shell row: it runs no Claude, so only its
248
+ # hooks or a conversation id can say a background session is its; else
249
+ # every 🌙 session in a repo where a terminal sits was billed to the
250
+ # terminal's code
251
+ by_place: bool = True
246
252
 
247
253
 
248
254
  @lru_cache(maxsize=1024)
@@ -325,6 +331,7 @@ def attribute(job: Mapping[str, Any], agents: Iterable[FleetAgent]
325
331
  2. It continues one of the agent's own conversations (``sessionId`` or
326
332
  ``resumeSessionId``).
327
333
  3. Its ``cwd`` is inside the agent's directory (the deepest one wins).
334
+ Steps 3 and 4 skip shell rows (``by_place``): a terminal runs no Claude.
328
335
  4. Its ``cwd`` is a git worktree of the repository an agent works in
329
336
  (``repo_of``: same ``--git-common-dir``), wherever it lives: the
330
337
  agent in that repository's main checkout, else the shallowest
@@ -345,6 +352,7 @@ def attribute(job: Mapping[str, Any], agents: Iterable[FleetAgent]
345
352
  return agent, VIA_CONVERSATION
346
353
  if not isinstance(cwd, str) or not cwd:
347
354
  return None
355
+ agents = [a for a in agents if a.by_place]
348
356
  best: Optional[FleetAgent] = None
349
357
  best_len = -1
350
358
  for agent in agents:
@@ -977,6 +985,8 @@ def fleet_agents(sessions: Iterable[Any], foreign_of=None) -> List[FleetAgent]:
977
985
  detector's ``get_foreign_sessions``). Terminated and done agents have
978
986
  no repo in use any more.
979
987
  """
988
+ from .backends.shell import is_shell_session
989
+
980
990
  out = []
981
991
  for s in sessions:
982
992
  if getattr(s, "status", None) in ("terminated", "done"):
@@ -994,6 +1004,7 @@ def fleet_agents(sessions: Iterable[Any], foreign_of=None) -> List[FleetAgent]:
994
1004
  branch=getattr(s, "branch", None),
995
1005
  billing_code=getattr(s, "billing_code", None) or s.name,
996
1006
  billing_code_id=getattr(s, "billing_code_id", None),
1007
+ by_place=not is_shell_session(s),
997
1008
  ))
998
1009
  return out
999
1010
 
overcode/cli/__init__.py CHANGED
@@ -14,6 +14,8 @@ from ..launcher import AgentLauncher # noqa: F401
14
14
  # Import submodules to register their commands with the Typer apps
15
15
  from . import agent # noqa: F401
16
16
  from . import budget # noqa: F401
17
+ from . import spend # noqa: F401
18
+ from . import gateway # noqa: F401
17
19
  from . import hooks # noqa: F401
18
20
  from . import skills # noqa: F401
19
21
  from . import skill_profiles # noqa: F401
overcode/cli/_shared.py CHANGED
@@ -84,6 +84,22 @@ billing_app = typer.Typer(
84
84
  )
85
85
  app.add_typer(billing_app, name="billing")
86
86
 
87
+ # Spend outside agents' conversations: evals and sims (experiment billing)
88
+ spend_app = typer.Typer(
89
+ name="spend",
90
+ help="Record spend an agent's evals and sims made outside its conversation.",
91
+ no_args_is_help=True,
92
+ )
93
+ app.add_typer(spend_app, name="spend")
94
+
95
+ # The local spend gateway (experiment billing)
96
+ gateway_app = typer.Typer(
97
+ name="gateway",
98
+ help="Run the local spend gateway: an OpenAI-compatible proxy that meters evals by token.",
99
+ no_args_is_help=True,
100
+ )
101
+ app.add_typer(gateway_app, name="gateway")
102
+
87
103
  # Sister subcommand group
88
104
  sister_app = typer.Typer(
89
105
  name="sister",
overcode/cli/agent.py CHANGED
@@ -750,6 +750,13 @@ def list_agents(
750
750
  joules: Annotated[
751
751
  bool, typer.Option("--joules", help="Show energy in joules instead of token counts")
752
752
  ] = False,
753
+ ext: Annotated[
754
+ bool, typer.Option("--ext", help="Add EXT: spend outside each agent's conversation "
755
+ "(evals, rentals; experiment billing)")
756
+ ] = False,
757
+ ext_split: Annotated[
758
+ bool, typer.Option("--ext-split", help="EXT as a column per category (llm, compute...)")
759
+ ] = False,
753
760
  sisters: Annotated[
754
761
  bool, typer.Option("--sisters", help="Include sister (remote) agents")
755
762
  ] = False,
@@ -1119,14 +1126,21 @@ def list_agents(
1119
1126
  from ..summary_columns import uniform_columns
1120
1127
  shared = uniform_columns(row_contexts)
1121
1128
 
1129
+ ext_family = {"ext_split", "ext_cat_2", "ext_cat_3", "ext_cat_4", "ext_cat_5",
1130
+ "ext_cat_6", "ext_cat_more"}
1131
+
1122
1132
  def col_filter(col):
1133
+ if ext_split and col.id in ext_family:
1134
+ return True
1135
+ if (ext and not ext_split) and col.id == "eval_cost":
1136
+ return True
1123
1137
  return detail in col.detail_levels and col.id not in shared
1124
1138
 
1125
1139
  all_cells = [render_summary_cells(ctx, column_filter=col_filter) for ctx in row_contexts]
1126
1140
 
1127
1141
  # Auto-align columns across all rows, then append activity
1128
1142
  widths = compute_column_widths(all_cells)
1129
- header = render_header_cells(column_filter=col_filter, column_widths=widths)
1143
+ header = render_header_cells(column_filter=col_filter, column_widths=widths, fleet=fleet)
1130
1144
  header.truncate(console.width, pad=False)
1131
1145
  console.print(header, no_wrap=True)
1132
1146
  aligned_lines = [pad_and_join_cells(row, widths) for row in all_cells]
@@ -1581,6 +1595,43 @@ def rename(
1581
1595
  rprint(f"[green]Renamed agent: {name} → {new_name} (conversation preserved)[/green]")
1582
1596
 
1583
1597
 
1598
+ def _still_running(sm, session, tmux_session: str) -> list:
1599
+ """What ``session`` started that is still running: its child agents at
1600
+ work and its overcode jobs, one line each (``overcode report``'s guard).
1601
+
1602
+ A child's status is the daemon's when it is fresh, its record's otherwise.
1603
+ """
1604
+ from ..child_lifecycle import CHILD_NOT_WORKING
1605
+ from ..monitor_daemon_state import get_monitor_daemon_state
1606
+
1607
+ lines = []
1608
+ children = sm.get_children(session.id)
1609
+ if children:
1610
+ daemon_state = None
1611
+ try:
1612
+ daemon_state = get_monitor_daemon_state(tmux_session)
1613
+ if daemon_state is not None and daemon_state.is_stale():
1614
+ daemon_state = None
1615
+ except Exception:
1616
+ daemon_state = None
1617
+ for child in children:
1618
+ status = child.status
1619
+ if daemon_state is not None:
1620
+ published = daemon_state.get_session(child.id)
1621
+ if published is not None and published.current_status:
1622
+ status = published.current_status
1623
+ if status not in CHILD_NOT_WORKING:
1624
+ lines.append(f"child agent {child.name} ({status})")
1625
+ try:
1626
+ from ..job_manager import JobManager
1627
+ for job in JobManager().list_jobs():
1628
+ if job.agent_session_id == session.id and job.status == "running":
1629
+ lines.append(f"job {job.name}")
1630
+ except Exception:
1631
+ pass
1632
+ return lines
1633
+
1634
+
1584
1635
  @app.command()
1585
1636
  def report(
1586
1637
  status: Annotated[
@@ -1591,6 +1642,10 @@ def report(
1591
1642
  Optional[str],
1592
1643
  typer.Option("--reason", "-r", help="Reason for the report"),
1593
1644
  ] = None,
1645
+ force: Annotated[
1646
+ bool,
1647
+ typer.Option("--force", help="Report even with child agents or jobs still running"),
1648
+ ] = False,
1594
1649
  ):
1595
1650
  """Report completion status from a child agent.
1596
1651
 
@@ -1598,6 +1653,16 @@ def report(
1598
1653
  Reads OVERCODE_SESSION_NAME and OVERCODE_TMUX_SESSION from env vars
1599
1654
  (automatically set for all child agents).
1600
1655
 
1656
+ Report last: once your work is finished and nothing you started is
1657
+ still running. A report marks you done when your turn ends. While your
1658
+ own child agents or overcode jobs are still running it is refused
1659
+ (exit 1, nothing filed): wait for them, or kill them, or pass --force
1660
+ if they are meant to outlive you. Background shells you started are
1661
+ not checked, so end or wait for those yourself.
1662
+
1663
+ Given more work after reporting (a new prompt), you go back to
1664
+ running and the report is set aside: report again when that is done.
1665
+
1601
1666
  Examples:
1602
1667
  overcode report --status success
1603
1668
  overcode report --status failure --reason "Tests failed"
@@ -1618,6 +1683,21 @@ def report(
1618
1683
  rprint("[dim]This command should be run from within a child agent launched by overcode[/dim]")
1619
1684
  raise typer.Exit(code=1)
1620
1685
 
1686
+ from ..agent_identity import current_agent
1687
+ from ..session_manager import SessionManager
1688
+ sm = SessionManager()
1689
+ session = current_agent(sm)
1690
+
1691
+ if session and not force:
1692
+ outstanding = _still_running(sm, session, tmux_session)
1693
+ if outstanding:
1694
+ rprint("[red]Not reported: still running[/red]")
1695
+ for line in outstanding:
1696
+ rprint(f" {line}")
1697
+ rprint("[dim]Wait for these (overcode follow / jobs), kill them, or pass "
1698
+ "--force if they are meant to outlive this report.[/dim]")
1699
+ raise typer.Exit(code=1)
1700
+
1621
1701
  # Write the report in the agent's own directory (agents/<id>/, item 35)
1622
1702
  from ..hook_handler import agent_file_for_write
1623
1703
  report_file = agent_file_for_write(
@@ -1632,10 +1712,6 @@ def report(
1632
1712
 
1633
1713
  # Also update session fields for persistence: the agent by its id (its
1634
1714
  # launch name is stale after a rename), by name only for a pre-0.6 agent
1635
- from ..agent_identity import current_agent
1636
- from ..session_manager import SessionManager
1637
- sm = SessionManager()
1638
- session = current_agent(sm)
1639
1715
  if session:
1640
1716
  sm.update_session(
1641
1717
  session.id,
overcode/cli/budget.py CHANGED
@@ -186,9 +186,13 @@ def budget_show(
186
186
  rprint("[dim]No running agents[/dim]")
187
187
  return
188
188
 
189
+ from ..budget_gate import charged_cost
190
+
189
191
  for agent in agents:
190
192
  budget = agent.cost_budget_usd
191
- spent = agent.stats.estimated_cost_usd
193
+ # Its evals and sims count against its budget (experiment billing)
194
+ spent = charged_cost(agent.stats)
195
+ external = float(getattr(agent.stats, "external_cost_usd", 0.0) or 0.0)
192
196
  budget_str = f"${budget:.2f}" if budget > 0 else "unlimited"
193
197
  spent_str = f"${spent:.4f}"
194
198
 
@@ -203,11 +207,13 @@ def budget_show(
203
207
  children = manager.get_descendants(agent.id)
204
208
  # Released children's spend until their release stays here (#520)
205
209
  carried = sum(_released_cost(a) for a in [agent, *children])
206
- subtree_spend = spent + sum(c.stats.estimated_cost_usd for c in children) + carried
210
+ subtree_spend = spent + sum(charged_cost(c.stats) for c in children) + carried
207
211
 
208
212
  depth = manager.compute_depth(agent)
209
213
  indent = " " * depth
210
214
  line = f" {indent}{agent.name:<16} budget={budget_str:<10} spent={spent_str:<10} {status}"
215
+ if external > 0:
216
+ line += f" (evals: ${external:.4f})"
211
217
  if children or carried > 0:
212
218
  line += f" (subtree: ${subtree_spend:.4f})"
213
219
  print(line)
@@ -344,26 +350,127 @@ def billing(
344
350
  # Claude background sessions billed to a code are among its agents
345
351
  background = any(entry.get("background") for _, entry in rows)
346
352
  bg_head = " background" if background else ""
353
+ # Spend outside agents' conversations (evals, sims: external_spend), part of cost
354
+ evals = any(entry.get("runs") for _, entry in rows)
355
+ # ...split by category (llm, compute, storage, other, or an agent's own word)
356
+ cat_totals: dict = {}
357
+ for _, entry in rows:
358
+ for cat, usd in (entry.get("ext_by") or {}).items():
359
+ cat_totals[cat] = cat_totals.get(cat, 0.0) + usd
360
+ cats = [c for c in sorted(cat_totals, key=lambda c: (-cat_totals[c], c)) if abs(cat_totals[c]) > 1e-9]
361
+ ev_head = (f" {'own':>10} {'external':>10}" + "".join(f" {c[:10]:>10}" for c in cats)
362
+ + f" {'runs':>4}") if evals else ""
347
363
  q_head = f" {quota['label']:>9}" if quota is not None else ""
348
364
  id_head = f" {'id':<34}" if ids else ""
349
- print(f" {'code':<{width}} {'cost':>10} {'tokens':>8}{q_head} {'agents':>6} running"
365
+ print(f" {'code':<{width}} {'cost':>10}{ev_head} {'tokens':>8}{q_head} {'agents':>6} running"
350
366
  f"{bg_head}{id_head}")
351
367
  for code, entry in rows:
352
368
  bg_cell = f" {entry.get('background', 0):>10}" if background else ""
353
369
  q_cell = f" {format_pp(entry.get('quota_pp', 0.0)):>9}" if quota is not None else ""
354
370
  id_cell = f" {code if is_code_id(code) else '(no id)':<34}" if ids else ""
355
- print(f" {entry['name']:<{width}} ${entry['cost']:>9.2f} {format_tokens(entry['tokens']):>8}"
371
+ ext = entry.get("ext_cost", 0.0)
372
+ ev_cell = (f" ${entry['cost'] - ext:>9.2f} ${ext:>9.2f}"
373
+ + "".join(f" ${(entry.get('ext_by') or {}).get(c, 0.0):>9.2f}" for c in cats)
374
+ + f" {entry.get('runs', 0):>4}") if evals else ""
375
+ print(f" {entry['name']:<{width}} ${entry['cost']:>9.2f}{ev_cell}"
376
+ f" {format_tokens(entry['tokens']):>8}"
356
377
  f"{q_cell} {entry['agents']:>6} {entry['running']:>7}{bg_cell}{id_cell}")
357
378
  if quota is not None and quota.get("unattributed") is not None:
358
379
  print(f" {'unattributed':<{width}} {'':>10} {'':>8} {format_pp(quota['unattributed']):>9}")
359
380
  total = sum(e["cost"] for _, e in rows)
360
381
  q_total = f" {format_pp(sum(quota['codes'].values())):>9}" if quota is not None else ""
361
- print(f" {'total':<{width}} ${total:>9.2f} {'':>8}{q_total}")
382
+ ext_total = sum(e.get("ext_cost", 0.0) for _, e in rows)
383
+ ev_total = (f" ${total - ext_total:>9.2f} ${ext_total:>9.2f}"
384
+ + "".join(f" ${cat_totals[c]:>9.2f}" for c in cats) + f" {'':>4}") if evals else ""
385
+ print(f" {'total':<{width}} ${total:>9.2f}{ev_total} {'':>8}{q_total}")
386
+ if evals:
387
+ rprint("\n [dim]cost = own (agents' conversations) + external (evals through the "
388
+ "spend gateway, overcode spend record), split by category; runs: how many[/dim]")
362
389
  if quota is not None:
363
390
  rprint(f"\n [dim]{quota['label'].strip()}: predicted points of the weekly subscription "
364
391
  f"quota (estimate, model {quota['confidence']}; overcode usage model)[/dim]")
365
392
 
366
393
 
394
+ @billing_app.command("show")
395
+ def billing_show(
396
+ code: Annotated[str, typer.Argument(help="The code (an experiment): its name, a previous name, or its id")],
397
+ since: Annotated[
398
+ Optional[str],
399
+ typer.Option("--since", help="Spend since: 30d, 2w, 12h, 2026-09, 2026-09-15"),
400
+ ] = None,
401
+ as_json: Annotated[bool, typer.Option("--json", help="Print JSON")] = False,
402
+ ):
403
+ """One code's spend, split: each agent's own, and each eval run's.
404
+
405
+ Eval runs are spend recorded with `overcode spend record` (or the
406
+ Python helper) by an agent's evals and sims, billed to the agent's code
407
+ and shown under the agent that ran them.
408
+
409
+ Examples:
410
+ overcode billing show exp-tuning
411
+ overcode billing show exp-tuning --since 7d
412
+ """
413
+ import json
414
+
415
+ from ..session_archive import parse_since
416
+ from ..session_manager import SessionManager
417
+
418
+ manager = SessionManager()
419
+ ledger = manager.ledger
420
+ code_id = ledger.codes.find(code)
421
+ if code_id is None:
422
+ rprint(f"[red]Error: no billing code '{code}'[/red]")
423
+ raise typer.Exit(code=1)
424
+ try:
425
+ start = parse_since(since) if since else None
426
+ except ValueError as e:
427
+ rprint(f"[red]Error: {e}[/red]")
428
+ raise typer.Exit(code=1)
429
+ detail: dict = {}
430
+ ledger.report(since=start, agents=detail)
431
+ spent = detail.get(code_id, {})
432
+ names = {sid: d["name"] for sid, d in spent.items() if not d.get("external")}
433
+ live = {s.id: s.name for s in manager.list_sessions()}
434
+
435
+ def agent_name(sid):
436
+ if not sid:
437
+ return "-"
438
+ return names.get(sid) or live.get(sid) or sid[:8]
439
+
440
+ agents = sorted(((sid, d) for sid, d in spent.items() if not d.get("external")),
441
+ key=lambda kv: -kv[1]["cost"])
442
+ runs = sorted(((sid, d) for sid, d in spent.items() if d.get("external")),
443
+ key=lambda kv: -kv[1]["cost"])
444
+ own = sum(d["cost"] for _, d in agents)
445
+ evals = sum(d["cost"] for _, d in runs)
446
+ name = ledger.codes.name_of(code_id)
447
+ if as_json:
448
+ print(json.dumps({
449
+ "code": code_id, "name": name, "scope": f"since {since}" if since else "all time",
450
+ "agents_cost": own, "evals_cost": evals, "cost": own + evals,
451
+ "agents": [{"id": sid, "name": d["name"], "cost": d["cost"], "running": d["running"]}
452
+ for sid, d in agents],
453
+ "runs": [{"run": sid, "label": d["name"], "agent": d.get("parent"),
454
+ "agent_name": agent_name(d.get("parent")), "cost": d["cost"]}
455
+ for sid, d in runs]}, indent=2))
456
+ return
457
+ scope = f"since {since}" if since else "all time"
458
+ if not spent:
459
+ rprint(f"[dim]No spend on {name} ({scope})[/dim]")
460
+ return
461
+ rprint(f"\n[bold]{name}[/bold] ({scope}): ${own + evals:.2f} "
462
+ f"= agents ${own:.2f} + evals ${evals:.2f}\n")
463
+ width = max(12, *(len(str(d["name"])) for _, d in [*agents, *runs]))
464
+ if agents:
465
+ print(f" {'agent':<{width}} {'cost':>10}")
466
+ for _, d in agents:
467
+ print(f" {d['name']:<{width}} ${d['cost']:>9.2f}" + (" running" if d["running"] else ""))
468
+ if runs:
469
+ print(f"\n {'eval run':<{width}} {'cost':>10} agent")
470
+ for _, d in runs:
471
+ print(f" {d['name']:<{width}} ${d['cost']:>9.2f} {agent_name(d.get('parent'))}")
472
+
473
+
367
474
  @billing_app.command("rename")
368
475
  def billing_rename(
369
476
  old: Annotated[str, typer.Argument(help="The code: its name, a previous name, or its id")],
overcode/cli/doctor.py CHANGED
@@ -309,6 +309,13 @@ def _print_storage(session: str, session_manager) -> None:
309
309
  rprint(f"[dim] {note}[/dim]")
310
310
  for finding in storage_findings(report, terminated_grace_seconds=grace):
311
311
  rprint(f"[yellow]⚠[/yellow] {finding}")
312
+ try:
313
+ from ..doctor import gateway_findings
314
+
315
+ for finding in gateway_findings():
316
+ rprint(f"[yellow]⚠[/yellow] {finding}")
317
+ except Exception as e:
318
+ rprint(f"[yellow]⚠[/yellow] spend gateway check failed: {e}")
312
319
  try:
313
320
  from ..doctor import billing_findings
314
321