codee-agent 0.9.2__py3-none-any.whl → 0.9.3__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.
- codee/admin.py +28 -1
- codee/admin_service.py +11 -4
- codee/test_admin.py +19 -5
- codee/test_admin_service.py +37 -7
- {codee_agent-0.9.2.dist-info → codee_agent-0.9.3.dist-info}/METADATA +1 -1
- {codee_agent-0.9.2.dist-info → codee_agent-0.9.3.dist-info}/RECORD +20 -20
- codee_agent_abstract/provider.py +25 -0
- codee_agent_abstract/test.py +17 -1
- codee_agent_abstract/transcript.py +32 -1
- codee_agent_claude_code/provider.py +55 -2
- codee_agent_claude_code/test.py +63 -0
- codee_agent_codex/provider.py +33 -2
- codee_agent_codex/test.py +40 -0
- codee_agent_github_copilot/provider.py +40 -2
- codee_agent_github_copilot/test.py +50 -0
- codee_agent_opencode/provider.py +160 -1
- codee_agent_opencode/test.py +125 -0
- {codee_agent-0.9.2.dist-info → codee_agent-0.9.3.dist-info}/WHEEL +0 -0
- {codee_agent-0.9.2.dist-info → codee_agent-0.9.3.dist-info}/entry_points.txt +0 -0
- {codee_agent-0.9.2.dist-info → codee_agent-0.9.3.dist-info}/licenses/LICENSE +0 -0
codee/admin.py
CHANGED
|
@@ -219,6 +219,25 @@ class PeepStep(BaseModel):
|
|
|
219
219
|
timestamp: str = ""
|
|
220
220
|
|
|
221
221
|
|
|
222
|
+
def _context_summary(context: dict[str, int] | None) -> str:
|
|
223
|
+
"""One line on how full a session's context window is, "" when unknown.
|
|
224
|
+
|
|
225
|
+
Reads "Context: 41,245 / 128,000 tokens (32%) · 1 compaction", dropping
|
|
226
|
+
the window and share when the agent didn't say how big it is.
|
|
227
|
+
"""
|
|
228
|
+
if not context:
|
|
229
|
+
return ""
|
|
230
|
+
tokens, window = context["tokens"], context["window"]
|
|
231
|
+
compactions = context["compactions"]
|
|
232
|
+
parts = []
|
|
233
|
+
if tokens and window:
|
|
234
|
+
parts.append(f"{tokens:,} / {window:,} tokens ({tokens / window:.0%})")
|
|
235
|
+
elif tokens:
|
|
236
|
+
parts.append(f"{tokens:,} tokens")
|
|
237
|
+
parts.append(f"{compactions} compaction{'' if compactions == 1 else 's'}")
|
|
238
|
+
return "Context: " + " · ".join(parts)
|
|
239
|
+
|
|
240
|
+
|
|
222
241
|
def _active_job(job: dict[str, Any]) -> ActiveJob:
|
|
223
242
|
"""One in-flight run as its dashboard row reads it.
|
|
224
243
|
|
|
@@ -425,11 +444,13 @@ class AdminState(rx.State):
|
|
|
425
444
|
kill_job_label: str = ""
|
|
426
445
|
# The session the Peep dialog shows, held for the same reason, with the
|
|
427
446
|
# last steps read from its transcript. ``peep_note`` says why there are
|
|
428
|
-
# none, or that the session has finished since.
|
|
447
|
+
# none, or that the session has finished since. ``peep_context`` is one
|
|
448
|
+
# line on how full its context window is, empty when the agent can't tell.
|
|
429
449
|
peep_job_id: int = 0
|
|
430
450
|
peep_job_label: str = ""
|
|
431
451
|
peep_steps: list[PeepStep] = []
|
|
432
452
|
peep_note: str = ""
|
|
453
|
+
peep_context: str = ""
|
|
433
454
|
paused: bool = False
|
|
434
455
|
total_runs: int = 0
|
|
435
456
|
last_24h_runs: int = 0
|
|
@@ -1046,6 +1067,7 @@ class AdminState(rx.State):
|
|
|
1046
1067
|
self.peep_job_id = job_id
|
|
1047
1068
|
self.peep_job_label = label
|
|
1048
1069
|
self.peep_steps = []
|
|
1070
|
+
self.peep_context = ""
|
|
1049
1071
|
self._load_peep()
|
|
1050
1072
|
|
|
1051
1073
|
def set_peep_dialog_open(self, is_open: bool) -> None:
|
|
@@ -1054,6 +1076,7 @@ class AdminState(rx.State):
|
|
|
1054
1076
|
self.peep_job_label = ""
|
|
1055
1077
|
self.peep_steps = []
|
|
1056
1078
|
self.peep_note = ""
|
|
1079
|
+
self.peep_context = ""
|
|
1057
1080
|
|
|
1058
1081
|
def refresh_peep(self) -> None:
|
|
1059
1082
|
if self.peep_job_id:
|
|
@@ -1080,6 +1103,7 @@ class AdminState(rx.State):
|
|
|
1080
1103
|
"sessions yet.")
|
|
1081
1104
|
return
|
|
1082
1105
|
self.peep_steps = [PeepStep(**entry) for entry in peep["entries"]]
|
|
1106
|
+
self.peep_context = _context_summary(peep.get("context"))
|
|
1083
1107
|
self.peep_note = ("" if self.peep_steps else
|
|
1084
1108
|
"Nothing to show yet. The agent may still be "
|
|
1085
1109
|
"starting up.")
|
|
@@ -2338,6 +2362,9 @@ def peep_dialog() -> rx.Component:
|
|
|
2338
2362
|
font_size="0.85rem", overflow="hidden",
|
|
2339
2363
|
text_overflow="ellipsis", white_space="nowrap"),
|
|
2340
2364
|
color=MUTED),
|
|
2365
|
+
rx.cond(AdminState.peep_context != "",
|
|
2366
|
+
rx.text(AdminState.peep_context, color=MUTED,
|
|
2367
|
+
font_size="0.8rem", margin_top="0.35rem")),
|
|
2341
2368
|
rx.vstack(
|
|
2342
2369
|
rx.foreach(AdminState.peep_steps, peep_step),
|
|
2343
2370
|
rx.cond(AdminState.peep_note != "",
|
codee/admin_service.py
CHANGED
|
@@ -2094,8 +2094,10 @@ class AdminService:
|
|
|
2094
2094
|
"""The last ``limit`` steps of a running session. None once it finished.
|
|
2095
2095
|
|
|
2096
2096
|
``entries`` is None rather than a list when the session's agent keeps
|
|
2097
|
-
no transcript Codee can read.
|
|
2098
|
-
|
|
2097
|
+
no transcript Codee can read. ``context`` says how full the session's
|
|
2098
|
+
context window is, None when the agent can't tell. A row that names no
|
|
2099
|
+
agent, from before the dashboard recorded one, is read as the default
|
|
2100
|
+
agent's.
|
|
2099
2101
|
"""
|
|
2100
2102
|
job = next((job for job in runs_db.active_jobs(main_context=self.context)
|
|
2101
2103
|
if job["id"] == job_id), None)
|
|
@@ -2104,21 +2106,26 @@ class AdminService:
|
|
|
2104
2106
|
agent = (resolve_agent_code(job.get("agent") or "")
|
|
2105
2107
|
or self.context.settings.coding_agent)
|
|
2106
2108
|
implementation = CODING_AGENTS.get(agent)
|
|
2107
|
-
entries = None
|
|
2109
|
+
entries = context = None
|
|
2108
2110
|
if implementation is not None:
|
|
2109
2111
|
try:
|
|
2110
2112
|
entries = implementation.peep(job["session_id"], self.root,
|
|
2111
2113
|
limit)
|
|
2114
|
+
context = implementation.context_usage(job["session_id"],
|
|
2115
|
+
self.root)
|
|
2112
2116
|
except Exception as error:
|
|
2113
2117
|
print(f"[admin] Could not read job {job_id}'s transcript: "
|
|
2114
2118
|
f"{error}")
|
|
2115
|
-
entries = []
|
|
2119
|
+
entries = entries or []
|
|
2116
2120
|
return {
|
|
2117
2121
|
"agent": agent_label(agent),
|
|
2118
2122
|
"entries": (None if entries is None else
|
|
2119
2123
|
[{"kind": entry.kind, "text": entry.text,
|
|
2120
2124
|
"timestamp": entry.timestamp}
|
|
2121
2125
|
for entry in entries]),
|
|
2126
|
+
"context": (None if context is None else
|
|
2127
|
+
{"tokens": context.tokens, "window": context.window,
|
|
2128
|
+
"compactions": context.compactions}),
|
|
2122
2129
|
}
|
|
2123
2130
|
|
|
2124
2131
|
def set_paused(self, paused: bool) -> bool:
|
codee/test_admin.py
CHANGED
|
@@ -4,7 +4,8 @@ from types import SimpleNamespace
|
|
|
4
4
|
from unittest.mock import Mock, patch
|
|
5
5
|
|
|
6
6
|
from codee.admin import (EFFORT_DEFAULT, AdminState, ModelOption, PeepStep,
|
|
7
|
-
_highlight_parts, _run_preview,
|
|
7
|
+
_context_summary, _highlight_parts, _run_preview,
|
|
8
|
+
running_panel)
|
|
8
9
|
|
|
9
10
|
|
|
10
11
|
def test_pause_with_running_agents_explains_they_will_finish() -> None:
|
|
@@ -101,7 +102,7 @@ def test_killing_a_session_that_already_finished_says_so() -> None:
|
|
|
101
102
|
|
|
102
103
|
def _peep_state(**fields) -> SimpleNamespace:
|
|
103
104
|
state = SimpleNamespace(peep_job_id=0, peep_job_label="", peep_steps=[],
|
|
104
|
-
peep_note="")
|
|
105
|
+
peep_note="", peep_context="")
|
|
105
106
|
state.__dict__.update(fields)
|
|
106
107
|
state._load_peep = lambda: AdminState._load_peep(state)
|
|
107
108
|
return state
|
|
@@ -112,7 +113,9 @@ def test_peep_shows_the_sessions_last_steps() -> None:
|
|
|
112
113
|
with patch("codee.admin.SERVICE.peep_job", return_value={
|
|
113
114
|
"agent": "Claude Code",
|
|
114
115
|
"entries": [{"kind": "tool", "text": "Bash: ls",
|
|
115
|
-
"timestamp": "2026-10-01T10:00:00Z"}]
|
|
116
|
+
"timestamp": "2026-10-01T10:00:00Z"}],
|
|
117
|
+
"context": {"tokens": 41245, "window": 128000,
|
|
118
|
+
"compactions": 1}}) as peep:
|
|
116
119
|
AdminState.open_peep.fn(state, 7, "/nightly")
|
|
117
120
|
|
|
118
121
|
peep.assert_called_once_with(7, 10)
|
|
@@ -120,6 +123,17 @@ def test_peep_shows_the_sessions_last_steps() -> None:
|
|
|
120
123
|
assert [(step.kind, step.text) for step in state.peep_steps] == [
|
|
121
124
|
("tool", "Bash: ls")]
|
|
122
125
|
assert state.peep_note == ""
|
|
126
|
+
assert state.peep_context == (
|
|
127
|
+
"Context: 41,245 / 128,000 tokens (32%) · 1 compaction")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def test_the_context_line_says_only_what_the_agent_wrote_down() -> None:
|
|
131
|
+
assert _context_summary(None) == ""
|
|
132
|
+
assert _context_summary({"tokens": 41245, "window": 0,
|
|
133
|
+
"compactions": 0}) == (
|
|
134
|
+
"Context: 41,245 tokens · 0 compactions")
|
|
135
|
+
assert _context_summary({"tokens": 0, "window": 0,
|
|
136
|
+
"compactions": 3}) == "Context: 3 compactions"
|
|
123
137
|
|
|
124
138
|
|
|
125
139
|
def test_peep_says_when_there_is_nothing_yet() -> None:
|
|
@@ -154,12 +168,12 @@ def test_refreshing_a_finished_session_keeps_what_was_on_screen() -> None:
|
|
|
154
168
|
def test_closing_the_peep_dialog_forgets_the_session() -> None:
|
|
155
169
|
state = _peep_state(peep_job_id=7, peep_job_label="/nightly",
|
|
156
170
|
peep_steps=[PeepStep(kind="text", text="x")],
|
|
157
|
-
peep_note="note")
|
|
171
|
+
peep_note="note", peep_context="Context: 1 compaction")
|
|
158
172
|
|
|
159
173
|
AdminState.set_peep_dialog_open.fn(state, False)
|
|
160
174
|
|
|
161
175
|
assert (state.peep_job_id, state.peep_job_label, state.peep_steps,
|
|
162
|
-
state.peep_note) == (0, "", [], "")
|
|
176
|
+
state.peep_note, state.peep_context) == (0, "", [], "", "")
|
|
163
177
|
|
|
164
178
|
|
|
165
179
|
def test_clearing_skill_search_resets_query() -> None:
|
codee/test_admin_service.py
CHANGED
|
@@ -10,10 +10,11 @@ from pathlib import Path
|
|
|
10
10
|
from unittest.mock import Mock, patch
|
|
11
11
|
from urllib.parse import parse_qs, urlparse
|
|
12
12
|
|
|
13
|
-
from codee_agent_abstract.provider import AgentModel, PeepEntry
|
|
13
|
+
from codee_agent_abstract.provider import AgentModel, ContextUsage, PeepEntry
|
|
14
14
|
from codee_agent_claude_code.provider import ClaudeCodeAgent
|
|
15
15
|
from codee_agent_codex.provider import CodexAgent
|
|
16
16
|
from codee_agent_github_copilot.provider import GitHubCopilotAgent
|
|
17
|
+
from codee_agent_opencode.provider import OpenCodeAgent
|
|
17
18
|
|
|
18
19
|
from codee.admin_service import (
|
|
19
20
|
MCP_CHECK, TASKS_CHECK, USAGE_CACHE_SECONDS,
|
|
@@ -3782,14 +3783,20 @@ class PeepJobTest(unittest.TestCase):
|
|
|
3782
3783
|
|
|
3783
3784
|
with patch.object(CodexAgent, "peep", return_value=[
|
|
3784
3785
|
PeepEntry("tool", "shell: ls", "2026-10-01T10:00:00Z")]
|
|
3785
|
-
) as peep
|
|
3786
|
+
) as peep, \
|
|
3787
|
+
patch.object(CodexAgent, "context_usage",
|
|
3788
|
+
return_value=ContextUsage(51863, 258400, 2)
|
|
3789
|
+
) as context_usage:
|
|
3786
3790
|
result = service.peep_job(job_id)
|
|
3787
3791
|
|
|
3788
3792
|
peep.assert_called_once_with("thread-1", root, 10)
|
|
3793
|
+
context_usage.assert_called_once_with("thread-1", root)
|
|
3789
3794
|
self.assertEqual(result, {
|
|
3790
3795
|
"agent": "Codex",
|
|
3791
3796
|
"entries": [{"kind": "tool", "text": "shell: ls",
|
|
3792
|
-
"timestamp": "2026-10-01T10:00:00Z"}]
|
|
3797
|
+
"timestamp": "2026-10-01T10:00:00Z"}],
|
|
3798
|
+
"context": {"tokens": 51863, "window": 258400,
|
|
3799
|
+
"compactions": 2}})
|
|
3793
3800
|
|
|
3794
3801
|
def test_a_row_naming_no_agent_is_read_as_the_default_agents(self) -> None:
|
|
3795
3802
|
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
@@ -3798,11 +3805,30 @@ class PeepJobTest(unittest.TestCase):
|
|
|
3798
3805
|
main_context=service.context)
|
|
3799
3806
|
|
|
3800
3807
|
with patch.object(ClaudeCodeAgent, "peep",
|
|
3801
|
-
return_value=[]) as peep
|
|
3808
|
+
return_value=[]) as peep, \
|
|
3809
|
+
patch.object(ClaudeCodeAgent, "context_usage",
|
|
3810
|
+
return_value=None):
|
|
3802
3811
|
result = service.peep_job(job_id)
|
|
3803
3812
|
|
|
3804
3813
|
peep.assert_called_once()
|
|
3805
|
-
self.assertEqual(result, {"agent": "Claude Code", "entries": []
|
|
3814
|
+
self.assertEqual(result, {"agent": "Claude Code", "entries": [],
|
|
3815
|
+
"context": None})
|
|
3816
|
+
|
|
3817
|
+
def test_steps_read_before_the_usage_failed_are_kept(self) -> None:
|
|
3818
|
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
3819
|
+
service = self._service(Path(temporary_directory))
|
|
3820
|
+
job_id = runs_db.start_job("sid-1", "/nightly",
|
|
3821
|
+
main_context=service.context)
|
|
3822
|
+
|
|
3823
|
+
with patch.object(ClaudeCodeAgent, "peep", return_value=[
|
|
3824
|
+
PeepEntry("text", "Done.")]), \
|
|
3825
|
+
patch.object(ClaudeCodeAgent, "context_usage",
|
|
3826
|
+
side_effect=OSError("gone")):
|
|
3827
|
+
result = service.peep_job(job_id)
|
|
3828
|
+
|
|
3829
|
+
self.assertEqual(result["entries"],
|
|
3830
|
+
[{"kind": "text", "text": "Done.", "timestamp": ""}])
|
|
3831
|
+
self.assertIsNone(result["context"])
|
|
3806
3832
|
|
|
3807
3833
|
def test_an_agent_without_a_transcript_says_so(self) -> None:
|
|
3808
3834
|
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
@@ -3811,9 +3837,13 @@ class PeepJobTest(unittest.TestCase):
|
|
|
3811
3837
|
agent="OpenCode",
|
|
3812
3838
|
main_context=service.context)
|
|
3813
3839
|
|
|
3814
|
-
|
|
3840
|
+
with patch.object(OpenCodeAgent, "peep", return_value=None), \
|
|
3841
|
+
patch.object(OpenCodeAgent, "context_usage",
|
|
3842
|
+
return_value=None):
|
|
3843
|
+
result = service.peep_job(job_id)
|
|
3815
3844
|
|
|
3816
|
-
self.assertEqual(result, {"agent": "OpenCode", "entries": None
|
|
3845
|
+
self.assertEqual(result, {"agent": "OpenCode", "entries": None,
|
|
3846
|
+
"context": None})
|
|
3817
3847
|
|
|
3818
3848
|
def test_a_finished_session_is_none(self) -> None:
|
|
3819
3849
|
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codee-agent
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.3
|
|
4
4
|
Summary: A virtual co-worker that picks up Jira and Azure DevOps tasks and solves them with coding agents.
|
|
5
5
|
Keywords: ai,agent,jira,azure-devops,claude-code,github-copilot,codex,opencode,automation
|
|
6
6
|
Author: Denis Kibalko
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
codee/.gitignore,sha256=Fltsn5J90L9HwYTVg7Xlaoek3U0riZWmDTWmf0Ttfr8,15
|
|
2
2
|
codee/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
-
codee/admin.py,sha256=
|
|
3
|
+
codee/admin.py,sha256=OzUEUpv4tMh4ks_GJxBsbmd3WNeN_7kdMIa0ZNAHjYA,200542
|
|
4
4
|
codee/admin_api.py,sha256=q2S2H6neSXkcjrlhI3s190jJbOgenL0sqle5vnYmM5E,2503
|
|
5
5
|
codee/admin_cli.py,sha256=8Hj9okvF1KMRsfm8IhGwl_E6OLqVAQ-wB2fjDKB9M4w,2871
|
|
6
|
-
codee/admin_service.py,sha256=
|
|
6
|
+
codee/admin_service.py,sha256=3S56yMad2gQb7FDz1qBAzt_FlUVYFE4QU8LtamZ13q8,125632
|
|
7
7
|
codee/agent_cli.py,sha256=BNCMT4bIoAVmgbbU5QxAyktPmUXXWbB_I9cjg1vdBLg,2553
|
|
8
8
|
codee/coding_agents.py,sha256=w7ofwl8b7CaPJzwBttxNpZyHUbm94P1XroKrRN5y2f8,3438
|
|
9
9
|
codee/executor.py,sha256=FWUi_uMHqkt5552gAnxm5yN8mADYzzOdhvJEUUnpqiE,25222
|
|
@@ -42,10 +42,10 @@ codee/templates/skills/task-code-reviewer/SKILL.md,sha256=spT7kL_X6WsJtvUt6_2Ga3
|
|
|
42
42
|
codee/templates/skills/task-developer/SKILL.md,sha256=65YFC9kF7UY5AZXAP4O5nYFksTVdfcq-a6LNeRO4414,1956
|
|
43
43
|
codee/templates/skills/task-qa/SKILL.md,sha256=sPyMDbicCfYdf4QF8E5vLjUuPrZNyKl0F9xxHNMptW4,1746
|
|
44
44
|
codee/templates/skills/task-security-reviewer/SKILL.md,sha256=DY__ZKPGUeqveMZ0M3P4eGLaRkn3zykFlWW6tlf3VIY,1842
|
|
45
|
-
codee/test_admin.py,sha256=
|
|
45
|
+
codee/test_admin.py,sha256=fyLX0BRoSMsIZDOw1M5bDFg2NKO71hzMRSESKXaY6GE,15648
|
|
46
46
|
codee/test_admin_api.py,sha256=eT-ZCWw8giVU5V1xdqdctytVjuXV3wm3FKv4Nnp3gaU,2710
|
|
47
47
|
codee/test_admin_cli.py,sha256=xMAdp8nBneNp6krZQo3SLtGM9rpjo19mnmmKqtM0QDw,3775
|
|
48
|
-
codee/test_admin_service.py,sha256=
|
|
48
|
+
codee/test_admin_service.py,sha256=fM3vjAJqZIWpxpdtILcjug9QSPuGfa9EJ87yBAu9HBw,179865
|
|
49
49
|
codee/test_agent_cli.py,sha256=JMRuG1lt5EgGr-YbvXEG8MSQdlQZwF4Yda8ZDLZVJTo,4363
|
|
50
50
|
codee/test_coding_agents.py,sha256=8YPcEqVcyrvcQq6gpX3DmdHoP7z7fJ9kHl59Hre9Ruk,2700
|
|
51
51
|
codee/test_executor.py,sha256=z8c71dhOcsjp9ILn79d7Tf0e3YC5TQMYYevOGU1AmpQ,28164
|
|
@@ -58,25 +58,25 @@ codee_admin/__init__.py,sha256=kdPfIMlHX4kajFVw6XmC2jqsw1XKkkfEGWWC_3bdDZE,51
|
|
|
58
58
|
codee_admin/codee_admin.py,sha256=MVzRzfRsMYWkcaD3zQG8bDmvs5FTrUSFz1Ij-_wU8e4,93
|
|
59
59
|
codee_agent_abstract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
60
60
|
codee_agent_abstract/acp.py,sha256=93FBrYQNcFF2ihij_ef3FgZlSKd5-gL6oiDjRNdHkfw,7714
|
|
61
|
-
codee_agent_abstract/provider.py,sha256=
|
|
62
|
-
codee_agent_abstract/test.py,sha256=
|
|
63
|
-
codee_agent_abstract/transcript.py,sha256=
|
|
61
|
+
codee_agent_abstract/provider.py,sha256=ldBXT4WquuHXtX083y_zxGWScYJDktBX0zTJvn87l1o,9700
|
|
62
|
+
codee_agent_abstract/test.py,sha256=x0qDiG907L5cFyDJmWEG6ZGTKdAQmIu9UK-qoDL0QoA,10729
|
|
63
|
+
codee_agent_abstract/transcript.py,sha256=CuR-NQlHFL90FVtq4Y9zOV7wLSGuUkOld1sWcsFIPDQ,3854
|
|
64
64
|
codee_agent_claude_code/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
65
65
|
codee_agent_claude_code/account.py,sha256=Gv_9vGtMFROi9p2iNUqKKWmDoA3HZE_7n6wHVie9XJM,3068
|
|
66
66
|
codee_agent_claude_code/credentials.py,sha256=sT9GasA5SjZIoNmlZlo1hRECYDFn6O3Tge7Tuw8D9J8,5320
|
|
67
67
|
codee_agent_claude_code/oauth.py,sha256=kSr5cLuVcHUvny563DSXpwCV0tw8zySMsfqtdqDrGnI,10357
|
|
68
|
-
codee_agent_claude_code/provider.py,sha256=
|
|
69
|
-
codee_agent_claude_code/test.py,sha256=
|
|
68
|
+
codee_agent_claude_code/provider.py,sha256=CmUdds-ckq2a3yubIUYw-ntesdkTFFmv28sNQsDCJK0,10865
|
|
69
|
+
codee_agent_claude_code/test.py,sha256=vE8tXFqcz0jiwWIhBy8SAOIsZBy3cDb6OBC-ddASrQM,30442
|
|
70
70
|
codee_agent_claude_code/usage.py,sha256=wSvJNDwAJmmQT7Syc-TF-DeW3yc8c2iJvZbbRwbJsqU,6202
|
|
71
71
|
codee_agent_codex/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
72
|
-
codee_agent_codex/provider.py,sha256=
|
|
73
|
-
codee_agent_codex/test.py,sha256=
|
|
72
|
+
codee_agent_codex/provider.py,sha256=4QjFW-GAXPX90pUJCgmPRklIrpgYxdRGmOxD-PKVIfo,22038
|
|
73
|
+
codee_agent_codex/test.py,sha256=LhMqma8mLA3P_cSWQ2ziPNpwHYu_h4xlvtnuWZ7kT7s,17827
|
|
74
74
|
codee_agent_github_copilot/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
75
|
-
codee_agent_github_copilot/provider.py,sha256=
|
|
76
|
-
codee_agent_github_copilot/test.py,sha256=
|
|
75
|
+
codee_agent_github_copilot/provider.py,sha256=ZcMuF9qrZ-9FazUmhJ31NnGjF2pDyutndEA9YYkds24,19702
|
|
76
|
+
codee_agent_github_copilot/test.py,sha256=2LY6dUIdMAXFn6dUMcKlLXJTFs5y7lfAnF3Aa8lJDFE,23105
|
|
77
77
|
codee_agent_opencode/__init__.py,sha256=7RLeh9HIa5kXdpzvXSwI2UjNczzsTwOmcanVjv2ZkhY,41
|
|
78
|
-
codee_agent_opencode/provider.py,sha256=
|
|
79
|
-
codee_agent_opencode/test.py,sha256=
|
|
78
|
+
codee_agent_opencode/provider.py,sha256=SFpHLA0egskIKYutLHqO0qn43h90M8WO-e5XGKFaCVA,16035
|
|
79
|
+
codee_agent_opencode/test.py,sha256=h8p_Df2VfowTOyDKhdcGOg2u3AnKz-LX07g2O8KvtJM,14592
|
|
80
80
|
codee_database/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
81
81
|
codee_database/claude_code_accounts.py,sha256=aaB4HKiwkcp1nPZ6JQS4Ja0YwsfE-yeIIr73wHI8Sps,11290
|
|
82
82
|
codee_database/database.py,sha256=qoIemJhiOfZEaoN3AspFaLmfAXZkCm8bgctuUs9MKwE,358
|
|
@@ -95,8 +95,8 @@ codee_tasks_azure_devops/test.py,sha256=i9xDAM0sNw6Cr1s3BprECDnua4WQHkD1anD7kK_l
|
|
|
95
95
|
codee_tasks_jira/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
96
96
|
codee_tasks_jira/provider.py,sha256=N0llXpNzA4O6jD72hx_3_iksloFykar7wscZDcGfdb4,19053
|
|
97
97
|
codee_tasks_jira/test.py,sha256=R0jOw8k_8uF6mYhANpGWZxQI8Dkya0M2Bk0oEK64iGo,27070
|
|
98
|
-
codee_agent-0.9.
|
|
99
|
-
codee_agent-0.9.
|
|
100
|
-
codee_agent-0.9.
|
|
101
|
-
codee_agent-0.9.
|
|
102
|
-
codee_agent-0.9.
|
|
98
|
+
codee_agent-0.9.3.dist-info/licenses/LICENSE,sha256=kXz80_Kc5IXrxIiweSCMx9Dv_AUeOcfwnQqCk2IDTmY,1075
|
|
99
|
+
codee_agent-0.9.3.dist-info/WHEEL,sha256=a0ta4TK7UKMB0EbDesmi2mn0Djkly7aj_7Tu2R7SseE,81
|
|
100
|
+
codee_agent-0.9.3.dist-info/entry_points.txt,sha256=Hr_8ZaN6g5DO1S94WbFpIwJzGAIeyhJrWIXl9BA0uIM,194
|
|
101
|
+
codee_agent-0.9.3.dist-info/METADATA,sha256=NbCVqUAFkPCddQEYQxnTdvX3m-13MLel0zNgXA2Nq9E,2997
|
|
102
|
+
codee_agent-0.9.3.dist-info/RECORD,,
|
codee_agent_abstract/provider.py
CHANGED
|
@@ -68,6 +68,21 @@ class PeepEntry:
|
|
|
68
68
|
timestamp: str = ""
|
|
69
69
|
|
|
70
70
|
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class ContextUsage:
|
|
73
|
+
"""How full a live session's context window is, as the Peep dialog shows it.
|
|
74
|
+
|
|
75
|
+
``tokens`` is what the model's last call put in the window: its prompt and
|
|
76
|
+
its reply, which the next call carries forward. ``window`` is the size of
|
|
77
|
+
that window. Either is 0 when the agent didn't write it down.
|
|
78
|
+
``compactions`` is how many times the session has been compacted so far.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
tokens: int = 0
|
|
82
|
+
window: int = 0
|
|
83
|
+
compactions: int = 0
|
|
84
|
+
|
|
85
|
+
|
|
71
86
|
class AgentResponse(str):
|
|
72
87
|
"""Agent text with optional diagnostic output for the run record."""
|
|
73
88
|
|
|
@@ -206,6 +221,16 @@ class AbstractCodingAgent(ABC):
|
|
|
206
221
|
"""
|
|
207
222
|
return None
|
|
208
223
|
|
|
224
|
+
@classmethod
|
|
225
|
+
def context_usage(cls, session_id: str,
|
|
226
|
+
cwd: Path) -> ContextUsage | None:
|
|
227
|
+
"""How full a live session's context window is, read like ``peep``.
|
|
228
|
+
|
|
229
|
+
None when this agent keeps no transcript Codee can read, or the
|
|
230
|
+
transcript says nothing about it yet. Never raises.
|
|
231
|
+
"""
|
|
232
|
+
return None
|
|
233
|
+
|
|
209
234
|
def describe(self) -> str:
|
|
210
235
|
"""Human-readable one-liner about this agent, for logs."""
|
|
211
236
|
return type(self).__name__
|
codee_agent_abstract/test.py
CHANGED
|
@@ -7,7 +7,8 @@ from pathlib import Path
|
|
|
7
7
|
from unittest.mock import Mock, patch
|
|
8
8
|
|
|
9
9
|
from codee_agent_abstract import acp
|
|
10
|
-
from codee_agent_abstract.transcript import
|
|
10
|
+
from codee_agent_abstract.transcript import (
|
|
11
|
+
clip, scan_jsonl, tail_jsonl, tool_summary)
|
|
11
12
|
from codee_agent_abstract.provider import AgentModel, resolve_command
|
|
12
13
|
|
|
13
14
|
|
|
@@ -222,6 +223,21 @@ class TranscriptTest(unittest.TestCase):
|
|
|
222
223
|
def test_tail_of_a_missing_file_is_empty(self) -> None:
|
|
223
224
|
self.assertEqual(tail_jsonl(Path("/nonexistent/session.jsonl")), [])
|
|
224
225
|
|
|
226
|
+
def test_scan_reads_only_the_lines_carrying_the_marker(self) -> None:
|
|
227
|
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
228
|
+
path = Path(temporary_directory) / "session.jsonl"
|
|
229
|
+
path.write_text(
|
|
230
|
+
json.dumps({"type": "compacted", "n": 1}) + "\n"
|
|
231
|
+
+ json.dumps({"type": "message", "n": 2}) + "\n"
|
|
232
|
+
+ "not json, but compacted\n"
|
|
233
|
+
+ json.dumps({"type": "compacted", "n": 3}) + "\n",
|
|
234
|
+
encoding="utf-8")
|
|
235
|
+
|
|
236
|
+
records = scan_jsonl(path, b"compacted")
|
|
237
|
+
|
|
238
|
+
self.assertEqual([record["n"] for record in records], [1, 3])
|
|
239
|
+
self.assertEqual(scan_jsonl(Path("/nonexistent.jsonl"), b"x"), [])
|
|
240
|
+
|
|
225
241
|
def test_a_tool_call_is_named_by_its_most_telling_argument(self) -> None:
|
|
226
242
|
self.assertEqual(tool_summary("Bash", {"command": "pytest -q",
|
|
227
243
|
"timeout": 60}),
|
|
@@ -44,6 +44,36 @@ def tail_jsonl(path: Path, max_bytes: int = TAIL_BYTES) -> list[dict]:
|
|
|
44
44
|
return records
|
|
45
45
|
|
|
46
46
|
|
|
47
|
+
def scan_jsonl(path: Path, marker: bytes) -> list[dict]:
|
|
48
|
+
"""The JSON objects on the lines of ``path`` that contain ``marker``.
|
|
49
|
+
|
|
50
|
+
Reads the whole file, a line at a time, for the rare events a tail can't
|
|
51
|
+
count (compactions). Only the lines carrying ``marker`` are parsed, so a
|
|
52
|
+
transcript of many megabytes costs one pass over its bytes. [] when the
|
|
53
|
+
file can't be read.
|
|
54
|
+
"""
|
|
55
|
+
records = []
|
|
56
|
+
try:
|
|
57
|
+
with path.open("rb") as handle:
|
|
58
|
+
for line in handle:
|
|
59
|
+
if marker not in line:
|
|
60
|
+
continue
|
|
61
|
+
try:
|
|
62
|
+
record = json.loads(line)
|
|
63
|
+
except ValueError:
|
|
64
|
+
continue
|
|
65
|
+
if isinstance(record, dict):
|
|
66
|
+
records.append(record)
|
|
67
|
+
except OSError:
|
|
68
|
+
return []
|
|
69
|
+
return records
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def token_count(value: object) -> int:
|
|
73
|
+
"""``value`` as a token count, 0 when it isn't a whole number."""
|
|
74
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else 0
|
|
75
|
+
|
|
76
|
+
|
|
47
77
|
def clip(text: str, limit: int = MAX_ENTRY_CHARS) -> str:
|
|
48
78
|
"""``text`` trimmed, and cut to ``limit`` characters with a marker if longer."""
|
|
49
79
|
text = text.strip()
|
|
@@ -64,7 +94,8 @@ def tool_summary(name: str, arguments: object) -> str:
|
|
|
64
94
|
except ValueError:
|
|
65
95
|
return clip(f"{name}: {arguments}", 600)
|
|
66
96
|
if isinstance(arguments, dict):
|
|
67
|
-
for key in ("command", "cmd", "file_path", "
|
|
97
|
+
for key in ("command", "cmd", "file_path", "filePath", "path",
|
|
98
|
+
"pattern", "url",
|
|
68
99
|
"query", "description", "prompt"):
|
|
69
100
|
value = arguments.get(key)
|
|
70
101
|
if value:
|
|
@@ -5,8 +5,9 @@ from collections.abc import Callable
|
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
|
|
7
7
|
from codee_agent_abstract.provider import (
|
|
8
|
-
AbstractCodingAgent, AgentModel, PeepEntry)
|
|
9
|
-
from codee_agent_abstract.transcript import
|
|
8
|
+
AbstractCodingAgent, AgentModel, ContextUsage, PeepEntry)
|
|
9
|
+
from codee_agent_abstract.transcript import (
|
|
10
|
+
clip, scan_jsonl, tail_jsonl, token_count, tool_summary)
|
|
10
11
|
from codee_agent_claude_code.credentials import config_dir
|
|
11
12
|
from codee_main_context.context import Settings
|
|
12
13
|
from codee_main_context.logging import get_logger
|
|
@@ -42,6 +43,19 @@ MODELS = [
|
|
|
42
43
|
AgentModel("haiku", "Latest Haiku (alias)"),
|
|
43
44
|
]
|
|
44
45
|
|
|
46
|
+
# The transcript doesn't say how big the context window is, so it is looked up
|
|
47
|
+
# by model: 1M since the 4.6 generation, 200K before it and on Haiku 4.5.
|
|
48
|
+
WIDE_WINDOW = 1_000_000
|
|
49
|
+
NARROW_WINDOW = 200_000
|
|
50
|
+
_NARROW_WINDOW_MODEL = re.compile(
|
|
51
|
+
r"^claude-(3|haiku-4|(opus|sonnet)-4(-[015])?(-\d{8})?$)")
|
|
52
|
+
# The CLI's own notices are saved as assistant turns of this "model", with
|
|
53
|
+
# usage all zero; they say nothing about the window.
|
|
54
|
+
SYNTHETIC_MODEL = "<synthetic>"
|
|
55
|
+
# Written to the transcript, as a system line, each time the session is
|
|
56
|
+
# compacted.
|
|
57
|
+
COMPACT_BOUNDARY = "compact_boundary"
|
|
58
|
+
|
|
45
59
|
|
|
46
60
|
class ClaudeCodeAgent(AbstractCodingAgent):
|
|
47
61
|
"""Runs the ``claude`` CLI in a fresh session, under the id the caller supplies."""
|
|
@@ -75,6 +89,34 @@ class ClaudeCodeAgent(AbstractCodingAgent):
|
|
|
75
89
|
for entry in _entries(record)]
|
|
76
90
|
return entries[-limit:]
|
|
77
91
|
|
|
92
|
+
@classmethod
|
|
93
|
+
def context_usage(cls, session_id: str,
|
|
94
|
+
cwd: Path) -> ContextUsage | None:
|
|
95
|
+
path = _transcript(session_id, cwd)
|
|
96
|
+
if path is None:
|
|
97
|
+
return None
|
|
98
|
+
tokens, model = 0, ""
|
|
99
|
+
for record in tail_jsonl(path):
|
|
100
|
+
message = record.get("message")
|
|
101
|
+
if (record.get("type") != "assistant" or record.get("isSidechain")
|
|
102
|
+
or not isinstance(message, dict)
|
|
103
|
+
or message.get("model") == SYNTHETIC_MODEL
|
|
104
|
+
or not isinstance(message.get("usage"), dict)):
|
|
105
|
+
continue
|
|
106
|
+
usage = message["usage"]
|
|
107
|
+
tokens = sum(token_count(usage.get(key)) for key in (
|
|
108
|
+
"input_tokens", "cache_creation_input_tokens",
|
|
109
|
+
"cache_read_input_tokens", "output_tokens"))
|
|
110
|
+
model = str(message.get("model") or "")
|
|
111
|
+
compactions = sum(
|
|
112
|
+
1 for record in scan_jsonl(path, COMPACT_BOUNDARY.encode())
|
|
113
|
+
if record.get("type") == "system"
|
|
114
|
+
and record.get("subtype") == COMPACT_BOUNDARY)
|
|
115
|
+
if not tokens and not compactions:
|
|
116
|
+
return None
|
|
117
|
+
return ContextUsage(tokens, _context_window(model, tokens) if tokens
|
|
118
|
+
else 0, compactions)
|
|
119
|
+
|
|
78
120
|
def run(self, user_message: str, session_id: str, model: str = "",
|
|
79
121
|
on_session_id: Callable[[str], None] | None = None,
|
|
80
122
|
effort: str = "", context_tier: str = "") -> str:
|
|
@@ -181,6 +223,17 @@ def _transcript(session_id: str, cwd: Path) -> Path | None:
|
|
|
181
223
|
return next(projects.glob(f"*/{name}"), None)
|
|
182
224
|
|
|
183
225
|
|
|
226
|
+
def _context_window(model: str, tokens: int) -> int:
|
|
227
|
+
"""The context window ``model`` runs with, given ``tokens`` already in it.
|
|
228
|
+
|
|
229
|
+
A session holding more than the narrow window must have the wide one,
|
|
230
|
+
whatever its model looks like.
|
|
231
|
+
"""
|
|
232
|
+
if _NARROW_WINDOW_MODEL.match(model) and tokens <= NARROW_WINDOW:
|
|
233
|
+
return NARROW_WINDOW
|
|
234
|
+
return WIDE_WINDOW
|
|
235
|
+
|
|
236
|
+
|
|
184
237
|
def _entries(record: dict) -> list[PeepEntry]:
|
|
185
238
|
"""The steps one transcript line carries: what the model thought, said or ran.
|
|
186
239
|
|
codee_agent_claude_code/test.py
CHANGED
|
@@ -580,3 +580,66 @@ class ClaudeCodePeepTest(unittest.TestCase):
|
|
|
580
580
|
self.assertEqual(ClaudeCodeAgent.peep(SESSION, self.CWD), [])
|
|
581
581
|
self.assertEqual(
|
|
582
582
|
ClaudeCodeAgent.peep("../../etc/passwd", self.CWD), [])
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
class ClaudeCodeContextUsageTest(unittest.TestCase):
|
|
586
|
+
CWD = Path("/srv/codee/my_repo")
|
|
587
|
+
|
|
588
|
+
def _usage(self, model: str, input_tokens: int, output_tokens: int = 0,
|
|
589
|
+
**fields) -> dict:
|
|
590
|
+
return {"type": "assistant", **fields,
|
|
591
|
+
"message": {"role": "assistant", "model": model, "content": [],
|
|
592
|
+
"usage": {"input_tokens": input_tokens,
|
|
593
|
+
"cache_creation_input_tokens": 1000,
|
|
594
|
+
"cache_read_input_tokens": 40000,
|
|
595
|
+
"output_tokens": output_tokens}}}
|
|
596
|
+
|
|
597
|
+
def _usage_of(self, *lines: dict) -> object:
|
|
598
|
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
599
|
+
config = Path(temporary_directory)
|
|
600
|
+
directory = config / "projects" / "-srv-codee-my-repo"
|
|
601
|
+
directory.mkdir(parents=True)
|
|
602
|
+
(directory / f"{SESSION}.jsonl").write_text(
|
|
603
|
+
"".join(json.dumps(line) + "\n" for line in lines),
|
|
604
|
+
encoding="utf-8")
|
|
605
|
+
with patch.dict(os.environ,
|
|
606
|
+
{credentials.CONFIG_DIR_ENV: str(config)}):
|
|
607
|
+
return ClaudeCodeAgent.context_usage(SESSION, self.CWD)
|
|
608
|
+
|
|
609
|
+
def test_reads_the_last_calls_tokens_and_counts_the_compactions(
|
|
610
|
+
self) -> None:
|
|
611
|
+
usage = self._usage_of(
|
|
612
|
+
self._usage("claude-opus-5-5", 10),
|
|
613
|
+
{"type": "system", "subtype": "compact_boundary",
|
|
614
|
+
"compactMetadata": {"trigger": "auto", "preTokens": 900000}},
|
|
615
|
+
{"type": "user", "message": {"role": "user", "content": [
|
|
616
|
+
{"type": "tool_result",
|
|
617
|
+
"content": "grep compact_boundary transcript.jsonl"}]}},
|
|
618
|
+
self._usage("claude-opus-5-5", 5, 500),
|
|
619
|
+
self._usage("claude-sonnet-5", 900000, isSidechain=True),
|
|
620
|
+
self._usage("<synthetic>", 0))
|
|
621
|
+
|
|
622
|
+
self.assertEqual((usage.tokens, usage.window, usage.compactions),
|
|
623
|
+
(41505, 1_000_000, 1))
|
|
624
|
+
|
|
625
|
+
def test_an_older_model_has_the_narrow_window(self) -> None:
|
|
626
|
+
usage = self._usage_of(self._usage("claude-haiku-4-5", 59000))
|
|
627
|
+
|
|
628
|
+
self.assertEqual((usage.tokens, usage.window, usage.compactions),
|
|
629
|
+
(100000, 200_000, 0))
|
|
630
|
+
|
|
631
|
+
def test_a_narrow_model_holding_more_than_it_fits_has_the_wide_one(
|
|
632
|
+
self) -> None:
|
|
633
|
+
usage = self._usage_of(
|
|
634
|
+
self._usage("claude-sonnet-4-5-20250929", 300000))
|
|
635
|
+
|
|
636
|
+
self.assertEqual(usage.window, 1_000_000)
|
|
637
|
+
|
|
638
|
+
def test_a_session_with_no_model_call_yet_says_nothing(self) -> None:
|
|
639
|
+
self.assertIsNone(self._usage_of(
|
|
640
|
+
{"type": "user", "message": {"role": "user", "content": "/x"}}))
|
|
641
|
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
642
|
+
with patch.dict(os.environ,
|
|
643
|
+
{credentials.CONFIG_DIR_ENV: temporary_directory}):
|
|
644
|
+
self.assertIsNone(
|
|
645
|
+
ClaudeCodeAgent.context_usage(SESSION, self.CWD))
|
codee_agent_codex/provider.py
CHANGED
|
@@ -9,8 +9,9 @@ from collections.abc import Callable
|
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
|
|
11
11
|
from codee_agent_abstract.provider import (
|
|
12
|
-
AbstractCodingAgent, AgentModel, PeepEntry, resolve_command)
|
|
13
|
-
from codee_agent_abstract.transcript import
|
|
12
|
+
AbstractCodingAgent, AgentModel, ContextUsage, PeepEntry, resolve_command)
|
|
13
|
+
from codee_agent_abstract.transcript import (
|
|
14
|
+
clip, scan_jsonl, tail_jsonl, token_count, tool_summary)
|
|
14
15
|
from codee_main_context.context import Settings
|
|
15
16
|
from codee_main_context.logging import get_logger
|
|
16
17
|
|
|
@@ -33,6 +34,10 @@ TURN_FAILED = "turn.failed"
|
|
|
33
34
|
ITEM_COMPLETED = "item.completed"
|
|
34
35
|
ERROR = "error"
|
|
35
36
|
AGENT_MESSAGE = "agent_message"
|
|
37
|
+
# What the rollout, which Peep reads, records after each model call (the tokens
|
|
38
|
+
# it used and the window's size), and each time the thread is compacted.
|
|
39
|
+
TOKEN_COUNT = "token_count"
|
|
40
|
+
COMPACTED = "compacted"
|
|
36
41
|
|
|
37
42
|
# `codex` has no "list models" command, but its app server answers `model/list`
|
|
38
43
|
# with the account's live catalog — ids, display names and the reasoning effort
|
|
@@ -80,6 +85,32 @@ class CodexAgent(AbstractCodingAgent):
|
|
|
80
85
|
for entry in _rollout_entries(record)]
|
|
81
86
|
return entries[-limit:]
|
|
82
87
|
|
|
88
|
+
@classmethod
|
|
89
|
+
def context_usage(cls, session_id: str,
|
|
90
|
+
cwd: Path) -> ContextUsage | None:
|
|
91
|
+
path = _rollout(session_id)
|
|
92
|
+
if path is None:
|
|
93
|
+
return None
|
|
94
|
+
tokens = window = 0
|
|
95
|
+
for record in tail_jsonl(path):
|
|
96
|
+
payload = record.get("payload")
|
|
97
|
+
if (record.get("type") != "event_msg"
|
|
98
|
+
or not isinstance(payload, dict)
|
|
99
|
+
or payload.get("type") != TOKEN_COUNT
|
|
100
|
+
or not isinstance(payload.get("info"), dict)):
|
|
101
|
+
continue
|
|
102
|
+
info = payload["info"]
|
|
103
|
+
last = info.get("last_token_usage")
|
|
104
|
+
tokens = token_count((last if isinstance(last, dict) else {}
|
|
105
|
+
).get("total_tokens"))
|
|
106
|
+
window = token_count(info.get("model_context_window"))
|
|
107
|
+
compactions = sum(
|
|
108
|
+
1 for record in scan_jsonl(path, f'"{COMPACTED}"'.encode())
|
|
109
|
+
if record.get("type") == COMPACTED)
|
|
110
|
+
if not tokens and not compactions:
|
|
111
|
+
return None
|
|
112
|
+
return ContextUsage(tokens, window, compactions)
|
|
113
|
+
|
|
83
114
|
def run(self, user_message: str, session_id: str, model: str = "",
|
|
84
115
|
on_session_id: Callable[[str], None] | None = None,
|
|
85
116
|
effort: str = "", context_tier: str = "") -> str:
|
codee_agent_codex/test.py
CHANGED
|
@@ -377,3 +377,43 @@ class CodexPeepTest(unittest.TestCase):
|
|
|
377
377
|
with patch.dict(os.environ, {"CODEX_HOME": temporary_directory}):
|
|
378
378
|
self.assertEqual(
|
|
379
379
|
CodexAgent.peep("codee-session-1", Path("/repo")), [])
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class CodexContextUsageTest(unittest.TestCase):
|
|
383
|
+
THREAD = "01a03949-7aee-70e0-af79-2b81ba610169"
|
|
384
|
+
|
|
385
|
+
def _token_count(self, total: int, window: int) -> dict:
|
|
386
|
+
return {"type": "event_msg", "payload": {"type": "token_count", "info": {
|
|
387
|
+
"total_token_usage": {"total_tokens": total * 10},
|
|
388
|
+
"last_token_usage": {"input_tokens": total - 100,
|
|
389
|
+
"cached_input_tokens": total - 1000,
|
|
390
|
+
"output_tokens": 100,
|
|
391
|
+
"total_tokens": total},
|
|
392
|
+
"model_context_window": window}}}
|
|
393
|
+
|
|
394
|
+
def _usage_of(self, *lines: dict) -> object:
|
|
395
|
+
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
396
|
+
day = Path(temporary_directory) / "sessions" / "2026" / "10" / "01"
|
|
397
|
+
day.mkdir(parents=True)
|
|
398
|
+
(day / f"rollout-2026-10-01T10-00-00-{self.THREAD}.jsonl"
|
|
399
|
+
).write_text("".join(json.dumps(line) + "\n" for line in lines),
|
|
400
|
+
encoding="utf-8")
|
|
401
|
+
with patch.dict(os.environ, {"CODEX_HOME": temporary_directory}):
|
|
402
|
+
return CodexAgent.context_usage(self.THREAD, Path("/repo"))
|
|
403
|
+
|
|
404
|
+
def test_reads_the_last_calls_tokens_and_counts_the_compactions(
|
|
405
|
+
self) -> None:
|
|
406
|
+
usage = self._usage_of(
|
|
407
|
+
self._token_count(200000, 258400),
|
|
408
|
+
{"type": "compacted", "payload": {"message": "summary"}},
|
|
409
|
+
{"type": "event_msg", "payload": {"type": "context_compacted"}},
|
|
410
|
+
self._token_count(51863, 258400),
|
|
411
|
+
{"type": "event_msg",
|
|
412
|
+
"payload": {"type": "token_count", "info": None}})
|
|
413
|
+
|
|
414
|
+
self.assertEqual((usage.tokens, usage.window, usage.compactions),
|
|
415
|
+
(51863, 258400, 1))
|
|
416
|
+
|
|
417
|
+
def test_a_thread_with_no_model_call_yet_says_nothing(self) -> None:
|
|
418
|
+
self.assertIsNone(self._usage_of(
|
|
419
|
+
{"type": "session_meta", "payload": {"id": self.THREAD}}))
|
|
@@ -10,8 +10,9 @@ from pathlib import Path
|
|
|
10
10
|
|
|
11
11
|
from codee_agent_abstract import acp
|
|
12
12
|
from codee_agent_abstract.provider import (
|
|
13
|
-
AbstractCodingAgent, AgentModel, AgentResponse, PeepEntry)
|
|
14
|
-
from codee_agent_abstract.transcript import
|
|
13
|
+
AbstractCodingAgent, AgentModel, AgentResponse, ContextUsage, PeepEntry)
|
|
14
|
+
from codee_agent_abstract.transcript import (
|
|
15
|
+
clip, scan_jsonl, tail_jsonl, token_count, tool_summary)
|
|
15
16
|
from codee_main_context.context import Settings
|
|
16
17
|
from codee_main_context.logging import get_logger
|
|
17
18
|
|
|
@@ -26,6 +27,11 @@ RESULT = "result"
|
|
|
26
27
|
# The session's events log, which Peep reads, also names each tool call as it
|
|
27
28
|
# starts.
|
|
28
29
|
TOOL_EXECUTION_START = "tool.execution_start"
|
|
30
|
+
# It records each model call's tokens and prompt limit, and each compaction,
|
|
31
|
+
# with what is left in the window after it. Sub-agents log theirs to the same
|
|
32
|
+
# file under an ``agentId``; only the main agent's say how full the session is.
|
|
33
|
+
USAGE_RECORD = "session.usage_record"
|
|
34
|
+
COMPACTION_COMPLETE = "session.compaction_complete"
|
|
29
35
|
|
|
30
36
|
# What a session id has to look like before it is put into a path.
|
|
31
37
|
_SESSION_ID = re.compile(r"^[A-Za-z0-9_-]+$")
|
|
@@ -148,6 +154,38 @@ class GitHubCopilotAgent(AbstractCodingAgent):
|
|
|
148
154
|
for entry in _events_entries(record)]
|
|
149
155
|
return entries[-limit:]
|
|
150
156
|
|
|
157
|
+
@classmethod
|
|
158
|
+
def context_usage(cls, session_id: str,
|
|
159
|
+
cwd: Path) -> ContextUsage | None:
|
|
160
|
+
path = _events_file(session_id)
|
|
161
|
+
if path is None:
|
|
162
|
+
return None
|
|
163
|
+
tokens = window = 0
|
|
164
|
+
for record in tail_jsonl(path):
|
|
165
|
+
data = record.get("data")
|
|
166
|
+
if record.get("agentId") or not isinstance(data, dict):
|
|
167
|
+
continue
|
|
168
|
+
kind = record.get("type")
|
|
169
|
+
if kind == USAGE_RECORD and isinstance(data.get("usage"), dict):
|
|
170
|
+
usage = data["usage"]
|
|
171
|
+
if usage.get("parentToolCallId"):
|
|
172
|
+
continue
|
|
173
|
+
tokens = (token_count(usage.get("inputTokens"))
|
|
174
|
+
+ token_count(usage.get("outputTokens")))
|
|
175
|
+
window = token_count(usage.get("maxPromptTokens")) or window
|
|
176
|
+
elif kind == COMPACTION_COMPLETE and data.get("success"):
|
|
177
|
+
tokens = token_count(data.get("postCompactionTokens"))
|
|
178
|
+
window = token_count(data.get("tokenLimit")) or window
|
|
179
|
+
compactions = sum(
|
|
180
|
+
1 for record in scan_jsonl(path, COMPACTION_COMPLETE.encode())
|
|
181
|
+
if record.get("type") == COMPACTION_COMPLETE
|
|
182
|
+
and not record.get("agentId")
|
|
183
|
+
and isinstance(record.get("data"), dict)
|
|
184
|
+
and record["data"].get("success"))
|
|
185
|
+
if not tokens and not compactions:
|
|
186
|
+
return None
|
|
187
|
+
return ContextUsage(tokens, window, compactions)
|
|
188
|
+
|
|
151
189
|
def run(self, user_message: str, session_id: str, model: str = "",
|
|
152
190
|
on_session_id: Callable[[str], None] | None = None,
|
|
153
191
|
effort: str = "", context_tier: str = "") -> str:
|
|
@@ -479,3 +479,53 @@ class GitHubCopilotPeepTest(unittest.TestCase):
|
|
|
479
479
|
|
|
480
480
|
if __name__ == "__main__":
|
|
481
481
|
unittest.main()
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
class GitHubCopilotContextUsageTest(unittest.TestCase):
|
|
485
|
+
def _usage_record(self, input_tokens: int, limit: int, **fields) -> dict:
|
|
486
|
+
return {"type": "session.usage_record", **fields, "data": {"usage": {
|
|
487
|
+
"model": "claude-opus-5", "inputTokens": input_tokens,
|
|
488
|
+
"cacheReadTokens": input_tokens - 100, "outputTokens": 500,
|
|
489
|
+
"maxPromptTokens": limit}}}
|
|
490
|
+
|
|
491
|
+
def _usage_of(self, *records: dict) -> object:
|
|
492
|
+
with tempfile.TemporaryDirectory() as home:
|
|
493
|
+
folder = Path(home) / "session-state" / SESSION
|
|
494
|
+
folder.mkdir(parents=True)
|
|
495
|
+
(folder / "events.jsonl").write_text(
|
|
496
|
+
"".join(json.dumps(record) + "\n" for record in records),
|
|
497
|
+
encoding="utf-8")
|
|
498
|
+
with patch.dict(os.environ, {"COPILOT_HOME": home}):
|
|
499
|
+
return GitHubCopilotAgent.context_usage(SESSION, Path("/repo"))
|
|
500
|
+
|
|
501
|
+
def test_reads_the_last_calls_tokens_and_counts_the_compactions(
|
|
502
|
+
self) -> None:
|
|
503
|
+
usage = self._usage_of(
|
|
504
|
+
self._usage_record(120000, 128000),
|
|
505
|
+
{"type": "session.compaction_complete",
|
|
506
|
+
"data": {"success": True, "preCompactionTokens": 120500,
|
|
507
|
+
"postCompactionTokens": 9000, "tokenLimit": 128000}},
|
|
508
|
+
{"type": "session.compaction_complete",
|
|
509
|
+
"data": {"success": False, "error": "timeout"}},
|
|
510
|
+
self._usage_record(30000, 128000),
|
|
511
|
+
self._usage_record(90000, 64000, agentId="explore-1"),
|
|
512
|
+
{"type": "session.compaction_complete", "agentId": "explore-1",
|
|
513
|
+
"data": {"success": True, "postCompactionTokens": 1}})
|
|
514
|
+
|
|
515
|
+
self.assertEqual((usage.tokens, usage.window, usage.compactions),
|
|
516
|
+
(30500, 128000, 1))
|
|
517
|
+
|
|
518
|
+
def test_a_compaction_leaves_what_it_kept_until_the_next_call(
|
|
519
|
+
self) -> None:
|
|
520
|
+
usage = self._usage_of(
|
|
521
|
+
self._usage_record(120000, 128000),
|
|
522
|
+
{"type": "session.compaction_complete",
|
|
523
|
+
"data": {"success": True, "postCompactionTokens": 9000,
|
|
524
|
+
"tokenLimit": 128000}})
|
|
525
|
+
|
|
526
|
+
self.assertEqual((usage.tokens, usage.window, usage.compactions),
|
|
527
|
+
(9000, 128000, 1))
|
|
528
|
+
|
|
529
|
+
def test_a_cli_that_logs_no_usage_says_nothing(self) -> None:
|
|
530
|
+
self.assertIsNone(self._usage_of(
|
|
531
|
+
{"type": "assistant.message", "data": {"content": "Hi"}}))
|
codee_agent_opencode/provider.py
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import json
|
|
2
2
|
import os
|
|
3
|
+
import sqlite3
|
|
3
4
|
import subprocess
|
|
4
5
|
import threading
|
|
5
6
|
from collections.abc import Callable
|
|
7
|
+
from datetime import datetime, timezone
|
|
6
8
|
from pathlib import Path
|
|
7
9
|
|
|
8
10
|
from codee_agent_abstract import acp
|
|
9
11
|
from codee_agent_abstract.provider import (
|
|
10
|
-
AbstractCodingAgent, AgentModel, resolve_command)
|
|
12
|
+
AbstractCodingAgent, AgentModel, ContextUsage, PeepEntry, resolve_command)
|
|
13
|
+
from codee_agent_abstract.transcript import clip, token_count, tool_summary
|
|
11
14
|
from codee_main_context.context import Settings
|
|
12
15
|
from codee_main_context.logging import get_logger
|
|
13
16
|
|
|
@@ -22,6 +25,30 @@ ACP_COMMAND = ["opencode", "acp"]
|
|
|
22
25
|
# How `--model` names a variant: `provider/model#variant`.
|
|
23
26
|
VARIANT_SEPARATOR = "#"
|
|
24
27
|
|
|
28
|
+
# OpenCode keeps every session in one SQLite database under its data directory,
|
|
29
|
+
# a row per message, and the models.dev catalog it runs on (each model's
|
|
30
|
+
# context limits) in the same file. Peep reads both, read-only.
|
|
31
|
+
DATABASE = "opencode.db"
|
|
32
|
+
CATALOG_KEY = "models-dev:catalog"
|
|
33
|
+
_LAST_ASSISTANT_MESSAGES = (
|
|
34
|
+
"SELECT data FROM session_message WHERE session_id = ? "
|
|
35
|
+
"AND type = 'assistant' ORDER BY seq DESC LIMIT ?")
|
|
36
|
+
# A message's tokens stay zero until its call finishes, so the last one that
|
|
37
|
+
# has any is the one that says how full the window is.
|
|
38
|
+
_LAST_USAGE = (
|
|
39
|
+
"SELECT data FROM session_message WHERE session_id = ? "
|
|
40
|
+
"AND type = 'assistant' "
|
|
41
|
+
"AND coalesce(json_extract(data, '$.tokens.input'), 0) "
|
|
42
|
+
"+ coalesce(json_extract(data, '$.tokens.cache.read'), 0) "
|
|
43
|
+
"+ coalesce(json_extract(data, '$.tokens.cache.write'), 0) > 0 "
|
|
44
|
+
"ORDER BY seq DESC LIMIT 1")
|
|
45
|
+
_COMPACTIONS = (
|
|
46
|
+
"SELECT count(*) FROM session_message WHERE session_id = ? "
|
|
47
|
+
"AND type = 'compaction' AND json_extract(data, '$.status') = 'completed'")
|
|
48
|
+
_MODEL_LIMIT = (
|
|
49
|
+
"SELECT json_extract(json_extract(value, '$.body'), ?) FROM kv "
|
|
50
|
+
"WHERE key = ?")
|
|
51
|
+
|
|
25
52
|
|
|
26
53
|
class OpenCodeAgent(AbstractCodingAgent):
|
|
27
54
|
"""Runs the ``opencode`` CLI non-interactively in a fresh session."""
|
|
@@ -62,6 +89,43 @@ class OpenCodeAgent(AbstractCodingAgent):
|
|
|
62
89
|
log.warning("Could not read the opencode model catalog: %s", exc)
|
|
63
90
|
return []
|
|
64
91
|
|
|
92
|
+
@classmethod
|
|
93
|
+
def peep(cls, session_id: str, cwd: Path,
|
|
94
|
+
limit: int = 10) -> list[PeepEntry] | None:
|
|
95
|
+
# ``cwd`` doesn't matter: OpenCode files every project's sessions in
|
|
96
|
+
# the one database.
|
|
97
|
+
rows = _query(_LAST_ASSISTANT_MESSAGES, (session_id, limit))
|
|
98
|
+
if rows is None:
|
|
99
|
+
return None
|
|
100
|
+
entries = [entry for (data,) in reversed(rows)
|
|
101
|
+
for entry in _message_entries(data)]
|
|
102
|
+
return entries[-limit:]
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def context_usage(cls, session_id: str,
|
|
106
|
+
cwd: Path) -> ContextUsage | None:
|
|
107
|
+
rows = _query(_LAST_USAGE, (session_id,)) or []
|
|
108
|
+
message = _json_object(rows[0][0]) if rows else {}
|
|
109
|
+
tokens = message.get("tokens")
|
|
110
|
+
used = window = 0
|
|
111
|
+
if isinstance(tokens, dict):
|
|
112
|
+
cache = tokens.get("cache")
|
|
113
|
+
cache = cache if isinstance(cache, dict) else {}
|
|
114
|
+
# The sum OpenCode's own sidebar shows as the context in use.
|
|
115
|
+
used = (sum(token_count(tokens.get(key))
|
|
116
|
+
for key in ("input", "output", "reasoning"))
|
|
117
|
+
+ token_count(cache.get("read"))
|
|
118
|
+
+ token_count(cache.get("write")))
|
|
119
|
+
model = message.get("model")
|
|
120
|
+
if used and isinstance(model, dict):
|
|
121
|
+
window = _context_window(str(model.get("providerID") or ""),
|
|
122
|
+
str(model.get("id") or ""))
|
|
123
|
+
counted = _query(_COMPACTIONS, (session_id,)) or [(0,)]
|
|
124
|
+
compactions = token_count(counted[0][0])
|
|
125
|
+
if not used and not compactions:
|
|
126
|
+
return None
|
|
127
|
+
return ContextUsage(used, window, compactions)
|
|
128
|
+
|
|
65
129
|
def skill_prompt(self, slug: str, path: Path, argument: str = "",
|
|
66
130
|
argument_name: str = "") -> str:
|
|
67
131
|
prompt = f"Read {_relative(path, self._cwd)} and follow its instructions exactly."
|
|
@@ -184,6 +248,101 @@ def _with_variant(model: str, effort: str) -> str:
|
|
|
184
248
|
return f"{model}{VARIANT_SEPARATOR}{effort}"
|
|
185
249
|
|
|
186
250
|
|
|
251
|
+
def _database() -> Path:
|
|
252
|
+
"""Where OpenCode keeps its database: ``opencode/`` under XDG_DATA_HOME."""
|
|
253
|
+
configured = os.environ.get("XDG_DATA_HOME", "").strip()
|
|
254
|
+
base = Path(configured) if configured else Path.home() / ".local" / "share"
|
|
255
|
+
return base / "opencode" / DATABASE
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _query(sql: str, parameters: tuple) -> list[tuple] | None:
|
|
259
|
+
"""The rows ``sql`` reads from OpenCode's database, opened read-only.
|
|
260
|
+
|
|
261
|
+
[] when there is no database yet or it can't be read just now. None when
|
|
262
|
+
it has no ``session_message`` table: an OpenCode older than 2.0, which
|
|
263
|
+
keeps its sessions another way.
|
|
264
|
+
"""
|
|
265
|
+
path = _database()
|
|
266
|
+
if not path.is_file():
|
|
267
|
+
return []
|
|
268
|
+
try:
|
|
269
|
+
connection = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True,
|
|
270
|
+
timeout=2)
|
|
271
|
+
except sqlite3.Error:
|
|
272
|
+
return []
|
|
273
|
+
try:
|
|
274
|
+
return connection.execute(sql, parameters).fetchall()
|
|
275
|
+
except sqlite3.OperationalError as exc:
|
|
276
|
+
return None if "no such table: session_message" in str(exc) else []
|
|
277
|
+
except sqlite3.Error:
|
|
278
|
+
return []
|
|
279
|
+
finally:
|
|
280
|
+
connection.close()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _json_object(data: object) -> dict:
|
|
284
|
+
"""``data`` parsed as a JSON object, {} when it is anything else."""
|
|
285
|
+
try:
|
|
286
|
+
value = json.loads(data) if isinstance(data, str) else None
|
|
287
|
+
except ValueError:
|
|
288
|
+
return {}
|
|
289
|
+
return value if isinstance(value, dict) else {}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _iso(milliseconds: object) -> str:
|
|
293
|
+
"""An epoch time in milliseconds as ISO UTC, "" when there is none."""
|
|
294
|
+
if not token_count(milliseconds):
|
|
295
|
+
return ""
|
|
296
|
+
moment = datetime.fromtimestamp(milliseconds / 1000, timezone.utc)
|
|
297
|
+
return moment.isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _message_entries(data: str) -> list[PeepEntry]:
|
|
301
|
+
"""The steps one assistant message carries: what the model thought, said or ran.
|
|
302
|
+
|
|
303
|
+
Tool output is left out; the call says what the agent is doing.
|
|
304
|
+
"""
|
|
305
|
+
message = _json_object(data)
|
|
306
|
+
time = message.get("time")
|
|
307
|
+
created = time.get("created") if isinstance(time, dict) else None
|
|
308
|
+
content = message.get("content")
|
|
309
|
+
entries = []
|
|
310
|
+
for block in content if isinstance(content, list) else []:
|
|
311
|
+
if not isinstance(block, dict):
|
|
312
|
+
continue
|
|
313
|
+
time = block.get("time")
|
|
314
|
+
timestamp = _iso((time.get("created") if isinstance(time, dict)
|
|
315
|
+
else None) or created)
|
|
316
|
+
kind = block.get("type")
|
|
317
|
+
text = str(block.get("text") or "")
|
|
318
|
+
if kind == "reasoning" and text.strip():
|
|
319
|
+
entries.append(PeepEntry("thinking", clip(text), timestamp))
|
|
320
|
+
elif kind == "text" and text.strip():
|
|
321
|
+
entries.append(PeepEntry("text", clip(text), timestamp))
|
|
322
|
+
elif kind == "tool":
|
|
323
|
+
state = block.get("state")
|
|
324
|
+
entries.append(PeepEntry("tool", tool_summary(
|
|
325
|
+
str(block.get("name") or "tool"),
|
|
326
|
+
state.get("input") if isinstance(state, dict) else None),
|
|
327
|
+
timestamp))
|
|
328
|
+
return entries
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _context_window(provider: str, model: str) -> int:
|
|
332
|
+
"""How many tokens ``model`` takes in, from OpenCode's models.dev catalog.
|
|
333
|
+
|
|
334
|
+
Its input limit where the catalog gives one (that is what OpenCode
|
|
335
|
+
compacts against), else its whole context. 0 for a model the catalog
|
|
336
|
+
doesn't list, such as one configured by hand.
|
|
337
|
+
"""
|
|
338
|
+
if not provider or not model or '"' in provider + model:
|
|
339
|
+
return 0
|
|
340
|
+
rows = _query(_MODEL_LIMIT,
|
|
341
|
+
(f'$."{provider}".models."{model}".limit', CATALOG_KEY))
|
|
342
|
+
limit = _json_object(rows[0][0]) if rows else {}
|
|
343
|
+
return token_count(limit.get("input")) or token_count(limit.get("context"))
|
|
344
|
+
|
|
345
|
+
|
|
187
346
|
def _relative(path: Path, cwd: Path) -> str:
|
|
188
347
|
try:
|
|
189
348
|
return str(path.relative_to(cwd))
|
codee_agent_opencode/test.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import io
|
|
2
2
|
import json
|
|
3
|
+
import os
|
|
4
|
+
import sqlite3
|
|
3
5
|
import subprocess
|
|
4
6
|
import tempfile
|
|
5
7
|
import unittest
|
|
@@ -204,3 +206,126 @@ class OpenCodeRunTest(unittest.TestCase):
|
|
|
204
206
|
|
|
205
207
|
if __name__ == "__main__":
|
|
206
208
|
unittest.main()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class OpenCodeSessionTest(unittest.TestCase):
|
|
212
|
+
"""Peep and context usage, read from OpenCode's SQLite database."""
|
|
213
|
+
|
|
214
|
+
SESSION = "ses_f0d0cbe84ffeNWiy62O86QX1MO"
|
|
215
|
+
|
|
216
|
+
def _database(self, data_home: str, *messages: tuple[str, dict],
|
|
217
|
+
catalog: dict | None = None) -> None:
|
|
218
|
+
folder = Path(data_home) / "opencode"
|
|
219
|
+
folder.mkdir()
|
|
220
|
+
connection = sqlite3.connect(folder / "opencode.db")
|
|
221
|
+
connection.execute(
|
|
222
|
+
"CREATE TABLE session_message (id text PRIMARY KEY, "
|
|
223
|
+
"session_id text NOT NULL, type text NOT NULL, "
|
|
224
|
+
"seq integer NOT NULL, time_created integer NOT NULL, "
|
|
225
|
+
"time_updated integer NOT NULL, data text NOT NULL)")
|
|
226
|
+
connection.execute(
|
|
227
|
+
"CREATE TABLE kv (key text PRIMARY KEY, value text NOT NULL, "
|
|
228
|
+
"time_created integer NOT NULL, time_updated integer NOT NULL)")
|
|
229
|
+
for seq, (kind, data) in enumerate(messages):
|
|
230
|
+
connection.execute(
|
|
231
|
+
"INSERT INTO session_message VALUES (?, ?, ?, ?, 0, 0, ?)",
|
|
232
|
+
(f"msg_{seq}", self.SESSION, kind, seq, json.dumps(data)))
|
|
233
|
+
connection.execute(
|
|
234
|
+
"INSERT INTO session_message VALUES ('other', 'ses_other', "
|
|
235
|
+
"'assistant', 0, 0, 0, ?)",
|
|
236
|
+
(json.dumps({"content": [{"type": "text", "text": "Not mine"}]}),))
|
|
237
|
+
if catalog is not None:
|
|
238
|
+
connection.execute(
|
|
239
|
+
"INSERT INTO kv VALUES ('models-dev:catalog', ?, 0, 0)",
|
|
240
|
+
(json.dumps({"updatedAt": 0, "body": json.dumps(catalog)}),))
|
|
241
|
+
connection.commit()
|
|
242
|
+
connection.close()
|
|
243
|
+
|
|
244
|
+
def _assistant(self, *content: dict, tokens: dict | None = None,
|
|
245
|
+
created: int = 1790782423879) -> tuple[str, dict]:
|
|
246
|
+
return ("assistant", {
|
|
247
|
+
"time": {"created": created},
|
|
248
|
+
"model": {"id": "gpt-5-mini", "providerID": "github-copilot"},
|
|
249
|
+
"content": list(content),
|
|
250
|
+
"tokens": tokens or {"input": 0, "output": 0, "reasoning": 0,
|
|
251
|
+
"cache": {"read": 0, "write": 0}}})
|
|
252
|
+
|
|
253
|
+
def test_reads_the_last_steps_of_the_session(self) -> None:
|
|
254
|
+
with tempfile.TemporaryDirectory() as data_home:
|
|
255
|
+
self._database(
|
|
256
|
+
data_home,
|
|
257
|
+
("user", {"text": "/nightly"}),
|
|
258
|
+
self._assistant(
|
|
259
|
+
{"type": "reasoning", "text": "Reading the logs first.",
|
|
260
|
+
"time": {"created": 1790782427293}},
|
|
261
|
+
{"type": "tool", "name": "read", "state": {
|
|
262
|
+
"status": "completed",
|
|
263
|
+
"input": {"filePath": "/repo/app.log"},
|
|
264
|
+
"output": "secret output"}}),
|
|
265
|
+
("compaction", {"status": "completed", "summary": "..."}),
|
|
266
|
+
self._assistant({"type": "text", "text": "Found it."}))
|
|
267
|
+
with patch.dict(os.environ, {"XDG_DATA_HOME": data_home}):
|
|
268
|
+
steps = OpenCodeAgent.peep(self.SESSION, Path("/repo"))
|
|
269
|
+
|
|
270
|
+
self.assertEqual(
|
|
271
|
+
[(step.kind, step.text) for step in steps],
|
|
272
|
+
[("thinking", "Reading the logs first."),
|
|
273
|
+
("tool", "read: /repo/app.log"),
|
|
274
|
+
("text", "Found it.")])
|
|
275
|
+
self.assertEqual(steps[0].timestamp, "2026-09-30T15:33:47.293Z")
|
|
276
|
+
self.assertEqual(steps[1].timestamp, "2026-09-30T15:33:43.879Z")
|
|
277
|
+
|
|
278
|
+
def test_reads_the_last_finished_calls_tokens_and_counts_compactions(
|
|
279
|
+
self) -> None:
|
|
280
|
+
with tempfile.TemporaryDirectory() as data_home:
|
|
281
|
+
self._database(
|
|
282
|
+
data_home,
|
|
283
|
+
self._assistant(tokens={"input": 90000, "output": 10,
|
|
284
|
+
"reasoning": 0,
|
|
285
|
+
"cache": {"read": 0, "write": 0}}),
|
|
286
|
+
("compaction", {"status": "completed", "reason": "auto"}),
|
|
287
|
+
("compaction", {"status": "running"}),
|
|
288
|
+
self._assistant(tokens={"input": 600, "output": 100,
|
|
289
|
+
"reasoning": 50,
|
|
290
|
+
"cache": {"read": 30000,
|
|
291
|
+
"write": 250}}),
|
|
292
|
+
# Still streaming: its tokens aren't in yet.
|
|
293
|
+
self._assistant({"type": "text", "text": "Working"}),
|
|
294
|
+
catalog={"github-copilot": {"models": {"gpt-5-mini": {
|
|
295
|
+
"limit": {"context": 264000, "input": 128000,
|
|
296
|
+
"output": 64000}}}}})
|
|
297
|
+
with patch.dict(os.environ, {"XDG_DATA_HOME": data_home}):
|
|
298
|
+
usage = OpenCodeAgent.context_usage(self.SESSION, Path("/"))
|
|
299
|
+
|
|
300
|
+
self.assertEqual((usage.tokens, usage.window, usage.compactions),
|
|
301
|
+
(31000, 128000, 1))
|
|
302
|
+
|
|
303
|
+
def test_a_model_the_catalog_doesnt_list_has_no_window(self) -> None:
|
|
304
|
+
with tempfile.TemporaryDirectory() as data_home:
|
|
305
|
+
self._database(
|
|
306
|
+
data_home,
|
|
307
|
+
self._assistant(tokens={"input": 500, "output": 0,
|
|
308
|
+
"reasoning": 0,
|
|
309
|
+
"cache": {"read": 0, "write": 0}}),
|
|
310
|
+
catalog={"anthropic": {"models": {}}})
|
|
311
|
+
with patch.dict(os.environ, {"XDG_DATA_HOME": data_home}):
|
|
312
|
+
usage = OpenCodeAgent.context_usage(self.SESSION, Path("/"))
|
|
313
|
+
|
|
314
|
+
self.assertEqual((usage.tokens, usage.window), (500, 0))
|
|
315
|
+
|
|
316
|
+
def test_no_database_yet_means_nothing_to_show(self) -> None:
|
|
317
|
+
with tempfile.TemporaryDirectory() as data_home:
|
|
318
|
+
with patch.dict(os.environ, {"XDG_DATA_HOME": data_home}):
|
|
319
|
+
self.assertEqual(
|
|
320
|
+
OpenCodeAgent.peep(self.SESSION, Path("/")), [])
|
|
321
|
+
self.assertIsNone(
|
|
322
|
+
OpenCodeAgent.context_usage(self.SESSION, Path("/")))
|
|
323
|
+
|
|
324
|
+
def test_an_opencode_before_2_cannot_be_read(self) -> None:
|
|
325
|
+
with tempfile.TemporaryDirectory() as data_home:
|
|
326
|
+
folder = Path(data_home) / "opencode"
|
|
327
|
+
folder.mkdir()
|
|
328
|
+
sqlite3.connect(folder / "opencode.db").close()
|
|
329
|
+
with patch.dict(os.environ, {"XDG_DATA_HOME": data_home}):
|
|
330
|
+
self.assertIsNone(
|
|
331
|
+
OpenCodeAgent.peep(self.SESSION, Path("/")))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|