coder-agent 0.1.0__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 (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,82 @@
1
+ """The sandbox: the place where the commands of the agent run.
2
+
3
+ The local sandbox runs the commands on the machine of the user. The other
4
+ sandboxes are containers: a Docker container through SWE-ReX, Modal, bubblewrap
5
+ or contree. They are chosen with `sandbox.type` in the configuration:
6
+
7
+ ```yaml
8
+ sandbox:
9
+ type: swerex_docker
10
+ image: python:3.11
11
+ ```
12
+
13
+ The options that the environment does not know are ignored.
14
+
15
+ The `sandbox.mode` says how much the commands may do on this machine:
16
+ `read-only`, `workspace-write` or `full-access`. The modes are enforced by
17
+ the operating system (see `coderagent.core.os_sandbox`), so they hold even
18
+ when the permission layer lets everything through.
19
+ """
20
+
21
+ from importlib import import_module
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from coderagent.config.schema import ENVIRONMENT_CLASSES, ENVIRONMENT_TYPES, SandboxConfig
26
+ from coderagent.core.os_sandbox import FULL_ACCESS
27
+ from coderagent.environments import is_local
28
+ from coderagent.tools.builtin.shell import CodingEnvironment
29
+
30
+ LOCAL = "local"
31
+
32
+
33
+ def sandbox_class(kind: str) -> type:
34
+ """The class of the environment that the name stands for.
35
+
36
+ A dotted path is a way to name any environment: the class of the user.
37
+ """
38
+ path = ENVIRONMENT_CLASSES.get(kind, kind)
39
+ if "." not in path:
40
+ raise ValueError(f"unknown sandbox '{kind}'. Use one of: {', '.join(ENVIRONMENT_TYPES)}.")
41
+ module_name, class_name = path.rsplit(".", 1)
42
+ try:
43
+ return getattr(import_module(module_name), class_name)
44
+ except ImportError as error:
45
+ if kind not in ENVIRONMENT_CLASSES:
46
+ raise
47
+ raise ImportError(
48
+ f"The sandbox '{kind}' needs the packages of the remote sandboxes: pip install 'coder-agent[sandbox]'"
49
+ ) from error
50
+
51
+
52
+ def build_environment(config: SandboxConfig, cwd: Path) -> Any:
53
+ """The environment of the session."""
54
+ if config.type == LOCAL:
55
+ return CodingEnvironment(cwd=str(cwd))
56
+ options = config.model_dump(exclude={"type"})
57
+ kind = options.pop("environment_class", config.type)
58
+ """The way of mini-swe-agent to name an environment, kept for the old configurations."""
59
+ environment = sandbox_class(kind)(**options)
60
+ if is_local(environment):
61
+ """A local environment works in the directory of the session."""
62
+ environment.config.cwd = str(cwd)
63
+ if hasattr(environment, "_check_finished"):
64
+ """A coding agent ends a turn when the model says so, not when a command prints a sentinel."""
65
+ environment._check_finished = lambda output: None
66
+ return environment
67
+
68
+
69
+ def describe(environment: Any, kind: str = "", mode: str = "") -> str:
70
+ """The name of the environment, for the interface."""
71
+ if kind and kind != LOCAL:
72
+ return kind
73
+ if not kind:
74
+ kind = (
75
+ LOCAL if environment is None or isinstance(environment, CodingEnvironment) else type(environment).__name__
76
+ )
77
+ if mode and mode != FULL_ACCESS and kind == LOCAL:
78
+ return f"{LOCAL}/{mode}"
79
+ return kind
80
+
81
+
82
+ __all__ = ["LOCAL", "build_environment", "describe", "sandbox_class"]
@@ -0,0 +1,107 @@
1
+ """The shape the answer of the agent has to have.
2
+
3
+ The model is asked for JSON that fits a schema, and the answer is checked
4
+ against it here. The schema is a small part of JSON Schema: the keywords that
5
+ say what a value is and what it holds. That is on purpose: the repository does
6
+ not carry a validator, and a schema that nobody checks is a schema that lies.
7
+ """
8
+
9
+ import json
10
+ from typing import Any
11
+
12
+ TYPES = {
13
+ "object": lambda value: isinstance(value, dict),
14
+ "array": lambda value: isinstance(value, list),
15
+ "string": lambda value: isinstance(value, str),
16
+ "number": lambda value: isinstance(value, (int, float)) and not isinstance(value, bool),
17
+ "integer": lambda value: isinstance(value, int) and not isinstance(value, bool),
18
+ "boolean": lambda value: isinstance(value, bool),
19
+ "null": lambda value: value is None,
20
+ }
21
+ """How a value of each type is recognized. A boolean is not a number."""
22
+
23
+
24
+ def validate(value: Any, schema: dict, where: str = "") -> list[str]:
25
+ """The ways the value does not fit the schema. An empty list means it fits."""
26
+ if not isinstance(schema, dict):
27
+ return []
28
+ errors = []
29
+ if value is None and schema.get("nullable"):
30
+ """A value that may be nothing fits, whatever its type says."""
31
+ return []
32
+ label = f"'{where}'" if where else "the answer"
33
+ expected = schema.get("type")
34
+ if expected:
35
+ names = expected if isinstance(expected, list) else [expected]
36
+ if not any(TYPES.get(name, lambda _value: True)(value) for name in names):
37
+ return [f"{label} must be {' or '.join(str(name) for name in names)}"]
38
+ if "enum" in schema and value not in schema["enum"]:
39
+ errors.append(f"{label} must be one of {schema['enum']}")
40
+ if isinstance(value, dict):
41
+ errors.extend(_object_errors(value, schema, where))
42
+ if isinstance(value, list) and isinstance(schema.get("items"), dict):
43
+ for index, item in enumerate(value):
44
+ errors.extend(validate(item, schema["items"], f"{where}[{index}]"))
45
+ return errors
46
+
47
+
48
+ def _object_errors(value: dict, schema: dict, where: str) -> list[str]:
49
+ """The ways the object does not fit the schema."""
50
+ errors = []
51
+ properties = schema.get("properties") if isinstance(schema.get("properties"), dict) else {}
52
+ for name in schema.get("required") or []:
53
+ if name not in value:
54
+ errors.append(f"{where or 'the answer'} is missing '{name}'")
55
+ for name, item in value.items():
56
+ if name in properties:
57
+ errors.extend(validate(item, properties[name], f"{where}.{name}" if where else name))
58
+ elif schema.get("additionalProperties") is False:
59
+ errors.append(f"{where or 'the answer'} has the unknown field '{name}'")
60
+ return errors
61
+
62
+
63
+ def parse(text: str) -> tuple[Any, str]:
64
+ """The JSON in the text, and the reason when there is none.
65
+
66
+ The answer of a model is often wrapped in a code fence, and sometimes it
67
+ has a sentence in front of it. Both are read.
68
+ """
69
+ stripped = text.strip()
70
+ if stripped.startswith("```"):
71
+ lines = stripped.splitlines()[1:]
72
+ stripped = "\n".join(lines).strip().removesuffix("```").strip()
73
+ try:
74
+ return json.loads(stripped), ""
75
+ except json.JSONDecodeError:
76
+ """The text is not JSON on its own. There may be an object in it."""
77
+ pass
78
+ start = stripped.find("{")
79
+ end = stripped.rfind("}")
80
+ if 0 <= start < end:
81
+ """There is an object in there: the text around it does not matter."""
82
+ try:
83
+ return json.loads(stripped[start : end + 1]), ""
84
+ except json.JSONDecodeError as error:
85
+ return None, _reason(error)
86
+ return None, _reason(None)
87
+
88
+
89
+ def _reason(error: json.JSONDecodeError | None) -> str:
90
+ """Why the answer is not JSON."""
91
+ if error is None:
92
+ return "the answer is not valid JSON: there is no JSON in it"
93
+ return f"the answer is not valid JSON: {error.msg} (line {error.lineno}, column {error.colno})"
94
+
95
+
96
+ def note(schema: dict) -> str:
97
+ """What the model is told about the schema it has to fit."""
98
+ return (
99
+ "<output_schema>\n"
100
+ f"{json.dumps(schema, ensure_ascii=False, indent=2)}\n"
101
+ "</output_schema>\n"
102
+ "Your answer must be JSON that fits this schema. "
103
+ "Answer with the JSON only: no prose, no explanation, no code fences."
104
+ )
105
+
106
+
107
+ __all__ = ["TYPES", "note", "parse", "validate"]
@@ -0,0 +1,344 @@
1
+ """Session state and its persistence. Events are the source of truth, the session is derived."""
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import time
7
+ import uuid
8
+ from dataclasses import dataclass, field
9
+ from enum import Enum
10
+ from pathlib import Path
11
+
12
+ from coderagent.core.events import Event, EventType
13
+ from coderagent.core.telemetry import collect
14
+ from coderagent.models.backends import has_price
15
+ from coderagent.paths import config_home
16
+
17
+ logger = logging.getLogger("coderagent.core.session")
18
+
19
+ PERSISTENCES = ("save-all", "save-none")
20
+ """How the history of the sessions is kept: on the disk, or nowhere."""
21
+
22
+
23
+ class SessionState(str, Enum):
24
+ IDLE = "idle"
25
+ THINKING = "thinking"
26
+ EXECUTING = "executing"
27
+ AWAITING_APPROVAL = "awaiting_approval"
28
+ DONE = "done"
29
+ ERROR = "error"
30
+
31
+
32
+ SUMMARY_LIMIT = 40
33
+ """How many characters of the first question the list of sessions shows."""
34
+
35
+
36
+ def summarize(text: str, limit: int = SUMMARY_LIMIT) -> str:
37
+ """A short title for a session: the first question, on one line, cut short."""
38
+ line = " ".join(str(text).split())
39
+ if len(line) <= limit:
40
+ return line
41
+ return line[:limit].rstrip() + "…"
42
+
43
+
44
+ @dataclass
45
+ class Session:
46
+ id: str
47
+ cwd: Path
48
+ created_at: float
49
+ updated_at: float
50
+ state: SessionState = SessionState.IDLE
51
+ model_name: str = ""
52
+ permission_mode: str = "default"
53
+ turn_count: int = 0
54
+ total_cost: float = 0.0
55
+ total_tokens: int = 0
56
+ """The tokens of the session, in and out. The budget of a model that has no price."""
57
+ name: str = ""
58
+ """The name the user gave to the session."""
59
+ summary: str = ""
60
+ """The first question of the session, cut short. It is what the list shows."""
61
+ archived: bool = False
62
+ """Whether the session is put away. An archived session is not in the list."""
63
+ metadata: dict = field(default_factory=dict)
64
+
65
+
66
+ def session_priced(session: Session, fallback_model: str = "") -> bool:
67
+ """Whether the money of a session is known.
68
+
69
+ A model without a price spends no money: the cost of the session is unknown,
70
+ not zero. A session that has not called a model yet belongs to the model of
71
+ the agent that holds it, so that is where its price is looked up.
72
+ """
73
+ model = session.metadata.get("model") or fallback_model
74
+ return bool(session.metadata.get("priced", True)) and (not model or has_price(model))
75
+
76
+
77
+ def default_root() -> Path:
78
+ """Directory holding all session files. Overridable via `MSWEA_CODER_HOME`."""
79
+ return config_home() / "sessions"
80
+
81
+
82
+ class SessionStore:
83
+ """Append-only JSONL event log. Replaying the log rebuilds the session."""
84
+
85
+ def __init__(self, root: Path | None = None, *, persist: bool = True, max_bytes: int = 0) -> None:
86
+ self.root = Path(root) if root else default_root()
87
+ self.persist = persist
88
+ """Whether the history is written to the disk. When it is not, the session lives in memory."""
89
+ self.max_bytes = max_bytes
90
+ """The bytes the history of all the sessions may take. 0 means no limit."""
91
+ self._size = 0
92
+ """The bytes the history takes, as far as it is known."""
93
+ self._measured = False
94
+ """Whether the size of the history has been measured on the disk."""
95
+
96
+ def create(self, cwd: Path) -> Session:
97
+ session = Session(
98
+ id=f"{time.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6]}",
99
+ cwd=Path(cwd),
100
+ created_at=time.time(),
101
+ updated_at=time.time(),
102
+ )
103
+ if not self.persist:
104
+ """The history is not kept, so there is nothing to write."""
105
+ return session
106
+ self.root.mkdir(parents=True, exist_ok=True)
107
+ self._write_meta(session)
108
+ self.append(
109
+ session.id,
110
+ Event(
111
+ type=EventType.STATE_CHANGE,
112
+ session_id=session.id,
113
+ timestamp=session.created_at,
114
+ payload={"state": session.state.value, "cwd": str(session.cwd), "created_at": session.created_at},
115
+ ),
116
+ )
117
+ return session
118
+
119
+ def path(self, session_id: str) -> Path:
120
+ return self.root / f"{session_id}.jsonl"
121
+
122
+ def meta_path(self, session_id: str) -> Path:
123
+ return self.root / f"{session_id}.meta.json"
124
+
125
+ def append(self, session_id: str, event: Event) -> None:
126
+ if not self.persist:
127
+ return
128
+ self.root.mkdir(parents=True, exist_ok=True)
129
+ line = json.dumps(event.to_dict(), ensure_ascii=False) + "\n"
130
+ with self.path(session_id).open("a", encoding="utf-8") as f:
131
+ f.write(line)
132
+ f.flush()
133
+ os.fsync(f.fileno())
134
+ self._size += len(line.encode("utf-8"))
135
+ if self.max_bytes:
136
+ if not self._measured:
137
+ self._size = self._total_size()
138
+ self._measured = True
139
+ if self._size > self.max_bytes:
140
+ self._prune(session_id)
141
+
142
+ def events(self, session_id: str) -> list[Event]:
143
+ path = self.path(session_id)
144
+ if not path.exists():
145
+ return []
146
+ events = []
147
+ for line in path.read_text(encoding="utf-8").splitlines():
148
+ if not line.strip():
149
+ continue
150
+ try:
151
+ event = Event.from_dict(json.loads(line))
152
+ except json.JSONDecodeError:
153
+ logger.warning("A line of the session log is broken, it is skipped: %s", line[:120])
154
+ continue
155
+ if event is not None:
156
+ events.append(event)
157
+ return events
158
+
159
+ def rebuild(self, session_id: str) -> Session:
160
+ """Replay the event log to get the current session state."""
161
+ session = Session(id=session_id, cwd=Path("."), created_at=0.0, updated_at=0.0)
162
+ events = self.events(session_id)
163
+ for event in events:
164
+ payload = event.payload
165
+ if event.type == EventType.STATE_CHANGE:
166
+ session.state = SessionState(payload.get("state", session.state.value))
167
+ if "cwd" in payload:
168
+ session.cwd = Path(payload["cwd"])
169
+ if "created_at" in payload:
170
+ session.created_at = payload["created_at"]
171
+ if "model_name" in payload:
172
+ session.model_name = payload["model_name"]
173
+ if "permission_mode" in payload:
174
+ session.permission_mode = payload["permission_mode"]
175
+ if "name" in payload:
176
+ session.name = payload["name"]
177
+ if "archived" in payload:
178
+ session.archived = bool(payload["archived"])
179
+ if "parent" in payload:
180
+ session.metadata["parent"] = payload["parent"]
181
+ elif event.type == EventType.USER_MESSAGE:
182
+ session.turn_count += 1
183
+ if not session.summary:
184
+ """The first question of the session is what the list shows."""
185
+ session.summary = summarize(payload.get("original") or payload.get("content", ""))
186
+ elif event.type == EventType.TOOL_RESULT and payload.get("todos"):
187
+ session.metadata["todos"] = payload["todos"]
188
+ elif event.type == EventType.TURN_END:
189
+ session.metadata["stop_reason"] = payload.get("stop_reason", "")
190
+ session.updated_at = event.timestamp
191
+ # The cost of the session is the cost of every call in the log, the sub agents included.
192
+ metrics = collect(events)
193
+ session.total_cost = metrics.total_cost
194
+ session.total_tokens = metrics.total_tokens_in + metrics.total_tokens_out
195
+ session.metadata["priced"] = metrics.priced
196
+ """A model without a price: the money of the session is unknown, not zero."""
197
+ session.metadata["model"] = next(reversed(metrics.per_model_cost), "")
198
+ """The model that made the calls of the session. Empty when there were none."""
199
+ return session
200
+
201
+ def list(self, cwd: Path | None = None, archived: bool | None = None) -> list[Session]:
202
+ """All sessions, newest first. Optionally restricted to a working directory.
203
+
204
+ `archived` says which ones are wanted: the ones that are put away, the ones
205
+ that are not, or all of them.
206
+ """
207
+ if not self.root.exists():
208
+ return []
209
+ sessions = []
210
+ for meta_path in self.root.glob("*.meta.json"):
211
+ try:
212
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
213
+ except (json.JSONDecodeError, OSError):
214
+ logger.warning("The meta file of a session is broken, it is skipped: %s", meta_path)
215
+ continue
216
+ if cwd is not None and Path(meta.get("cwd", "")) != Path(cwd):
217
+ continue
218
+ session = self.rebuild(meta["id"])
219
+ if archived is not None and session.archived != archived:
220
+ continue
221
+ sessions.append(session)
222
+ return sorted(sessions, key=lambda s: s.created_at, reverse=True)
223
+
224
+ def fork(self, session_id: str) -> Session:
225
+ """Copy a session into a new one. The original stays untouched."""
226
+ source = self.rebuild(session_id)
227
+ forked = Session(
228
+ id=f"{time.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6]}",
229
+ cwd=source.cwd,
230
+ created_at=time.time(),
231
+ updated_at=time.time(),
232
+ model_name=source.model_name,
233
+ permission_mode=source.permission_mode,
234
+ )
235
+ self.root.mkdir(parents=True, exist_ok=True)
236
+ self._write_meta(forked)
237
+ for event in self.events(session_id):
238
+ self.append(
239
+ forked.id,
240
+ Event(
241
+ type=event.type,
242
+ session_id=forked.id,
243
+ timestamp=event.timestamp,
244
+ payload=event.payload,
245
+ ),
246
+ )
247
+ self.append(
248
+ forked.id,
249
+ Event(
250
+ type=EventType.STATE_CHANGE,
251
+ session_id=forked.id,
252
+ timestamp=forked.created_at,
253
+ payload={
254
+ "state": source.state.value,
255
+ "cwd": str(forked.cwd),
256
+ "created_at": forked.created_at,
257
+ },
258
+ ),
259
+ )
260
+ return self.rebuild(forked.id)
261
+
262
+ def side(self, session_id: str) -> Session:
263
+ """A copy of a session, for a conversation that goes aside.
264
+
265
+ The copy knows its parent, so the session it came from is not lost.
266
+ The original is not touched.
267
+ """
268
+ side = self.fork(session_id)
269
+ self.append(
270
+ side.id,
271
+ Event(
272
+ type=EventType.STATE_CHANGE,
273
+ session_id=side.id,
274
+ timestamp=time.time(),
275
+ payload={"parent": session_id},
276
+ ),
277
+ )
278
+ return self.rebuild(side.id)
279
+
280
+ def _write_meta(self, session: Session) -> None:
281
+ meta = {
282
+ "id": session.id,
283
+ "cwd": str(session.cwd),
284
+ "created_at": session.created_at,
285
+ "model_name": session.model_name,
286
+ }
287
+ path = self.meta_path(session.id)
288
+ temporary = path.with_name(f"{path.name}.tmp")
289
+ temporary.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
290
+ os.replace(temporary, path)
291
+
292
+ # -- the life of a session ---------------------------------------------
293
+
294
+ def rename(self, session_id: str, name: str) -> bool:
295
+ """Give a session a name. Returns whether there is such a session."""
296
+ return self._state_event(session_id, {"name": name})
297
+
298
+ def archive(self, session_id: str, archived: bool = True) -> bool:
299
+ """Put a session away, or take it out again. Returns whether there is such a session."""
300
+ return self._state_event(session_id, {"archived": archived})
301
+
302
+ def delete(self, session_id: str) -> bool:
303
+ """Remove a session and everything in it. Returns whether there was such a session."""
304
+ path = self.path(session_id)
305
+ if not path.exists():
306
+ return False
307
+ path.unlink()
308
+ meta = self.meta_path(session_id)
309
+ if meta.exists():
310
+ meta.unlink()
311
+ return True
312
+
313
+ def _state_event(self, session_id: str, payload: dict) -> bool:
314
+ """Write a state of the session into its log."""
315
+ if not self.path(session_id).exists():
316
+ return False
317
+ self.append(
318
+ session_id,
319
+ Event(
320
+ type=EventType.STATE_CHANGE,
321
+ session_id=session_id,
322
+ timestamp=time.time(),
323
+ payload=payload,
324
+ ),
325
+ )
326
+ return True
327
+
328
+ def _total_size(self) -> int:
329
+ """The bytes the history of all the sessions takes."""
330
+ return sum(path.stat().st_size for path in self.root.glob("*.jsonl"))
331
+
332
+ def _prune(self, keep: str) -> None:
333
+ """Delete the oldest sessions until the history fits into the limit."""
334
+ logs = sorted(self.root.glob("*.jsonl"), key=lambda path: path.stat().st_mtime)
335
+ total = sum(path.stat().st_size for path in logs)
336
+ for path in logs:
337
+ if total <= self.max_bytes:
338
+ break
339
+ if path.stem == keep:
340
+ continue
341
+ """The session that is running is never deleted."""
342
+ total -= path.stat().st_size
343
+ self.delete(path.stem)
344
+ self._size = total
@@ -0,0 +1,74 @@
1
+ """The environment that the commands of the agent see.
2
+
3
+ The commands of the agent run on the machine of the user, and the environment
4
+ of the user holds the keys of the providers. The agent does not need them: the
5
+ model calls the provider from the process of the agent, not from the shell. A
6
+ key that the shell can print is a key that the model reads, and then the key
7
+ is in the transcript of the session.
8
+
9
+ So the keys stay out of the shell. The user may open them again with the
10
+ `include` list, when a script of the project needs one.
11
+ """
12
+
13
+ from fnmatch import fnmatchcase
14
+
15
+ CORE = (
16
+ "PATH",
17
+ "HOME",
18
+ "LANG",
19
+ "LC_ALL",
20
+ "LC_CTYPE",
21
+ "TERM",
22
+ "TMPDIR",
23
+ "TEMP",
24
+ "TMP",
25
+ "USER",
26
+ "LOGNAME",
27
+ "SHELL",
28
+ "TZ",
29
+ "PWD",
30
+ "SYSTEMROOT",
31
+ "COMSPEC",
32
+ "PATHEXT",
33
+ )
34
+ """The variables that a command needs to work at all."""
35
+
36
+ SECRETS = (
37
+ "*_API_KEY",
38
+ "*_KEY",
39
+ "*_TOKEN",
40
+ "*_SECRET",
41
+ "*_PASSWORD",
42
+ "*_PASSWD",
43
+ "*_CREDENTIALS",
44
+ "*_ACCESS_KEY",
45
+ )
46
+ """The patterns of the names that never reach the shell of the agent."""
47
+
48
+ INHERITS = ("all", "core", "none")
49
+ """How much of the environment of the user the agent sees."""
50
+
51
+
52
+ def build(inherit: str, exclude: list[str], include: list[str], overrides: dict, environ: dict) -> dict[str, str]:
53
+ """The environment the commands of the agent see."""
54
+ if inherit == "none":
55
+ env: dict[str, str] = {}
56
+ elif inherit == "core":
57
+ env = {name: value for name, value in environ.items() if name in CORE}
58
+ else:
59
+ env = dict(environ)
60
+ for name in [name for name in env if _hidden(name, exclude, include)]:
61
+ env.pop(name)
62
+ env.update(overrides)
63
+ return env
64
+
65
+
66
+ def _hidden(name: str, exclude: list[str], include: list[str]) -> bool:
67
+ """Whether a variable stays out of the shell of the agent."""
68
+ if any(fnmatchcase(name, pattern) for pattern in include):
69
+ """The user opened it again on purpose."""
70
+ return False
71
+ return any(fnmatchcase(name, pattern) for pattern in (*SECRETS, *exclude))
72
+
73
+
74
+ __all__ = ["CORE", "INHERITS", "SECRETS", "build"]