@lmmslab/harness 0.84.0 → 0.85.1
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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/python/harness/__init__.py +1 -1
- package/python/harness/builtin/prompts/core/core.md +48 -33
- package/python/harness/cli.py +37 -1
- package/python/harness/config/agent.py +3 -0
- package/python/harness/host/tasks.py +9 -1
- package/python/harness/instructions.py +329 -0
- package/python/harness/runtime/events.py +1 -0
- package/python/harness/runtime/execution/session.py +5 -3
- package/python/harness/runtime/reactive/tree.py +69 -39
- package/python/harness/runtime/task/environments.py +3 -1
- package/python/harness/runtime/task/run.py +68 -1
- package/python/harness/settings.py +18 -0
- package/python/harness/terminal.py +3 -0
- package/python/harness/transcript.py +12 -0
- package/python/harness/tui/chat.py +86 -19
- package/python/harness/tui/renderer.py +0 -33
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
<p align="center">
|
|
16
16
|
<a href="https://www.npmjs.com/package/@lmmslab/harness"><img alt="npm version" src="https://img.shields.io/npm/v/@lmmslab/harness?cacheSeconds=3600&style=flat-square&labelColor=112332&color=087f9c" /></a>
|
|
17
17
|
<a href="https://pypi.org/project/the-harness/"><img alt="PyPI version" src="https://img.shields.io/pypi/v/the-harness?cacheSeconds=3600&style=flat-square&labelColor=112332&color=087f9c" /></a>
|
|
18
|
-
<a href="https://discord.gg/
|
|
18
|
+
<a href="https://discord.gg/JbxU88aZyZ"><img alt="Discord community" src="https://img.shields.io/badge/discord-community-bc276e?style=flat-square&logo=discord&logoColor=white&labelColor=112332" /></a>
|
|
19
19
|
</p>
|
|
20
20
|
|
|
21
21
|
Tell an agent what to do in your own words. A language model plans and writes short programs; The Harness runs them in an environment the agent can see and act in. Watch, send a message, or take over at any time.
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# The one version: the core's. A lock records it with the versions of the packages that
|
|
4
4
|
# ran and the hash of the whole lock (the agent's identity, config/agent.py).
|
|
5
|
-
__version__ = "0.
|
|
5
|
+
__version__ = "0.85.1"
|
|
6
6
|
|
|
7
7
|
# A checkout's packages import beside the harness (paths.py).
|
|
8
8
|
from . import paths as _paths # noqa: E402,F401
|
|
@@ -42,32 +42,42 @@ what is already true needs no step, and the order follows from what is there.
|
|
|
42
42
|
The tree is designed as a whole, not grown from what went wrong last. Before you rely on
|
|
43
43
|
it, name every kind of thing that can happen to the agent where it is going to be: to
|
|
44
44
|
its condition, to where it stands, from what is around it, to what it is doing. The tree
|
|
45
|
-
divides all of that. A node is a situation: its condition says when the agent is in it
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
not
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
45
|
+
divides all of that. A node is a situation: its condition says when the agent is in it,
|
|
46
|
+
by what is happening to the agent, not by what causes it. What the node does is its
|
|
47
|
+
answer to the situation as such: something that fits whatever the cause, or telling you.
|
|
48
|
+
The nodes under it are the narrower situations within it that you know a better answer
|
|
49
|
+
for, each by its cause or circumstance. While one of them answers, the node itself does
|
|
50
|
+
not act; what is in the situation and in none of them gets the node's own answer. So a
|
|
51
|
+
node is complete from the moment it is set, and what you learn later goes under it
|
|
52
|
+
without changing it: write every node so. This holds at every depth, and how far a
|
|
53
|
+
situation is divided follows from how much you know of it. Design it from the top down.
|
|
54
|
+
Begin with the widest situations, each a respect in which something can be wrong for the
|
|
55
|
+
agent, and give each its node; then divide each into the narrower ones you already know.
|
|
56
|
+
What several conditions have in common is judged once, in the node above them, and each
|
|
57
|
+
of them says only what distinguishes it there. Prefer a deep tree to a wide one: a node
|
|
58
|
+
under another is judged only while that one's condition holds, so the narrow costs
|
|
59
|
+
nothing while the wide is quiet; and a wide node still answers the case you did not
|
|
60
|
+
list, where a row of cases has no node for it. A new node goes under the narrowest node
|
|
61
|
+
whose situation it falls in, and to the top only when it falls in none. The unexpected
|
|
62
|
+
has two forms, and the tree tells you of both. Something happens that no node answers.
|
|
63
|
+
Or what should happen does not: the agent goes on acting and what the action is for does
|
|
64
|
+
not come; the thing it should change stays as it was while time and supplies go. The
|
|
65
|
+
second is as much a situation of the agent as the first, and it is the one that passes
|
|
66
|
+
unnoticed, because nothing arrives. So for whatever is set going, a node watches what it
|
|
67
|
+
is for, and tells you when that stays away longer than it would if things were as you
|
|
68
|
+
assumed. Neither form may pass with no answer and without your hearing of it. What
|
|
69
|
+
happens to the agent whatever it is doing belongs in the tree, also when you met it
|
|
70
|
+
inside one program: answered there, it is answered nowhere else. What you set out to do
|
|
71
|
+
is not in it, however often you do it: a way of doing something that you have learned is
|
|
72
|
+
kept as a skill you call, not as a node. A node has done its work when its situation is
|
|
73
|
+
over: when its program ends and the situation is not over, a later node at its place has
|
|
74
|
+
the environment, or you are told what the program did. The tree is consistent when in
|
|
75
|
+
every situation it is settled which node has the environment: a node's place is what it
|
|
76
|
+
costs when it does not act now, the costlier the earlier; and a node takes the
|
|
77
|
+
environment only where you would, seeing everything as it is then. A reflex acts in your
|
|
78
|
+
place, so its condition is your whole judgement, what it interrupts and whether this is
|
|
79
|
+
the moment included, and what it does leaves things so that what it interrupted can go
|
|
80
|
+
on.
|
|
71
81
|
|
|
72
82
|
Build each thing for the situations it has to work in, and think and test in proportion
|
|
73
83
|
to what a failure costs: settle in the design what is cheap to settle; test what is
|
|
@@ -152,10 +162,12 @@ The calls every agent has:
|
|
|
152
162
|
<!-- end -->
|
|
153
163
|
<!-- end -->
|
|
154
164
|
What acts without you is one tree, empty at first. A node of it says when it has its
|
|
155
|
-
turn and what it does then
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
165
|
+
turn and what it does then. Any node may have nodes under it: one under another has its
|
|
166
|
+
turn only while that one's condition holds, and before it; what the node above does
|
|
167
|
+
itself comes when none under it is answering, and gives way when one of them begins.
|
|
168
|
+
Among the nodes at one place the earlier takes the environment from the later, and gives
|
|
169
|
+
it back when it is done. What several nodes read is a sense; what several do is a
|
|
170
|
+
function they call.
|
|
159
171
|
- set_reflex(name, when, do=None, under=None, priority=0, every=None, again_seconds=0):
|
|
160
172
|
put the node `name` into the tree, in place of a node of that name.
|
|
161
173
|
when: a function of the view: the node has its turn while it holds. It is judged
|
|
@@ -165,9 +177,12 @@ condition as the node above them or as a sense, an action as a function they cal
|
|
|
165
177
|
for is that the node's condition no longer holds. It begins again while the turn lasts,
|
|
166
178
|
not before again_seconds after it ended; a program that answers an event gets the event
|
|
167
179
|
when it takes an argument. Or the name of an event: you are told it, once each time
|
|
168
|
-
its turn comes, which is when its condition holds and no node before it at
|
|
169
|
-
is answering. Or "stop": what runs is ended.
|
|
170
|
-
Or nothing:
|
|
180
|
+
its turn comes, which is when its condition holds and no node under it or before it at
|
|
181
|
+
its place is answering. Or "stop": what runs is ended.
|
|
182
|
+
Or nothing: only the nodes under it answer.
|
|
183
|
+
under: the node `name` is a narrower situation within that one. A node may be put
|
|
184
|
+
under any node whose `when` is a condition, whatever that node does itself and without
|
|
185
|
+
setting it again.
|
|
171
186
|
priority (a whole number, 0 or more): the node's own, wherever it is in the tree. Of
|
|
172
187
|
two nodes whose turn it is the higher has the environment, among equals the earlier in
|
|
173
188
|
the tree; and it is the number a program's at_priority(n) is compared with. A node's
|
package/python/harness/cli.py
CHANGED
|
@@ -125,6 +125,9 @@ def run_flags(command):
|
|
|
125
125
|
command.add_argument("--agents", action="store_true",
|
|
126
126
|
help="sub-agents on in this conversation (they are off unless the setting session.agents "
|
|
127
127
|
"is on; the agent may also ask you to switch them on)")
|
|
128
|
+
command.add_argument("--bare", action="store_true",
|
|
129
|
+
help="read no instruction files (~/.harness/AGENTS.md, the project's AGENTS.md) in this "
|
|
130
|
+
"conversation")
|
|
128
131
|
|
|
129
132
|
|
|
130
133
|
def _coding_arguments(command):
|
|
@@ -372,6 +375,11 @@ def parser(packages: bool = True):
|
|
|
372
375
|
replay.add_argument("run", help="an episode directory, a conversation (its name under conversations/), or a "
|
|
373
376
|
"session (SESSION or SESSION/AGENT)")
|
|
374
377
|
replay.add_argument("--json", action="store_true", help="every record of its trace as a JSON line")
|
|
378
|
+
instructions = commands.add_parser("instructions", help="The instruction files (AGENTS.md) a conversation "
|
|
379
|
+
"working in FOLDER reads, and why others are left out")
|
|
380
|
+
instructions.add_argument("folder", nargs="?", type=Path, default=Path("."),
|
|
381
|
+
help="the conversation's folder (default: this one)")
|
|
382
|
+
instructions.add_argument("--json", action="store_true", help="the files as JSON")
|
|
375
383
|
doctor = commands.add_parser("doctor", help="Whether this computer can run the agent: Python, the model and its "
|
|
376
384
|
"key, the packages; or services, or an experiment (the eval "
|
|
377
385
|
"package's: harness doctor EXPERIMENT --help)",
|
|
@@ -663,6 +671,8 @@ def _run_options(args) -> dict:
|
|
|
663
671
|
options["learn"] = args.learn
|
|
664
672
|
if getattr(args, "agents", False):
|
|
665
673
|
options["agents"] = True
|
|
674
|
+
if getattr(args, "bare", False):
|
|
675
|
+
options["instructions"] = {"load": "off"}
|
|
666
676
|
return options
|
|
667
677
|
|
|
668
678
|
|
|
@@ -1226,6 +1236,32 @@ def _sessions(args):
|
|
|
1226
1236
|
return 0
|
|
1227
1237
|
|
|
1228
1238
|
|
|
1239
|
+
def _instructions(args):
|
|
1240
|
+
"""harness instructions [FOLDER]: what a conversation there reads at its start (instructions.py,
|
|
1241
|
+
with the settings' [instructions]), what was cut or left out and why."""
|
|
1242
|
+
from . import instructions
|
|
1243
|
+
from .paths import data
|
|
1244
|
+
from .settings import Settings
|
|
1245
|
+
|
|
1246
|
+
folder = args.folder.expanduser().resolve()
|
|
1247
|
+
if not folder.is_dir():
|
|
1248
|
+
raise UsageError(f"{folder} is not a folder")
|
|
1249
|
+
loaded = instructions.load(folder, Settings(data()).get()["instructions"])
|
|
1250
|
+
if args.json:
|
|
1251
|
+
output(loaded.record())
|
|
1252
|
+
return 0
|
|
1253
|
+
print(f"A conversation in {folder} reads" + (f" (project root {loaded.root}):" if loaded.root else ":"))
|
|
1254
|
+
for item in loaded.files:
|
|
1255
|
+
print(f" {item.label} {len(item.text.encode('utf-8'))} bytes" + (" (cut)" if item.cut else ""))
|
|
1256
|
+
if not loaded.files:
|
|
1257
|
+
print(" no instruction files")
|
|
1258
|
+
for label, why in loaded.skipped:
|
|
1259
|
+
print(f" left out: {label}: {why}")
|
|
1260
|
+
for warning in loaded.warnings:
|
|
1261
|
+
print(f" {warning}")
|
|
1262
|
+
return 0
|
|
1263
|
+
|
|
1264
|
+
|
|
1229
1265
|
def _replay(args):
|
|
1230
1266
|
"""harness replay RUN: terminal records, or raw records with --json."""
|
|
1231
1267
|
from .core.episodes import read_records
|
|
@@ -1322,7 +1358,7 @@ def _main(argv=None):
|
|
|
1322
1358
|
return 1
|
|
1323
1359
|
raise
|
|
1324
1360
|
commands = {"install": _install, "list": _list, "remove": _remove, "library": _library_command, "sessions": _sessions,
|
|
1325
|
-
"replay": _replay}
|
|
1361
|
+
"replay": _replay, "instructions": _instructions}
|
|
1326
1362
|
if args.command == "run":
|
|
1327
1363
|
if args.task == "rpc" and not explicit_task:
|
|
1328
1364
|
if args.print or args.json:
|
|
@@ -190,6 +190,9 @@ RUNTIME_KEYS = {
|
|
|
190
190
|
"agent_skills": "the app: Agent Skills the user installed, {name: {description, path}} (skills/agent_skills)",
|
|
191
191
|
"installed_skills": "the app: the Harness skills the user installed, by name (the prompt's installed section, "
|
|
192
192
|
"runtime/decision/prompts.py)",
|
|
193
|
+
"instructions": "{load, files, root_markers, max_bytes, exclude}: the user's and the project's instruction "
|
|
194
|
+
"files (AGENTS.md) the opening message carries (instructions.py); the settings' [instructions] "
|
|
195
|
+
"in a conversation a user starts, absent elsewhere (none are read)",
|
|
193
196
|
}
|
|
194
197
|
def _relative(value):
|
|
195
198
|
"""Paths of the core's content written relative to it, a package's as packages/<name>/...
|
|
@@ -37,7 +37,8 @@ CONVERSATION = ROOT / "configs" / "assistant.toml"
|
|
|
37
37
|
# --window-details, --think; and `learn`, a conversation that learns its environment for live
|
|
38
38
|
# minutes (true: learning.active_minutes) instead of doing a task (runtime/learning/active.py).
|
|
39
39
|
# `agents`: sub-agents on in this conversation whatever session.agents says.
|
|
40
|
-
RUN_KEYS = ("physical", "privacy", "think_while_acting", "think_interval", "learn", "managed_workspace", "agents"
|
|
40
|
+
RUN_KEYS = ("physical", "privacy", "think_while_acting", "think_interval", "learn", "managed_workspace", "agents",
|
|
41
|
+
"instructions")
|
|
41
42
|
# The keys of a conversation profile's file (profiles()).
|
|
42
43
|
PROFILE_KEYS = {
|
|
43
44
|
"description": "one line: what conversations of this profile are for",
|
|
@@ -334,6 +335,10 @@ class TaskHost:
|
|
|
334
335
|
"agent_skills": addons.agent_skill_options(self.packages, skills["agent"])}
|
|
335
336
|
# No implicit cross-task knowledge. A caller can explicitly bind a learning library.
|
|
336
337
|
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), "library": None}
|
|
338
|
+
# The user's and the project's instruction files (instructions.py): a conversation a user
|
|
339
|
+
# starts reads them; an experiment or a benchmark, whose config has none of this, does not.
|
|
340
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}),
|
|
341
|
+
"instructions": dict(values["instructions"])}
|
|
337
342
|
servers = self.mcp_servers()
|
|
338
343
|
if servers:
|
|
339
344
|
# The MCP servers a package connects (the app's connectors, through its gateway).
|
|
@@ -674,6 +679,9 @@ class TaskHost:
|
|
|
674
679
|
if unknown:
|
|
675
680
|
raise ValueError(f"a conversation's own runtime keys are {', '.join(RUN_KEYS)}, not {sorted(unknown)}")
|
|
676
681
|
runtime = dict(runtime or {})
|
|
682
|
+
if "instructions" in runtime:
|
|
683
|
+
# harness run --bare: {"load": "off"} over the settings' instructions.
|
|
684
|
+
runtime["instructions"] = {**(config.runtime.get("instructions") or {}), **dict(runtime["instructions"])}
|
|
677
685
|
learn = runtime.pop("learn", None)
|
|
678
686
|
runtime.pop("agents", None)
|
|
679
687
|
managed = runtime.pop("managed_workspace", False)
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Instruction files (AGENTS.md): what the user and a project tell every conversation, as Codex
|
|
2
|
+
and Claude Code read them.
|
|
3
|
+
|
|
4
|
+
user $HARNESS_DATA/AGENTS.override.md, else $HARNESS_DATA/AGENTS.md (~/.harness/)
|
|
5
|
+
project from the project root down to the conversation's folder, one file per
|
|
6
|
+
directory: the first non-empty of instructions.files (default
|
|
7
|
+
AGENTS.override.md, AGENTS.md, CLAUDE.md), then that directory's
|
|
8
|
+
CLAUDE.local.md. The root is the nearest ancestor of the folder holding one of
|
|
9
|
+
instructions.root_markers (default .git); with none, the folder alone. The walk
|
|
10
|
+
never goes above the root.
|
|
11
|
+
below a directory under the folder with its own file is read when a program first
|
|
12
|
+
touches a file in it (nested()), once per conversation.
|
|
13
|
+
|
|
14
|
+
`@path` in a file imports another (relative to the importing file, ~ for home, at most four
|
|
15
|
+
hops, not inside code spans or fenced blocks), when it lies inside the project root or the
|
|
16
|
+
data directory; an import elsewhere is left as text with a warning. Block-level HTML
|
|
17
|
+
comments are left out.
|
|
18
|
+
|
|
19
|
+
The files read at the start share instructions.max_bytes (default 32768, as Codex's
|
|
20
|
+
project_doc_max_bytes; the user file has its own). A file a program's touch brings in is cut
|
|
21
|
+
at 40,000 characters (Claude Code). A file over 4 MiB is skipped. Where something is cut the
|
|
22
|
+
model is told how to read the rest, and the user is warned.
|
|
23
|
+
|
|
24
|
+
The model gets them in its opening message (block()), as Codex gives them; compaction keeps
|
|
25
|
+
that message (runtime/task/run.py). Settings: instructions.load (all, user, off), .files,
|
|
26
|
+
.root_markers, .max_bytes, .exclude (settings.py); harness run --bare loads none.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
import fnmatch
|
|
31
|
+
import os
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
import re
|
|
34
|
+
|
|
35
|
+
from .paths import data
|
|
36
|
+
|
|
37
|
+
USER_FILES = ("AGENTS.override.md", "AGENTS.md")
|
|
38
|
+
DEFAULTS = {"load": "all", "files": "AGENTS.override.md, AGENTS.md, CLAUDE.md", "root_markers": ".git",
|
|
39
|
+
"max_bytes": 32768, "exclude": ""}
|
|
40
|
+
LOCAL_FILE = "CLAUDE.local.md"
|
|
41
|
+
NESTED_CHARS = 40_000
|
|
42
|
+
SKIP_BYTES = 4 * 1024 * 1024
|
|
43
|
+
IMPORT_DEPTH = 4
|
|
44
|
+
SEPARATOR = "\n\n--- project-doc ---\n\n"
|
|
45
|
+
|
|
46
|
+
_FENCE = re.compile(r"^\s*(```|~~~)")
|
|
47
|
+
_IMPORT = re.compile(r"(?<![\w`@])@((?:\\ |[^\s`])+)")
|
|
48
|
+
_COMMENT = re.compile(r"^[ \t]*<!--.*?-->[ \t]*\n?", re.S | re.M)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class File:
|
|
53
|
+
path: Path
|
|
54
|
+
label: str # how the model and the user see it: ~/..., or relative to the root
|
|
55
|
+
text: str
|
|
56
|
+
size: int # bytes on disk
|
|
57
|
+
cut: bool = False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Loaded:
|
|
62
|
+
folder: Path | None = None
|
|
63
|
+
root: Path | None = None
|
|
64
|
+
files: list[File] = field(default_factory=list)
|
|
65
|
+
skipped: list[tuple[str, str]] = field(default_factory=list) # (label, why)
|
|
66
|
+
warnings: list[str] = field(default_factory=list)
|
|
67
|
+
|
|
68
|
+
def record(self) -> dict:
|
|
69
|
+
"""What the trace keeps of it (the instructions record)."""
|
|
70
|
+
return {"folder": str(self.folder) if self.folder else None, "root": str(self.root) if self.root else None,
|
|
71
|
+
"files": [{"path": str(item.path), "label": item.label, "bytes": len(item.text.encode("utf-8")),
|
|
72
|
+
"size": item.size, **({"cut": True} if item.cut else {})} for item in self.files],
|
|
73
|
+
**({"skipped": [{"label": label, "why": why} for label, why in self.skipped]} if self.skipped else {}),
|
|
74
|
+
**({"warnings": list(self.warnings)} if self.warnings else {})}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def options(given=None) -> dict:
|
|
78
|
+
"""The instructions settings with their defaults; lists as lists."""
|
|
79
|
+
values = {**DEFAULTS, **{key: value for key, value in (given or {}).items() if value is not None}}
|
|
80
|
+
for key in ("files", "root_markers", "exclude"):
|
|
81
|
+
if isinstance(values[key], str):
|
|
82
|
+
values[key] = [item.strip() for item in values[key].split(",") if item.strip()]
|
|
83
|
+
else:
|
|
84
|
+
values[key] = [str(item) for item in values[key]]
|
|
85
|
+
values["max_bytes"] = max(0, int(values["max_bytes"]))
|
|
86
|
+
if values["load"] not in ("all", "user", "off"):
|
|
87
|
+
raise ValueError("instructions.load is all, user or off")
|
|
88
|
+
return values
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _label(path: Path, root: Path | None) -> str:
|
|
92
|
+
if root is not None and path.is_relative_to(root):
|
|
93
|
+
return path.relative_to(root).as_posix()
|
|
94
|
+
home = Path.home()
|
|
95
|
+
return "~/" + path.relative_to(home).as_posix() if path.is_relative_to(home) else path.as_posix()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _excluded(path: Path, patterns) -> bool:
|
|
99
|
+
text = path.as_posix()
|
|
100
|
+
return any(fnmatch.fnmatch(text, pattern) or fnmatch.fnmatch(path.name, pattern) for pattern in patterns)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _read(path: Path, label: str, loaded: Loaded) -> str | None:
|
|
104
|
+
"""The file's text, or None (absent, empty, too large, unreadable)."""
|
|
105
|
+
try:
|
|
106
|
+
size = path.stat().st_size
|
|
107
|
+
except OSError:
|
|
108
|
+
return None
|
|
109
|
+
if size > SKIP_BYTES:
|
|
110
|
+
loaded.skipped.append((label, "over 4 MiB"))
|
|
111
|
+
loaded.warnings.append(f"{label} is over 4 MiB and was not loaded")
|
|
112
|
+
return None
|
|
113
|
+
try:
|
|
114
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
115
|
+
except OSError as error:
|
|
116
|
+
loaded.skipped.append((label, f"unreadable: {error}"))
|
|
117
|
+
return None
|
|
118
|
+
text = _without_comments(text)
|
|
119
|
+
if not text.strip():
|
|
120
|
+
loaded.skipped.append((label, "empty"))
|
|
121
|
+
return None
|
|
122
|
+
return text
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _outside_code(text: str):
|
|
126
|
+
"""(line, inside_code) for each line: fenced blocks count as code."""
|
|
127
|
+
fenced = False
|
|
128
|
+
for line in text.splitlines(keepends=True):
|
|
129
|
+
if _FENCE.match(line):
|
|
130
|
+
fenced = not fenced
|
|
131
|
+
yield line, True
|
|
132
|
+
continue
|
|
133
|
+
yield line, fenced
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _without_comments(text: str) -> str:
|
|
137
|
+
"""The text without block-level HTML comments; comments inside fenced blocks stay."""
|
|
138
|
+
out, chunk = [], []
|
|
139
|
+
for line, code in _outside_code(text):
|
|
140
|
+
if code:
|
|
141
|
+
if chunk:
|
|
142
|
+
out.append(_COMMENT.sub("", "".join(chunk)))
|
|
143
|
+
chunk = []
|
|
144
|
+
out.append(line)
|
|
145
|
+
else:
|
|
146
|
+
chunk.append(line)
|
|
147
|
+
if chunk:
|
|
148
|
+
out.append(_COMMENT.sub("", "".join(chunk)))
|
|
149
|
+
return "".join(out)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _imports(text: str) -> list[str]:
|
|
153
|
+
"""The @paths a file imports: not inside code spans or fenced blocks."""
|
|
154
|
+
found = []
|
|
155
|
+
for line, code in _outside_code(text):
|
|
156
|
+
if code:
|
|
157
|
+
continue
|
|
158
|
+
line = re.sub(r"`[^`]*`", "", line)
|
|
159
|
+
found += [match.group(1).replace("\\ ", " ") for match in _IMPORT.finditer(line)]
|
|
160
|
+
return found
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _imported(path: Path, text: str, allowed, loaded: Loaded, root: Path | None, depth: int = 1, seen=None) -> list[File]:
|
|
164
|
+
"""The files `text` (of `path`) imports, and theirs, as entries after it."""
|
|
165
|
+
seen = seen if seen is not None else {path.resolve()}
|
|
166
|
+
entries = []
|
|
167
|
+
if depth > IMPORT_DEPTH:
|
|
168
|
+
return entries
|
|
169
|
+
for name in _imports(text):
|
|
170
|
+
target = Path(os.path.expanduser(name))
|
|
171
|
+
target = (target if target.is_absolute() else path.parent / target).resolve()
|
|
172
|
+
if target in seen or not target.is_file():
|
|
173
|
+
continue
|
|
174
|
+
label = _label(target, root)
|
|
175
|
+
if not any(target.is_relative_to(base) for base in allowed):
|
|
176
|
+
loaded.warnings.append(f"{_label(path, root)} imports {name}, outside the project and "
|
|
177
|
+
f"{_label(data(), None)}: not loaded")
|
|
178
|
+
continue
|
|
179
|
+
seen.add(target)
|
|
180
|
+
body = _read(target, label, loaded)
|
|
181
|
+
if body is None:
|
|
182
|
+
continue
|
|
183
|
+
entries.append(File(target, label, body, target.stat().st_size))
|
|
184
|
+
entries += _imported(target, body, allowed, loaded, root, depth + 1, seen)
|
|
185
|
+
return entries
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def project_root(folder: Path, markers) -> Path | None:
|
|
189
|
+
"""The nearest ancestor of `folder` (itself included) holding one of `markers`; None without."""
|
|
190
|
+
if not markers:
|
|
191
|
+
return None
|
|
192
|
+
for directory in (folder, *folder.parents):
|
|
193
|
+
if any((directory / marker).exists() for marker in markers):
|
|
194
|
+
return directory
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _directory_files(directory: Path, names, settings, root, loaded) -> list[File]:
|
|
199
|
+
"""The instruction file of one directory (the first of `names` with text), then its CLAUDE.local.md."""
|
|
200
|
+
entries = []
|
|
201
|
+
for name in names:
|
|
202
|
+
path = directory / name
|
|
203
|
+
if not path.is_file():
|
|
204
|
+
continue
|
|
205
|
+
label = _label(path, root)
|
|
206
|
+
if _excluded(path, settings["exclude"]):
|
|
207
|
+
loaded.skipped.append((label, "excluded (instructions.exclude)"))
|
|
208
|
+
continue
|
|
209
|
+
text = _read(path, label, loaded)
|
|
210
|
+
if text is not None:
|
|
211
|
+
entries.append(File(path, label, text, path.stat().st_size))
|
|
212
|
+
break
|
|
213
|
+
local = directory / LOCAL_FILE
|
|
214
|
+
if LOCAL_FILE not in names and local.is_file() and not _excluded(local, settings["exclude"]):
|
|
215
|
+
text = _read(local, _label(local, root), loaded)
|
|
216
|
+
if text is not None:
|
|
217
|
+
entries.append(File(local, _label(local, root), text, local.stat().st_size))
|
|
218
|
+
allowed = [root or directory, data()]
|
|
219
|
+
for entry in list(entries):
|
|
220
|
+
entries[entries.index(entry) + 1:entries.index(entry) + 1] = _imported(
|
|
221
|
+
entry.path, entry.text, allowed, loaded, root)
|
|
222
|
+
return entries
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _budget(entries: list[File], limit: int, loaded: Loaded, what: str) -> list[File]:
|
|
226
|
+
"""`entries` within `limit` bytes: the one that crosses it is cut, those after it left out."""
|
|
227
|
+
kept, left = [], limit
|
|
228
|
+
for entry in entries:
|
|
229
|
+
size = len(entry.text.encode("utf-8"))
|
|
230
|
+
if left <= 0:
|
|
231
|
+
loaded.skipped.append((entry.label, f"over the {limit}-byte budget (instructions.max_bytes)"))
|
|
232
|
+
loaded.warnings.append(f"{entry.label} was not loaded: the {what} instructions reached "
|
|
233
|
+
f"instructions.max_bytes ({limit} bytes)")
|
|
234
|
+
continue
|
|
235
|
+
if size > left:
|
|
236
|
+
entry.text = entry.text.encode("utf-8")[:left].decode("utf-8", "ignore")
|
|
237
|
+
entry.text += (f"\n(The rest of {entry.label} is not shown: {size - left} more bytes. "
|
|
238
|
+
"Read it with read_file when you need it.)")
|
|
239
|
+
entry.cut = True
|
|
240
|
+
loaded.warnings.append(f"{entry.label} was cut at {left} of {size} bytes (instructions.max_bytes)")
|
|
241
|
+
size = left
|
|
242
|
+
kept.append(entry)
|
|
243
|
+
left -= size
|
|
244
|
+
return kept
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def load(folder, settings=None, *, user: bool = True) -> Loaded:
|
|
248
|
+
"""The instruction files a conversation working in `folder` (None: no folder) reads at its
|
|
249
|
+
start; `user` false: the project's only (another folder joining the conversation)."""
|
|
250
|
+
settings = options(settings)
|
|
251
|
+
folder = Path(folder).expanduser().resolve() if folder else None
|
|
252
|
+
loaded = Loaded(folder=folder)
|
|
253
|
+
if settings["load"] == "off":
|
|
254
|
+
return loaded
|
|
255
|
+
limit = settings["max_bytes"]
|
|
256
|
+
found = []
|
|
257
|
+
for name in USER_FILES if user else ():
|
|
258
|
+
path = data() / name
|
|
259
|
+
if path.is_file() and not _excluded(path, settings["exclude"]):
|
|
260
|
+
text = _read(path, _label(path, None), loaded)
|
|
261
|
+
if text is not None:
|
|
262
|
+
found = [File(path, _label(path, None), text, path.stat().st_size)]
|
|
263
|
+
found += _imported(path, text, [data()], loaded, None)
|
|
264
|
+
break
|
|
265
|
+
if limit:
|
|
266
|
+
loaded.files += _budget(found, limit, loaded, "user")
|
|
267
|
+
if folder is None or settings["load"] == "user" or not limit:
|
|
268
|
+
return loaded
|
|
269
|
+
root = project_root(folder, settings["root_markers"])
|
|
270
|
+
loaded.root = root or folder
|
|
271
|
+
project = []
|
|
272
|
+
for directory in _walk(loaded.root, folder):
|
|
273
|
+
project += _directory_files(directory, settings["files"], settings, loaded.root, loaded)
|
|
274
|
+
loaded.files += _budget(project, limit, loaded, "project")
|
|
275
|
+
return loaded
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _walk(root: Path, folder: Path) -> list[Path]:
|
|
279
|
+
"""The directories from `root` down to `folder`, both included."""
|
|
280
|
+
if root == folder:
|
|
281
|
+
return [folder]
|
|
282
|
+
relative = folder.relative_to(root)
|
|
283
|
+
return [root, *(root / Path(*relative.parts[:index]) for index in range(1, len(relative.parts) + 1))]
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def nested(folder, touched, settings, told: set) -> list[File]:
|
|
287
|
+
"""The instruction files of directories below `folder` down to `touched` (a file or a
|
|
288
|
+
directory a program read, wrote or ran in) that the conversation has not been told of; each
|
|
289
|
+
cut at NESTED_CHARS. `told` holds the directories already told and is updated."""
|
|
290
|
+
settings = options(settings)
|
|
291
|
+
if settings["load"] != "all" or folder is None:
|
|
292
|
+
return []
|
|
293
|
+
folder = Path(folder).resolve()
|
|
294
|
+
target = (folder / touched).resolve() if not Path(touched).is_absolute() else Path(touched).resolve()
|
|
295
|
+
if not target.is_relative_to(folder) or target == folder:
|
|
296
|
+
return []
|
|
297
|
+
directory = target if target.is_dir() else target.parent
|
|
298
|
+
loaded = Loaded(folder=folder)
|
|
299
|
+
entries = []
|
|
300
|
+
for current in _walk(folder, directory)[1:]:
|
|
301
|
+
if current in told:
|
|
302
|
+
continue
|
|
303
|
+
told.add(current)
|
|
304
|
+
for entry in _directory_files(current, settings["files"], settings, folder, loaded):
|
|
305
|
+
if len(entry.text) > NESTED_CHARS:
|
|
306
|
+
entry.text = entry.text[:NESTED_CHARS] + (f"\n(The rest of {entry.label} is not shown. Read it with "
|
|
307
|
+
"read_file when you need it.)")
|
|
308
|
+
entry.cut = True
|
|
309
|
+
entries.append(entry)
|
|
310
|
+
return entries
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def block(loaded: Loaded) -> str:
|
|
314
|
+
"""The model's text: Codex's wrapper, the user's file first, each file under its path."""
|
|
315
|
+
if not loaded.files:
|
|
316
|
+
return ""
|
|
317
|
+
user = [entry for entry in loaded.files if entry.path.is_relative_to(data())]
|
|
318
|
+
project = [entry for entry in loaded.files if entry not in user]
|
|
319
|
+
parts = ["\n\n".join(f"(from {entry.label})\n{entry.text.strip()}" for entry in user)] if user else []
|
|
320
|
+
if project:
|
|
321
|
+
parts.append("\n\n".join(f"(from {entry.label})\n{entry.text.strip()}" for entry in project))
|
|
322
|
+
head = "# AGENTS.md instructions" + (f" for {loaded.folder}" if loaded.folder else "")
|
|
323
|
+
return f"{head}\n\n<INSTRUCTIONS>\n{SEPARATOR.join(parts) if len(parts) > 1 else parts[0]}\n</INSTRUCTIONS>\n\n"
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def told(entries: list[File]) -> str:
|
|
327
|
+
"""The note for files a program's touch brought in (nested())."""
|
|
328
|
+
return "\n\n".join(f"Instructions for {entry.path.parent.as_posix()} (from {entry.label}):\n{entry.text.strip()}"
|
|
329
|
+
for entry in entries)
|
|
@@ -183,6 +183,7 @@ EVENTS = {
|
|
|
183
183
|
"decision": {"source": "program", "shown": False},
|
|
184
184
|
"page_read": {"source": "environment", "shown": False},
|
|
185
185
|
"workspace_reclaimed": {"source": "harness", "shown": False},
|
|
186
|
+
"instructions": {"source": "harness", "shown": True},
|
|
186
187
|
"environment_attached": {"source": "harness", "shown": True},
|
|
187
188
|
"environment_refused": {"source": "harness", "shown": True},
|
|
188
189
|
"environment_released": {"source": "harness", "shown": True},
|
|
@@ -754,9 +754,11 @@ class EpisodeCore:
|
|
|
754
754
|
it holds: the situation it answers), or the name of an event (it answers that
|
|
755
755
|
event). `do`: a program (a function, started as a unit; its work is done when the
|
|
756
756
|
situation is over), the name of an event to raise, an action of the environment that
|
|
757
|
-
ends what runs ("stop"), or None: then
|
|
758
|
-
it. `
|
|
759
|
-
|
|
757
|
+
ends what runs ("stop"), or None: then only the nodes set `under`
|
|
758
|
+
it answer. `under`: the node it is a narrower situation of (any node whose `when` is
|
|
759
|
+
a condition, whatever that node does itself). `priority`: its own (the higher first,
|
|
760
|
+
0 or more; what a program's at_priority is compared with). `every`: the seconds
|
|
761
|
+
between judgements of its condition (None: when the state or the facts change). `again_seconds`: before it may begin again. Its name."""
|
|
760
762
|
return self.reactive.set(name, when, do, under=under, priority=priority, every=every,
|
|
761
763
|
again_seconds=again_seconds)
|
|
762
764
|
|
|
@@ -1,20 +1,28 @@
|
|
|
1
1
|
"""The reactive layer: one tree of reflexes.
|
|
2
2
|
|
|
3
|
-
What acts without the model is one tree, empty at first. A node
|
|
4
|
-
(`when`: a condition of the view, or the name of an event) and what
|
|
5
|
-
program, the name of an event to raise, an action that ends what runs,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
What acts without the model is one tree, empty at first. A node is a situation: it says
|
|
4
|
+
when the agent is in it (`when`: a condition of the view, or the name of an event) and what
|
|
5
|
+
answers it (`do`: a program, the name of an event to raise, an action that ends what runs,
|
|
6
|
+
or nothing). Any node may have nodes under it: the narrower situations within it. Four
|
|
7
|
+
statements are the whole of it:
|
|
8
|
+
|
|
9
|
+
1. A node under another has its turn only while that one's condition holds, and before
|
|
10
|
+
it: while a node under it is answering, the node itself does not act. What the node
|
|
11
|
+
does itself answers what is in its situation and in none of those under it. So a
|
|
12
|
+
node is complete when it is set, and the tree grows by putting nodes under nodes,
|
|
13
|
+
which changes none of them.
|
|
9
14
|
2. Among the nodes at one place the earlier (the higher priority, then the older) takes
|
|
10
15
|
the environment from the later, and gives it back when it is done.
|
|
11
16
|
3. A node has done its work when the situation it answers is over: its program is a
|
|
12
17
|
unit whose completion condition is that the node's condition no longer holds
|
|
13
18
|
(runtime/execution/entries.py: how a unit ended and whether its work is done are two
|
|
14
19
|
things, for every unit). When its program ends and the situation is not over, or
|
|
15
|
-
the program fails,
|
|
16
|
-
|
|
17
|
-
|
|
20
|
+
the program fails, what comes after it has the environment: a later node at that
|
|
21
|
+
place whose condition holds, then what the node above does itself; when nothing
|
|
22
|
+
has, the model is told what the program did (the event REFLEX_FAILED), once until
|
|
23
|
+
the node has done its work again.
|
|
24
|
+
4. A node that tells the model (`do` an event's name) has its turn like any other: it
|
|
25
|
+
tells when neither a node before it at its place nor one under it is answering.
|
|
18
26
|
|
|
19
27
|
A node's program runs as a unit whose priority is the node's own priority (rank()):
|
|
20
28
|
the units' priorities are how the tick lets the earlier take the environment from the later
|
|
@@ -73,9 +81,9 @@ def told(nodes: dict, before: dict) -> str:
|
|
|
73
81
|
@dataclass
|
|
74
82
|
class Reflex:
|
|
75
83
|
"""A node of the tree: its `name`; `when` it has its turn (a condition of the view) or
|
|
76
|
-
the `event` it answers; what it does: `do` (a program), or `action` (an event to
|
|
77
|
-
or one of the environment's actions that end what runs), or neither (
|
|
78
|
-
it is `under` (None: the top); its `priority
|
|
84
|
+
the `event` it answers; what it does itself: `do` (a program), or `action` (an event to
|
|
85
|
+
raise, or one of the environment's actions that end what runs), or neither (then only
|
|
86
|
+
the nodes under it answer); the node it is `under` (None: the top); its own `priority`; `every`
|
|
79
87
|
seconds its condition is judged (None: when the state or the facts change);
|
|
80
88
|
`again_seconds` before it may begin again after its program ended."""
|
|
81
89
|
|
|
@@ -182,7 +190,7 @@ class Reflexes:
|
|
|
182
190
|
"""Put the node `name` into the tree, in place of a node of that name (see Reflex;
|
|
183
191
|
`when`: a function of the view, or the name of an event; `do`: a program, or the
|
|
184
192
|
name of an event to raise, or an action of the environment that ends what runs
|
|
185
|
-
("stop"), or None
|
|
193
|
+
("stop"), or None: then only the nodes under it answer). Its name."""
|
|
186
194
|
staging = getattr(_staging, "layers", None)
|
|
187
195
|
if staging is not None and staging[0] is self:
|
|
188
196
|
return staging[1].set(name, when, do, under=under, priority=priority, every=every,
|
|
@@ -206,7 +214,7 @@ class Reflexes:
|
|
|
206
214
|
action, stops, do = do, do in self.actions, None
|
|
207
215
|
elif do is not None and not callable(do):
|
|
208
216
|
raise TypeError("`do` is a program (a function), the name of an event, an action that ends what runs, "
|
|
209
|
-
"or None
|
|
217
|
+
"or None (then only the nodes under it answer)")
|
|
210
218
|
if isinstance(priority, bool) or not isinstance(priority, int) or priority < 0:
|
|
211
219
|
raise ValueError(f"priority is a whole number, 0 or more, got {priority!r}")
|
|
212
220
|
if isinstance(again_seconds, bool) or not isinstance(again_seconds, (int, float)) or again_seconds < 0:
|
|
@@ -220,17 +228,17 @@ class Reflexes:
|
|
|
220
228
|
above = known.get(under)
|
|
221
229
|
if above is None:
|
|
222
230
|
raise ValueError(f"no reflex is named {under!r}: the node a reflex is under is set first")
|
|
223
|
-
if above.
|
|
224
|
-
|
|
225
|
-
|
|
231
|
+
if above.event is not None or above.stops:
|
|
232
|
+
# (Neither is a situation the agent is in for a while, which others could narrow.)
|
|
233
|
+
raise ValueError(f"{under!r} answers an event or ends what runs: nodes go under a node whose "
|
|
234
|
+
"`when` is a condition")
|
|
226
235
|
while above is not None:
|
|
227
236
|
if above.name == name:
|
|
228
237
|
raise ValueError(f"{name!r} cannot be under itself")
|
|
229
238
|
above = known.get(above.under) if above.under is not None else None
|
|
230
239
|
old = known.get(name)
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
raise ValueError(f"{name!r} has nodes under it: it stays a group (set without `do`)")
|
|
240
|
+
if (event is not None or stops) and any(node.under == name for node in known.values()):
|
|
241
|
+
raise ValueError(f"{name!r} has nodes under it: its `when` stays a condition, and it does not end what runs")
|
|
234
242
|
self._count += 1
|
|
235
243
|
self._retire(self.nodes.get(name))
|
|
236
244
|
self.nodes[name] = Reflex(name, when, event, do, action, stops, under, priority,
|
|
@@ -279,8 +287,7 @@ class Reflexes:
|
|
|
279
287
|
running = node.unit is not None and bool(getattr(node.unit, "running", False))
|
|
280
288
|
lines[here] = (f"began {node.triggered}, did its work {node.did}, did not {node.did_not}"
|
|
281
289
|
+ (", runs now" if running else ""))
|
|
282
|
-
|
|
283
|
-
lines.update(self.digest(node.name, here + "/"))
|
|
290
|
+
lines.update(self.digest(node.name, here + "/"))
|
|
284
291
|
return lines
|
|
285
292
|
|
|
286
293
|
def tell(self) -> None:
|
|
@@ -320,13 +327,21 @@ class Reflexes:
|
|
|
320
327
|
key=lambda node: (-node.priority, node.order))
|
|
321
328
|
|
|
322
329
|
def _leaves(self, name) -> list:
|
|
323
|
-
"""The nodes with a program at and under `name`, in the
|
|
330
|
+
"""The nodes with a program at and under `name`, in the order their turn comes: those
|
|
331
|
+
under a node before the node itself."""
|
|
324
332
|
node = self.nodes.get(name)
|
|
325
333
|
if node is None:
|
|
326
334
|
return []
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
335
|
+
return [leaf for child in self.children(name) for leaf in self._leaves(child.name)] + (
|
|
336
|
+
[node] if node.do is not None else [])
|
|
337
|
+
|
|
338
|
+
def _above(self, node) -> list:
|
|
339
|
+
"""The nodes `node` is under, the nearest first."""
|
|
340
|
+
found, above = [], self.nodes.get(node.under) if node.under is not None else None
|
|
341
|
+
while above is not None and above not in found:
|
|
342
|
+
found.append(above)
|
|
343
|
+
above = self.nodes.get(above.under) if above.under is not None else None
|
|
344
|
+
return found
|
|
330
345
|
|
|
331
346
|
def rank(self, node) -> float:
|
|
332
347
|
"""What a node's program holds the environment with: the node's own priority,
|
|
@@ -335,7 +350,7 @@ class Reflexes:
|
|
|
335
350
|
runs is what a program's priority (at_priority) and every other node's is compared
|
|
336
351
|
with: the higher has the environment, among equals the earlier in the tree; and
|
|
337
352
|
every node is above the model's programs (0)."""
|
|
338
|
-
leaves = [
|
|
353
|
+
leaves = [leaf for top in self.children() for leaf in self._leaves(top.name)]
|
|
339
354
|
place = next((index for index, leaf in enumerate(leaves) if leaf is node), 0)
|
|
340
355
|
return node.priority + (len(leaves) - place) / (len(leaves) + 1)
|
|
341
356
|
|
|
@@ -544,8 +559,10 @@ def judge(session, tree):
|
|
|
544
559
|
return lambda view: not layer._run(node, view)
|
|
545
560
|
|
|
546
561
|
def walk(name):
|
|
547
|
-
# The nodes at `name` whose
|
|
548
|
-
#
|
|
562
|
+
# The nodes at and under `name` whose condition holds, the earlier first; under a
|
|
563
|
+
# node before the node itself, which answers only what none of them does. Those with
|
|
564
|
+
# a program are returned; each node that acts is kept with the ones whose turn comes
|
|
565
|
+
# before its own: those under it, and for one that tells, those before it at its place.
|
|
549
566
|
before = []
|
|
550
567
|
for node in layer.children(name):
|
|
551
568
|
if node.event is not None or node.stops or layer.nodes.get(node.name) is not node:
|
|
@@ -564,19 +581,23 @@ def judge(session, tree):
|
|
|
564
581
|
for below in layer._below(node.name)[1:]:
|
|
565
582
|
below.holds, below.raised = _UNSEEN, False
|
|
566
583
|
continue
|
|
584
|
+
under = walk(node.name)
|
|
567
585
|
if node.action is not None:
|
|
568
|
-
telling.append((node,
|
|
586
|
+
telling.append((node, before + under))
|
|
569
587
|
elif node.do is not None:
|
|
570
|
-
wanting.append(node)
|
|
571
|
-
|
|
572
|
-
else:
|
|
573
|
-
before += walk(node.name)
|
|
588
|
+
wanting.append((node, under))
|
|
589
|
+
before += under + ([node] if node.do is not None else [])
|
|
574
590
|
return before
|
|
575
591
|
|
|
576
592
|
walk(None)
|
|
577
593
|
running = [entry for entry in tree.running() if entry.kind != "agent"]
|
|
578
594
|
startable = set()
|
|
579
|
-
for node in wanting:
|
|
595
|
+
for node, under in wanting:
|
|
596
|
+
if any(found.name in startable for found in under):
|
|
597
|
+
# A narrower situation under it is being answered: what the node does itself
|
|
598
|
+
# gives way, also where it already runs.
|
|
599
|
+
layer._retire(node)
|
|
600
|
+
continue
|
|
580
601
|
if node.unit is not None:
|
|
581
602
|
startable.add(node.name)
|
|
582
603
|
continue
|
|
@@ -584,7 +605,10 @@ def judge(session, tree):
|
|
|
584
605
|
layer.wake_at = node.ready_at if layer.wake_at is None else min(layer.wake_at, node.ready_at)
|
|
585
606
|
continue
|
|
586
607
|
rank = layer.rank(node)
|
|
587
|
-
|
|
608
|
+
# (The programs of the nodes it is under give way to it: they do not keep it waiting.)
|
|
609
|
+
giving_way = {above.name for above in layer._above(node)}
|
|
610
|
+
above = next((entry for entry in running if entry.rank > rank
|
|
611
|
+
and getattr(entry, "rule", None) not in giving_way), None)
|
|
588
612
|
if above is not None:
|
|
589
613
|
# What is before it has the environment: its turn is judged when that ends. Where
|
|
590
614
|
# that is a program that said so (at_priority), the model is told once.
|
|
@@ -601,8 +625,8 @@ def judge(session, tree):
|
|
|
601
625
|
running.append(node.unit)
|
|
602
626
|
startable.add(node.name)
|
|
603
627
|
spans.note("rule", name=node.name, action="began", unit=node.unit.id, priority=rank)
|
|
604
|
-
# A node that tells the model has its turn like any other
|
|
605
|
-
#
|
|
628
|
+
# A node that tells the model has its turn like any other: when none of those whose
|
|
629
|
+
# turn comes before its own (under it, and before it at its place) is acting. So it
|
|
606
630
|
# tells what nothing answered, and no more.
|
|
607
631
|
for node, before in telling:
|
|
608
632
|
if any(found.name in startable for found in before):
|
|
@@ -615,9 +639,15 @@ def judge(session, tree):
|
|
|
615
639
|
emit(tree, None, "reflex", session._rule_event(node, state))
|
|
616
640
|
layer.tell()
|
|
617
641
|
for node, unit in failures:
|
|
642
|
+
# What comes after a node whose program did not do its work: a later node at its
|
|
643
|
+
# place, then what the nodes above it do themselves (a program that is acting, or
|
|
644
|
+
# their telling the model).
|
|
618
645
|
later = layer.children(node.under)
|
|
619
646
|
later = later[later.index(node) + 1:] if node in later else []
|
|
620
|
-
|
|
647
|
+
taken = any(found.name in startable for other in later for found in layer._leaves(other.name)) or any(
|
|
648
|
+
above.name in startable or (above.action is not None and not above.stops and above.raised)
|
|
649
|
+
for above in layer._above(node))
|
|
650
|
+
if node.told or taken:
|
|
621
651
|
continue
|
|
622
652
|
node.told = True
|
|
623
653
|
emit(tree, None, "reflex", Event(ev.REFLEX_FAILED, node.name, {
|
|
@@ -174,6 +174,8 @@ class Environments:
|
|
|
174
174
|
with self._lock:
|
|
175
175
|
self.attached[kind] = row
|
|
176
176
|
conversation._prompt_added(row["prompt"])
|
|
177
|
+
# A folder of its own: that project's instruction files (instructions.py).
|
|
178
|
+
conversation.instructions_attached(row.get("root"))
|
|
177
179
|
trace.emit("environment_attached", kind=kind, label=label, why=why, level=level, asked=asked,
|
|
178
180
|
skipped_confirmation=bool(skips and level not in ("allow",) and not granted),
|
|
179
181
|
**{**(taken.get("metadata") or {}), **({"folder": str(folder)} if folder else {})})
|
|
@@ -218,7 +220,7 @@ class Environments:
|
|
|
218
220
|
# itself would make them.
|
|
219
221
|
"plain": RemoteEnvironment(endpoint, timeout=float(getattr(env, "timeout", 300.0)))
|
|
220
222
|
if endpoint else env,
|
|
221
|
-
"slot": threading.BoundedSemaphore(8), "prompt": prompt,
|
|
223
|
+
"slot": threading.BoundedSemaphore(8), "prompt": prompt, "root": profile.get("root"),
|
|
222
224
|
"answer": {"session": session,
|
|
223
225
|
"about": f"{kind} ({label}) is attached: call it as {kind}.NAME(...). Its calls are "
|
|
224
226
|
"described in your instructions from your next reply on; "
|
|
@@ -193,6 +193,9 @@ class TaskRun:
|
|
|
193
193
|
self._facts = dict((restore or {}).get("facts") or {})
|
|
194
194
|
self.status = IDLE
|
|
195
195
|
self.messages = []
|
|
196
|
+
# The instruction files read (instructions.Loaded, one per folder) and the directories
|
|
197
|
+
# below the folder whose files a program's touch brought in (_instructions_touched).
|
|
198
|
+
self.instructions, self._instructions_told = [], set()
|
|
196
199
|
self.kernel = None
|
|
197
200
|
self.episode = None
|
|
198
201
|
self.summary = None
|
|
@@ -772,6 +775,8 @@ class TaskRun:
|
|
|
772
775
|
self._mcp_entries.discard(record["id"])
|
|
773
776
|
self._units.pop(record["id"], None)
|
|
774
777
|
self._condition.notify_all()
|
|
778
|
+
if kind == "span_start" and record.get("lane") == "skill":
|
|
779
|
+
self._instructions_touched(record)
|
|
775
780
|
if kind == "span_start" and record.get("parent") is None:
|
|
776
781
|
# Under the program whose unit made it, else under the host's own program span.
|
|
777
782
|
cell = (self._units.get(record.get("entry")) or {}).get("cell")
|
|
@@ -1933,6 +1938,63 @@ class TaskRun:
|
|
|
1933
1938
|
self._reflex_told = dict(nodes)
|
|
1934
1939
|
return text
|
|
1935
1940
|
|
|
1941
|
+
def _instruction_files(self) -> str:
|
|
1942
|
+
"""The opening's instruction files: those a conversation working in the environment's
|
|
1943
|
+
folder (its profile's root) reads at its start, recorded in the trace (instructions)."""
|
|
1944
|
+
settings = self.config.runtime.get("instructions")
|
|
1945
|
+
if not settings:
|
|
1946
|
+
return ""
|
|
1947
|
+
from harness import instructions
|
|
1948
|
+
|
|
1949
|
+
try:
|
|
1950
|
+
loaded = instructions.load((self.profile or {}).get("root"), settings)
|
|
1951
|
+
except (OSError, ValueError) as error:
|
|
1952
|
+
self.trace.emit("instructions", files=[], warnings=[f"instruction files not read: {error}"])
|
|
1953
|
+
return ""
|
|
1954
|
+
self.instructions = [loaded]
|
|
1955
|
+
self.trace.emit("instructions", **loaded.record())
|
|
1956
|
+
return instructions.block(loaded)
|
|
1957
|
+
|
|
1958
|
+
def _instructions_touched(self, record) -> None:
|
|
1959
|
+
"""A program read, wrote or ran something in the folder (a skill's span): the
|
|
1960
|
+
instruction files of the directories below the folder down to it, not told yet, reach
|
|
1961
|
+
the model with its next call (Claude Code's files in subdirectories, read on demand)."""
|
|
1962
|
+
settings = self.config.runtime.get("instructions")
|
|
1963
|
+
parameters = record.get("parameters")
|
|
1964
|
+
if (not settings or not self.instructions or self.instructions[0].folder is None
|
|
1965
|
+
or record.get("name") not in ("read", "write", "run", "start") or not isinstance(parameters, dict)):
|
|
1966
|
+
return
|
|
1967
|
+
touched = parameters.get("path") if record.get("name") in ("read", "write") else parameters.get("cwd")
|
|
1968
|
+
if not isinstance(touched, str) or not touched or touched == ".":
|
|
1969
|
+
return
|
|
1970
|
+
from harness import instructions
|
|
1971
|
+
|
|
1972
|
+
try:
|
|
1973
|
+
with self._condition:
|
|
1974
|
+
found = instructions.nested(self.instructions[0].folder, touched, settings, self._instructions_told)
|
|
1975
|
+
except (OSError, ValueError):
|
|
1976
|
+
return
|
|
1977
|
+
if found:
|
|
1978
|
+
self.trace.emit("instructions", folder=str(self.instructions[0].folder), nested=True,
|
|
1979
|
+
files=[{"path": str(item.path), "label": item.label,
|
|
1980
|
+
"bytes": len(item.text.encode("utf-8")), "size": item.size,
|
|
1981
|
+
**({"cut": True} if item.cut else {})} for item in found])
|
|
1982
|
+
self._note(instructions.told(found))
|
|
1983
|
+
|
|
1984
|
+
def instructions_attached(self, root) -> None:
|
|
1985
|
+
"""An environment with a folder of its own joined the conversation: the model is told
|
|
1986
|
+
that folder's project instruction files (not the user's again) with its next call."""
|
|
1987
|
+
settings = self.config.runtime.get("instructions")
|
|
1988
|
+
if not settings or not root:
|
|
1989
|
+
return
|
|
1990
|
+
from harness import instructions
|
|
1991
|
+
|
|
1992
|
+
loaded = instructions.load(root, settings, user=False)
|
|
1993
|
+
self.instructions = [*getattr(self, "instructions", []), loaded]
|
|
1994
|
+
self.trace.emit("instructions", **loaded.record())
|
|
1995
|
+
if loaded.files:
|
|
1996
|
+
self._note(instructions.block(loaded).strip())
|
|
1997
|
+
|
|
1936
1998
|
def _compact_if_due(self, loop) -> None:
|
|
1937
1999
|
"""Compaction: when the context the model's last call read has reached
|
|
1938
2000
|
runtime.compact_at_tokens, the model writes a summary of the conversation
|
|
@@ -1983,6 +2045,9 @@ class TaskRun:
|
|
|
1983
2045
|
self._replaces, self._logged = self._replaces + self._logged, 0
|
|
1984
2046
|
self._context_tokens, self._compact_failures = 0, 0
|
|
1985
2047
|
self._reflex_told, self._learning_told = {}, None
|
|
2048
|
+
# Files below the folder are told again when a program touches them (the summary
|
|
2049
|
+
# does not carry them), as Claude Code reloads them on demand.
|
|
2050
|
+
self._instructions_told = set()
|
|
1986
2051
|
self.trace.emit("compaction", action="done", tokens=tokens, messages_before=before, messages=len(messages),
|
|
1987
2052
|
summary=text)
|
|
1988
2053
|
self._save()
|
|
@@ -2208,7 +2273,9 @@ class TaskRun:
|
|
|
2208
2273
|
instruction = active.goal(instruction, runtime.get("skills") or (), sandbox_of(runtime),
|
|
2209
2274
|
legacy_memory="legacy_memory" in EMBODIMENT_KINDS[embodiment].prompt_features)
|
|
2210
2275
|
self._said.insert(0, instruction)
|
|
2211
|
-
|
|
2276
|
+
# The user's and the project's instruction files (AGENTS.md, instructions.py), before
|
|
2277
|
+
# the task, as Codex gives them; compaction keeps this first message.
|
|
2278
|
+
opening = self._instruction_files() + f"Instruction: {instruction}\n"
|
|
2212
2279
|
if config.task_description:
|
|
2213
2280
|
opening += f"\nTask description:\n{config.task_description}\n\n"
|
|
2214
2281
|
# What the library holds, from the first call on.
|
|
@@ -99,6 +99,24 @@ _CORE_SCHEMA = {section: {key: Setting(*row) for key, row in rows.items()} for s
|
|
|
99
99
|
"command's program, the host or the folder; it wins over approvals.programs", "now",
|
|
100
100
|
{"action": "text", "match": "text"}, {"level": "allow", "action": "network", "match": "*.github.com"}),
|
|
101
101
|
},
|
|
102
|
+
"instructions": {
|
|
103
|
+
"load": ("all", "choice", ("all", "user", "off"),
|
|
104
|
+
"the instruction files a new conversation reads (instructions.py): all (yours, "
|
|
105
|
+
"~/.harness/AGENTS.md, and the project's AGENTS.md from its root down to the folder), user (yours "
|
|
106
|
+
"only), off (none)"),
|
|
107
|
+
"files": ("AGENTS.override.md, AGENTS.md, CLAUDE.md", "text", (0, 300),
|
|
108
|
+
"the file names tried in each directory, in order; the first with text is read (a directory's "
|
|
109
|
+
"CLAUDE.local.md is read after it)"),
|
|
110
|
+
"root_markers": (".git", "text", (0, 300),
|
|
111
|
+
"what marks a project's root: the nearest folder above holding one of these (comma-separated; "
|
|
112
|
+
"empty: only the conversation's folder is read)"),
|
|
113
|
+
"max_bytes": (32768, "int", (0, 1048576),
|
|
114
|
+
"bytes of instructions read at a conversation's start (yours and the project's each); "
|
|
115
|
+
"what is over it is cut and the model is told how to read the rest (0: yours and the "
|
|
116
|
+
"project's are not read)"),
|
|
117
|
+
"exclude": ("", "text", (0, 2000), "files never read, as path patterns (comma-separated, e.g. "
|
|
118
|
+
"*/vendor/*/AGENTS.md)"),
|
|
119
|
+
},
|
|
102
120
|
"limits": {
|
|
103
121
|
"max_steps": (60, "int", (1, 1000), "model calls a task may take"),
|
|
104
122
|
"max_minutes": (360, "int", (1, 1440), "minutes a conversation may run"),
|
|
@@ -40,6 +40,9 @@ COMMANDS = {
|
|
|
40
40
|
"settings": Command(note="change the settings"),
|
|
41
41
|
"packages": Command(note="the installed packages and the registry's: install, update, turn off, remove"),
|
|
42
42
|
"library": Command(note="what the agent remembers: this conversation's memory and each library's entries"),
|
|
43
|
+
"instructions": Command(words="[N]", note="the instruction files (AGENTS.md) this conversation read; N: open "
|
|
44
|
+
"that one in your editor"),
|
|
45
|
+
"init": Command(note="have the agent write the project's AGENTS.md, or suggest improvements to the one there"),
|
|
43
46
|
"learn": Command(words="[minutes] [for what]", note="a new conversation that learns this environment instead of "
|
|
44
47
|
"doing a task (default: the settings' minutes); during it, where "
|
|
45
48
|
"it stands"),
|
|
@@ -184,6 +184,18 @@ def items(record: dict, names: dict, timeline: bool = False) -> list[dict]:
|
|
|
184
184
|
f"({how}): {get('why')}", environment=get("kind"), why=get("why"))]
|
|
185
185
|
if kind == "environment_refused":
|
|
186
186
|
return [_item("environment", "note", f"did not take {get('kind')}: {get('reason')}", environment=get("kind"))]
|
|
187
|
+
if kind == "instructions":
|
|
188
|
+
# The instruction files read (instructions.py): at the start, for a folder that joined,
|
|
189
|
+
# or below the folder when a program touched it; and what was cut or left out.
|
|
190
|
+
files, out = get("files") or [], []
|
|
191
|
+
if files:
|
|
192
|
+
size = sum(item.get("bytes") or 0 for item in files)
|
|
193
|
+
out.append(_item("instructions", "note", ("instructions below the folder: " if get("nested") else
|
|
194
|
+
"instructions: ")
|
|
195
|
+
+ ", ".join(item["label"] + (" (cut)" if item.get("cut") else "") for item in files)
|
|
196
|
+
+ f" ({size / 1024:.1f} KB)", files=[item["path"] for item in files]))
|
|
197
|
+
out += [_item("instructions", "note", warning, warning=True) for warning in get("warnings") or ()]
|
|
198
|
+
return out
|
|
187
199
|
if kind == "agents_enabled":
|
|
188
200
|
return [_item("environment", "note", "sub-agents are on for this conversation" if get("enabled")
|
|
189
201
|
else "sub-agents stay off")]
|
|
@@ -108,6 +108,8 @@ class Chat:
|
|
|
108
108
|
self.waiting = None
|
|
109
109
|
self.details_open = False
|
|
110
110
|
self.details_output = []
|
|
111
|
+
self.printed = [] # every renderable printed into the scrollback, in order (_resized prints them again)
|
|
112
|
+
self.printed_size = None # the terminal size the scrollback was last printed for
|
|
111
113
|
self.help = False
|
|
112
114
|
self.ask = None # what waits for the user's approval: {text, options, at, reason}
|
|
113
115
|
self.echoed = None # the first message of a conversation started here, printed at once
|
|
@@ -159,11 +161,11 @@ class Chat:
|
|
|
159
161
|
|
|
160
162
|
app.renderer = WindowsInlineRenderer(app.renderer.style, app.output,
|
|
161
163
|
cpr_not_supported_callback=app.cpr_not_supported_callback)
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
app.
|
|
166
|
-
|
|
164
|
+
else:
|
|
165
|
+
# A resize prints the chat again (_resized). tmux does not always deliver SIGWINCH for
|
|
166
|
+
# each change, so the size is also polled; _resized acts once per size.
|
|
167
|
+
app._on_resize = self._resized
|
|
168
|
+
app.terminal_size_polling_interval = 0.2
|
|
167
169
|
app.timeoutlen, app.ttimeoutlen = 0.3, 0.05
|
|
168
170
|
return app
|
|
169
171
|
|
|
@@ -339,12 +341,18 @@ class Chat:
|
|
|
339
341
|
|
|
340
342
|
async def _view(self, coroutine):
|
|
341
343
|
"""A full-screen view over the chat; what it returns."""
|
|
342
|
-
|
|
343
|
-
|
|
344
|
+
size = self.app.output.get_size()
|
|
345
|
+
try:
|
|
346
|
+
async with in_terminal(render_cli_done=False):
|
|
347
|
+
return await coroutine
|
|
348
|
+
finally:
|
|
349
|
+
if sys.platform != "win32" and self.app.output.get_size() != size:
|
|
350
|
+
self._resized()
|
|
344
351
|
|
|
345
352
|
def run(self):
|
|
346
353
|
"""Until the user leaves; returns the conversation shown then (None: none)."""
|
|
347
354
|
self._banner()
|
|
355
|
+
self.printed_size = self.app.output.get_size()
|
|
348
356
|
with patch_stdout(raw=True):
|
|
349
357
|
self.app.run(pre_run=lambda: self._follow(self.conversation, self.records)
|
|
350
358
|
if self.conversation is not None else self._open_environment())
|
|
@@ -355,9 +363,9 @@ class Chat:
|
|
|
355
363
|
from .. import __version__
|
|
356
364
|
|
|
357
365
|
here = os.getcwd().replace(os.path.expanduser("~"), "~", 1)
|
|
358
|
-
self.
|
|
359
|
-
|
|
360
|
-
|
|
366
|
+
self._print(Text.assemble(("The Harness", "bold"), f" {__version__} ", (here, "dim")),
|
|
367
|
+
Text("Tell it what to do. / for commands, @ to attach a file, ! to run a command, ? for keys.",
|
|
368
|
+
style="dim"))
|
|
361
369
|
if warning := getattr(self.start, "warning", None):
|
|
362
370
|
self.note(warning, "yellow")
|
|
363
371
|
|
|
@@ -367,6 +375,7 @@ class Chat:
|
|
|
367
375
|
if self.details_open:
|
|
368
376
|
self.details_output.extend(renderables)
|
|
369
377
|
return
|
|
378
|
+
self.printed.extend(renderables)
|
|
370
379
|
try:
|
|
371
380
|
self.console.width = self.app.output.get_size().columns
|
|
372
381
|
except Exception:
|
|
@@ -374,6 +383,29 @@ class Chat:
|
|
|
374
383
|
for renderable in renderables:
|
|
375
384
|
self.console.print(renderable)
|
|
376
385
|
|
|
386
|
+
def _resized(self):
|
|
387
|
+
"""The terminal changed size: clear it and print the chat again at the new width, then
|
|
388
|
+
draw the live region, as Claude Code does. A terminal reflows the rows it already shows
|
|
389
|
+
in its own way (tmux 3.2 and 3.8 split the same row differently), so erasing the old
|
|
390
|
+
live region in place left some of its rows behind. Clearing also takes the terminal's
|
|
391
|
+
scrollback from before the chat started."""
|
|
392
|
+
app = self.app
|
|
393
|
+
size = app.output.get_size()
|
|
394
|
+
if size == self.printed_size:
|
|
395
|
+
return
|
|
396
|
+
self.printed_size = size
|
|
397
|
+
stream = io.StringIO()
|
|
398
|
+
console = Console(file=stream, force_terminal=True, legacy_windows=False, highlight=False, soft_wrap=False,
|
|
399
|
+
color_system=self.console.color_system, width=size.columns)
|
|
400
|
+
for renderable in self.printed:
|
|
401
|
+
console.print(renderable)
|
|
402
|
+
# Home, clear the screen, then the scrollback (clearing the screen copies it there in tmux).
|
|
403
|
+
app.output.write_raw("\x1b[H\x1b[2J\x1b[3J" + stream.getvalue().replace("\n", "\r\n"))
|
|
404
|
+
app.output.flush()
|
|
405
|
+
app.renderer.reset(leave_alternate_screen=False)
|
|
406
|
+
app.renderer.request_absolute_cursor_position()
|
|
407
|
+
app.invalidate()
|
|
408
|
+
|
|
377
409
|
def note(self, text, style="dim"):
|
|
378
410
|
self._later(self._print, Text(str(text), style=style))
|
|
379
411
|
|
|
@@ -409,6 +441,7 @@ class Chat:
|
|
|
409
441
|
self.starting = None
|
|
410
442
|
self.conversation, self.ask, self.lanes = conversation, None, Lanes()
|
|
411
443
|
self.learning, self.workspace, self.parked = None, None, False
|
|
444
|
+
self.instruction_files = [] # (label, path) of each instruction file the conversation read
|
|
412
445
|
self.status = getattr(conversation, "status", None)
|
|
413
446
|
self._reset()
|
|
414
447
|
generation, stop = self.generation, self.stop
|
|
@@ -460,6 +493,12 @@ class Chat:
|
|
|
460
493
|
self.ask = None
|
|
461
494
|
if kind in ("physical_answer", "confirmation"):
|
|
462
495
|
self.ask = None
|
|
496
|
+
if kind == "instructions":
|
|
497
|
+
known = getattr(self, "instruction_files", None)
|
|
498
|
+
if known is None:
|
|
499
|
+
known = self.instruction_files = []
|
|
500
|
+
known += [(item["label"], item["path"]) for item in record.get("files") or ()
|
|
501
|
+
if (item["label"], item["path"]) not in known]
|
|
463
502
|
# The timeline's items too, for the reasoning and the answer of finish() in a program.
|
|
464
503
|
items = [item for item in transcript.items(record, self.names, timeline=True) if item["kind"] not in TIMELINE]
|
|
465
504
|
if kind == "cell" and self.program is not None:
|
|
@@ -1227,10 +1266,44 @@ class Chat:
|
|
|
1227
1266
|
|
|
1228
1267
|
self.app.create_background_task(self._guarded(pick))
|
|
1229
1268
|
|
|
1269
|
+
async def _edit(self, path):
|
|
1270
|
+
"""`path` in the user's editor ($EDITOR; notepad on Windows, vi elsewhere), until it closes."""
|
|
1271
|
+
from shlex import split
|
|
1272
|
+
|
|
1273
|
+
self.note(f"Editing {path}. Save and close your editor to return. vi: Esc, :wq, Enter saves; :q! discards. Set EDITOR to choose another editor.")
|
|
1274
|
+
editor = os.environ.get("EDITOR") or ("notepad.exe" if os.name == "nt" else "vi")
|
|
1275
|
+
command = [editor] if os.path.isfile(editor) else split(editor, posix=os.name != "nt")
|
|
1276
|
+
async with in_terminal():
|
|
1277
|
+
result = await asyncio.to_thread(subprocess.run, [*command, str(path)], check=False)
|
|
1278
|
+
if result.returncode:
|
|
1279
|
+
raise ValueError(f"the editor exited with code {result.returncode}")
|
|
1280
|
+
|
|
1281
|
+
def do_instructions(self, words):
|
|
1282
|
+
"""The instruction files this conversation read (instructions.py); N opens that one."""
|
|
1283
|
+
files = getattr(self, "instruction_files", None) or []
|
|
1284
|
+
if not files:
|
|
1285
|
+
self.note("This conversation read no instruction files. It reads ~/.harness/AGENTS.md and the "
|
|
1286
|
+
"project's AGENTS.md (or CLAUDE.md) from its root down to its folder; instructions.load in "
|
|
1287
|
+
"/settings says which.")
|
|
1288
|
+
return
|
|
1289
|
+
if words.strip().isdigit() and 1 <= int(words) <= len(files):
|
|
1290
|
+
path = files[int(words) - 1][1]
|
|
1291
|
+
self.app.create_background_task(self._guarded(lambda: self._edit(path)))
|
|
1292
|
+
return
|
|
1293
|
+
self._print(*[Text.assemble((f" {number} {label}".ljust(36), "bold"), (path, "dim"))
|
|
1294
|
+
for number, (label, path) in enumerate(files, 1)],
|
|
1295
|
+
Text("/instructions N opens one in your editor; a new conversation reads them again.", style="dim"))
|
|
1296
|
+
|
|
1297
|
+
def do_init(self, _):
|
|
1298
|
+
"""Have the agent write the project's AGENTS.md (Claude Code's and Codex's /init)."""
|
|
1299
|
+
self.send("Write an AGENTS.md at the root of this project for the agents that work in it: how to set it "
|
|
1300
|
+
"up, build, test and lint it, how the code is laid out, its conventions, and what to check "
|
|
1301
|
+
"before a change is done. Read the project first, and keep it short and specific to it. If an "
|
|
1302
|
+
"AGENTS.md or a CLAUDE.md is there already, do not replace it: tell me what you would change "
|
|
1303
|
+
"and why, and change it only when I agree.")
|
|
1304
|
+
|
|
1230
1305
|
def do_models(self, _):
|
|
1231
1306
|
async def edit():
|
|
1232
|
-
from shlex import split
|
|
1233
|
-
|
|
1234
1307
|
from ..model_list import models
|
|
1235
1308
|
|
|
1236
1309
|
path = data() / "models.json"
|
|
@@ -1238,13 +1311,7 @@ class Chat:
|
|
|
1238
1311
|
models(data()) # writes the list when there is none yet
|
|
1239
1312
|
except ValueError:
|
|
1240
1313
|
pass # one saved with a mistake opens as it is, to be put right
|
|
1241
|
-
self.
|
|
1242
|
-
editor = os.environ.get("EDITOR") or ("notepad.exe" if os.name == "nt" else "vi")
|
|
1243
|
-
command = [editor] if os.path.isfile(editor) else split(editor, posix=os.name != "nt")
|
|
1244
|
-
async with in_terminal():
|
|
1245
|
-
result = await asyncio.to_thread(subprocess.run, [*command, str(path)], check=False)
|
|
1246
|
-
if result.returncode:
|
|
1247
|
-
raise ValueError(f"the editor exited with code {result.returncode}")
|
|
1314
|
+
await self._edit(path)
|
|
1248
1315
|
try:
|
|
1249
1316
|
rows = models(data())
|
|
1250
1317
|
except ValueError as error:
|
|
@@ -44,36 +44,3 @@ class WindowsInlineRenderer(Renderer):
|
|
|
44
44
|
self._reflow_cursor()
|
|
45
45
|
super().erase(leave_alternate_screen)
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
class ReflowInlineRenderer(Renderer):
|
|
49
|
-
"""Account for a macOS terminal reflowing inline rows after its width changes.
|
|
50
|
-
|
|
51
|
-
Erase only the previous live region, preserving transcript scrollback above it.
|
|
52
|
-
Windows uses its console-buffer implementation above.
|
|
53
|
-
"""
|
|
54
|
-
|
|
55
|
-
def _reflow_cursor(self):
|
|
56
|
-
size = self.output.get_size()
|
|
57
|
-
old = self._last_size
|
|
58
|
-
screen = self._last_screen
|
|
59
|
-
if screen is None or old is None or old.columns == size.columns:
|
|
60
|
-
return False
|
|
61
|
-
width = max(1, size.columns)
|
|
62
|
-
y = 0
|
|
63
|
-
for index in range(self._cursor_pos.y):
|
|
64
|
-
row = screen.data_buffer[index]
|
|
65
|
-
end = max((x + max(cell.width, 1) for x, cell in row.items()
|
|
66
|
-
if cell.char != " " or self._style_string_has_style[cell.style]), default=0)
|
|
67
|
-
y += max(1, (min(end, old.columns) + width - 1) // width)
|
|
68
|
-
self._cursor_pos = Point(self._cursor_pos.x % width, y + self._cursor_pos.x // width)
|
|
69
|
-
return True
|
|
70
|
-
|
|
71
|
-
def render(self, app, layout, is_done=False):
|
|
72
|
-
if self._reflow_cursor():
|
|
73
|
-
super().erase(leave_alternate_screen=False)
|
|
74
|
-
self.request_absolute_cursor_position()
|
|
75
|
-
super().render(app, layout, is_done)
|
|
76
|
-
|
|
77
|
-
def erase(self, leave_alternate_screen=True):
|
|
78
|
-
self._reflow_cursor()
|
|
79
|
-
super().erase(leave_alternate_screen)
|