ReMe/tests/unit/test_codex_tool_statistics.py
jinliyl 3db84c735f
feat(agent)!: add file-native proactive runtimes and ReMe Desktop (#743)
* feat(agent): unify persistent sessions and native fork settings

* fix(agent): preserve continuation and rejected session settings

* feat(event_stream): add bounded durable event streams

* fix(agent): preserve session guards and execution policies

* Revert "fix(agent): preserve session guards and execution policies"

This reverts commit 02188565dc.

* refactor(agent)!: unify file-native proactive runtimes

Coordinate named cron and event agents through an application-owned runtime,
with per-agent memory, native session registries and Markdown reminders.
Initialize Chat and task memories once under reme_agents and remove the old
PA delivery APIs and duplicated session state.

Serialize temporary query ownership with collection, recover incomplete
session-registry appends, and migrate benchmark plugins to public file helpers.
Split model providers into registered modules without changing their behavior.

* feat(proactive): add speech and scheduled observation collectors

Add DashScope ASR/TTS components, restart-safe finance collectors and
five-minute screenshot/Codex dialogue observations with bilingual docs.

Use response receipt time for stock freshness and recover interrupted
work-observation cleanup without replaying committed dialogue.

* refactor(core)!: unify execution cleanup and remove legacy contracts

Track queued Agent operations through shutdown and deletion, keep retry
backoff bounded, and reuse the local process runner for Shell steps.
Reject BASE registrations and remove duplicate config/path helpers.

BREAKING CHANGE: plugin discovery requires package-only entry points
and plugin.yaml; FileLink.predicate and the dream.ProactiveResult alias
are removed. Rebuild old derived graph indexes from workspace notes.

* feat(agent)!: add desktop workspace and isolated inbox delivery

* chore(desktop): remove one-click restart launcher

* fix(agent): guard session content and persist incremental display history

* test(home): verify host network isolation across platforms

* refactor(agent)!: unify durable inbox components

* docs: illustrate personal and proactive agent runtimes

* Refactor agent streaming and durable reminder delivery

Project formal turns through one ordered transcript, with live snapshots until native history catches up. Render localized activity groups, stable Markdown blocks and paged conversation history.

Bound proactive batches and preserve retries, persist reminder links before delivery, and synchronize explicit user-read receipts across sessions. Remove the obsolete desktop receipt format.

* Align desktop streaming activity with Codex

Keep assistant progress in the conversation and fold reasoning into activity details. Normalize native command actions into file, directory, search and command summaries with localized disclosure and explicit completion.

Match user bubbles and activity styling while preserving streaming anchors, links and expansion state.

* docs: explain proactive agents and personal runtime

* Align proactive runtime settings and documentation

* Unify agent runtime APIs and resource collection

* Deduplicate proactive observations and respect market sessions

* Refine proactive sessions and screenshot filtering

* Add desktop background transparency and tab transitions

* Tighten observation validation and task prompts

* Align streaming tool display with canonical item snapshots

* Unify Agent identity, task memory, and session workflows

Use agent_name and agent_type across the runtime, APIs, collectors and Desktop.
Initialize task_memory into MEMORY.md and return memory paths for native edits.
Keep task questions in read-only forks and automatic runs in validated file stages.
Document current behavior and cover default conversation rendering and SDK forks.

* Unify active sessions and task files; remove prompt wording tests

* Refine proactive jobs and fix coverage reporting

* Remove unused desktop artifacts and protocol probe

* Simplify proactive runs and commit validated artifacts after model failures

* Allow daily summaries for new records without reminders

* refactor(proactive): improve proactive and cron agent prompts and workflow steps

- Update cron agent description to emphasize recording what happened and reporting results
- Change sleep reminder rule to be specifically tagged for proactive agent
- Rename query fields to proactive_query for clarity
- Streamline and clarify proactive agent workflow steps in English and Chinese versions
- Enhance task analysis and reminder decision logic with clearer instructions
- Revise today's summary update format and examples with time stamps and consistent headings
- Provide separate detailed steps for cron agent execution and reporting
- Ensure reminder generation logic is more precise and avoid assumptions about user knowledge

* Add notebook and task management with resilient agent cleanup

* Improve search accounting and desktop conversation controls

* Guard conversation reset against endpoint changes

* refactor(proactive): simplify session options and improve markdown link warnings

- Remove unused failure status detection and associated UI styling in activity component
- Simplify session_options method by removing unnecessary parameters and excessive prompt formatting
- Enhance _query method to handle task content and event inputs conditionally based on agent type
- Add static method to extract and decode markdown links ignoring code blocks
- Introduce _warn_local_links to log warnings on broken local links without failing artifact validation
- Integrate local link warnings into artifact reading flow for proactive and cron agents
- Modify tests to reflect session_options signature changes and verify local link warning behavior
- Ensure TASK.md is non-empty before task execution, enforcing content validation
- Refactor CSS to remove deprecated broken activity state styles
- Improve test coverage with parameterized tests for broken local link warnings under various scenarios

* fix(agent): preserve user edits and recover durable commits

* fix(agent): guard outbox writes and defer full inbox delivery

* fix(agent): preserve reminder eligibility and serialize lifecycle transitions

* Simplify proactive task storage and desktop protocol

* Make proactive timeline limits configurable

* test(proactive): remove prompt checks and redundant cases

* Unify proactive task APIs and documentation

* fix(proactive): preserve incomplete triggers and skip oversized reminders

* fix(proactive): preserve queued trigger types across task updates

* docs(proactive): improve instructions for recording scheduled task results

- Clarify steps to follow after completing the scheduled task work
- Specify writing `action: write` in frontmatter when overwriting the record file
- Simplify description of what to include in the record body
- Emphasize using only necessary tools for the task and writing the record
- Align English and Chinese instructions for consistency

* fix(proactive): keep scheduled time and bypass event cooldown for cron
2026-11-19 21:37:25 +08:00

119 lines
4.7 KiB
Python

"""Native tool accounting includes calls omitted from typed SDK history."""
# pylint: disable=missing-function-docstring
import json
from types import SimpleNamespace
import pytest
from reme.components.agent_wrapper.codex_session_history import read_tool_calls
from reme.components.codex_app_server._session_history import item_chunks
from reme.enumeration import ChunkEnum
@pytest.mark.parametrize("kind", ["imageView", "imageGeneration", "clock", "sleep"])
def test_native_tools_have_stable_call_and_result_ids(kind):
item = SimpleNamespace(id="call-1", type=kind, model_dump=lambda **_: {"id": "call-1", "type": kind})
start = item_chunks(item, event="start")[0]
end = item_chunks(item, event="end")[0]
assert start.chunk_type == ChunkEnum.TOOL_CALL and end.chunk_type == ChunkEnum.TOOL_RESULT
assert start.tool_call_id == end.tool_call_id == "call-1"
def test_raw_turn_calls_include_rejected_tools_and_native_search_actions(tmp_path):
directory = tmp_path / "sessions"
directory.mkdir()
path = directory / "rollout-2026-11-19-session-1.jsonl"
records = [
{"type": "turn_context", "payload": {"turn_id": "older"}},
{"type": "response_item", "payload": {"type": "function_call", "call_id": "old", "name": "exec_command"}},
{"type": "turn_context", "payload": {"turn_id": "current"}},
{
"type": "response_item",
"payload": {
"type": "function_call",
"call_id": "search",
"name": "exec_command",
"arguments": '{"cmd":"rg error daily"}',
},
},
{
"type": "event_msg",
"payload": {
"type": "item_completed",
"item": {"id": "search", "parsed_cmd": [{"type": "search", "query": "error", "path": "daily"}]},
},
},
{
"type": "response_item",
"payload": {
"type": "custom_tool_call",
"call_id": "rejected",
"name": "apply_patch",
"input": "invalid patch",
},
},
{
"type": "response_item",
"payload": {
"type": "function_call",
"call_id": "image",
"name": "view_image",
"arguments": '{"path":"image.png"}',
},
},
{
"type": "response_item",
"payload": {
"type": "web_search_call",
"id": "web",
"action": {"type": "search", "queries": ["one", "two"]},
},
},
]
path.write_text("".join(json.dumps(record) + "\n" for record in records) + '{"unfinished":')
calls = read_tool_calls(path, tmp_path, "current")
assert [call["id"] for call in calls] == ["search", "rejected", "image", "web"]
assert calls[0]["actions"] == [{"type": "search", "query": "error", "path": "daily"}]
assert calls[1]["arguments"] == "invalid patch"
assert calls[-1]["name"] == "web_search"
assert len(read_tool_calls(path, tmp_path)) == 5
assert read_tool_calls(tmp_path / "not-created.jsonl", tmp_path) is None
assert read_tool_calls(None, tmp_path) is None
def test_tool_statistics_preserve_history_containment(tmp_path):
with pytest.raises(ValueError, match="outside its configured home"):
read_tool_calls(tmp_path.parent / "escape.jsonl", tmp_path)
def test_nested_tools_are_counted_even_without_response_item_calls(tmp_path):
directory = tmp_path / "sessions"
directory.mkdir()
records = [
{"type": "turn_context", "payload": {"turn_id": "current"}},
{
"type": "response_item",
"payload": {"type": "custom_tool_call", "call_id": "parent", "name": "exec", "input": "run tools"},
},
*[
{"type": "event_msg", "payload": {"type": "item_completed", "item": item}}
for item in [
{"type": "ImageView", "id": "image", "path": "file:///screen.png"},
{"type": "Clock", "id": "clock"},
{
"type": "CommandExecution",
"id": "search",
"command": "cd daily; rg status . | head",
"parsed_cmd": [{"type": "unknown"}],
},
{"type": "Reasoning", "id": "reasoning"},
]
],
]
path = directory / "rollout-2026-11-19-session-1.jsonl"
path.write_text("".join(json.dumps(r) + "\n" for r in records))
calls = read_tool_calls(path, tmp_path, "current")
assert [c["id"] for c in calls] == ["parent", "image", "clock", "search"]
assert calls[-1]["arguments"]["command"] == "cd daily; rg status . | head"