@lmmslab/harness 0.83.0 → 0.85.0

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 (38) hide show
  1. package/bin/harness.js +6 -1
  2. package/package.json +1 -1
  3. package/python/harness/__init__.py +1 -1
  4. package/python/harness/builtin/prompts/core/core.md +68 -38
  5. package/python/harness/builtin/prompts/shared/learning-goal.md +1 -1
  6. package/python/harness/cli.py +140 -18
  7. package/python/harness/config/agent.py +3 -0
  8. package/python/harness/core/trace.py +23 -3
  9. package/python/harness/core/worker.py +6 -0
  10. package/python/harness/host/client.py +26 -21
  11. package/python/harness/host/http.py +11 -1
  12. package/python/harness/host/sessions.py +38 -3
  13. package/python/harness/host/tasks.py +71 -27
  14. package/python/harness/instructions.py +329 -0
  15. package/python/harness/model_list.py +25 -5
  16. package/python/harness/packages/environments.py +51 -12
  17. package/python/harness/packages/manager.py +379 -102
  18. package/python/harness/packages/resolve.py +52 -15
  19. package/python/harness/packages/sources.py +17 -5
  20. package/python/harness/packages/state.py +10 -0
  21. package/python/harness/providers.py +66 -24
  22. package/python/harness/runtime/decision/model.py +9 -4
  23. package/python/harness/runtime/events.py +1 -0
  24. package/python/harness/runtime/execution/entries.py +53 -7
  25. package/python/harness/runtime/execution/session.py +57 -10
  26. package/python/harness/runtime/learning/active.py +4 -4
  27. package/python/harness/runtime/reactive/tree.py +96 -53
  28. package/python/harness/runtime/task/environments.py +3 -1
  29. package/python/harness/runtime/task/run.py +93 -4
  30. package/python/harness/runtime/tick.py +34 -3
  31. package/python/harness/settings.py +23 -1
  32. package/python/harness/terminal.py +3 -0
  33. package/python/harness/transcript.py +12 -0
  34. package/python/harness/tui/__init__.py +28 -6
  35. package/python/harness/tui/chat.py +323 -80
  36. package/python/harness/tui/pty.py +16 -0
  37. package/python/harness/tui/renderer.py +1 -0
  38. package/python/harness/tui/views.py +160 -38
package/bin/harness.js CHANGED
@@ -66,6 +66,11 @@ child.on("error", (error) => {
66
66
  process.exit(1);
67
67
  });
68
68
  child.on("exit", (code, signal) => {
69
- if (signal) process.kill(process.pid, signal);
69
+ if (signal) {
70
+ // Restore the default disposition before replaying the child's signal. Otherwise
71
+ // our forwarding handler catches it again and Node exits with a success status.
72
+ process.removeAllListeners(signal);
73
+ process.kill(process.pid, signal);
74
+ }
70
75
  else process.exit(code === null ? 1 : code);
71
76
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmmslab/harness",
3
- "version": "0.83.0",
3
+ "version": "0.85.0",
4
4
  "description": "Automatic Control for intelligence in action",
5
5
  "license": "MIT",
6
6
  "homepage": "https://harness.lmms-lab.com",
@@ -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.83.0"
5
+ __version__ = "0.85.0"
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,25 +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
- The nodes under it divide the situation further, wherever a narrower one needs an answer
47
- of its own, and the last of them answers what is in the situation and in none of the
48
- others, with what fits the whole situation or by telling you. This holds at every depth,
49
- and how far a situation is divided follows from how much you know of it. So what you
50
- have never met is still answered, by the narrowest situation it falls in; and when you
51
- come to know it, you divide there, where its place among everything else is already
52
- settled. What happens to the agent whatever it is doing belongs in the tree, also when
53
- you met it inside one program: answered there, it is answered nowhere else. What you set
54
- out to do is not in it, however often you do it: a way of doing something that you have
55
- learned is kept as a skill you call, not as a node. A node has done its work when its
56
- situation is over: when its program ends and the situation is not over, a later node at
57
- its place has the environment, or you are told what the program did. The tree is
58
- consistent when in every situation it is settled which node has the environment: a
59
- node's place is what it costs when it does not act now, the costlier the earlier; and a
60
- node takes the environment only where you would, seeing everything as it is then. A
61
- reflex acts in your place, so its condition is your whole judgement, what it interrupts
62
- and whether this is the moment included, and what it does leaves things so that what it
63
- interrupted can go on.
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.
64
81
 
65
82
  Build each thing for the situations it has to work in, and think and test in proportion
66
83
  to what a failure costs: settle in the design what is cheap to settle; test what is
@@ -145,10 +162,12 @@ The calls every agent has:
145
162
  <!-- end -->
146
163
  <!-- end -->
147
164
  What acts without you is one tree, empty at first. A node of it says when it has its
148
- turn and what it does then; a node under another has its turn only while that one's
149
- condition holds. Among the nodes at one place the earlier takes the environment from the
150
- later, and gives it back when it is done. What several nodes need is said once: a
151
- condition as the node above them or as a sense, an action as a function they call.
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.
152
171
  - set_reflex(name, when, do=None, under=None, priority=0, every=None, again_seconds=0):
153
172
  put the node `name` into the tree, in place of a node of that name.
154
173
  when: a function of the view: the node has its turn while it holds. It is judged
@@ -157,12 +176,17 @@ condition as the node above them or as a sense, an action as a function they cal
157
176
  do: a program (a function): started as a unit when the node's turn comes; what it is
158
177
  for is that the node's condition no longer holds. It begins again while the turn lasts,
159
178
  not before again_seconds after it ended; a program that answers an event gets the event
160
- when it takes an argument. Or the name of an event: you are
161
- told it, once each time the condition comes to hold. Or "stop": what runs is ended.
162
- Or nothing: the node is a group, and the nodes set with under=name are its content.
163
- priority (a whole number, 0 or more): the node's place among those where it is, the
164
- higher first, among equals the older. A node's program takes the environment from your
165
- programs.
179
+ when it takes an argument. Or the name of an event: you are told it, once each time
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.
186
+ priority (a whole number, 0 or more): the node's own, wherever it is in the tree. Of
187
+ two nodes whose turn it is the higher has the environment, among equals the earlier in
188
+ the tree; and it is the number a program's at_priority(n) is compared with. A node's
189
+ program takes the environment from your programs.
166
190
  every: the seconds between judgements of its condition; without it the condition is
167
191
  judged when the state or the facts change.
168
192
  A condition is read, not computed: the conditions judged in one moment share a few
@@ -207,16 +231,22 @@ has its call started again by itself then (its result counts it: .restarts).
207
231
  <!-- end -->
208
232
  What you start meanwhile waits for the higher unit to end. Units of equal priority take
209
233
  turns.
210
- Your programs have priority 0, so every reflex takes the environment from them. A
211
- program has its place among the reflexes like a node: at_priority(n) gives it one, from
212
- that call to its end. A reflex at the top of the tree with priority n or more, and what is
213
- under it, still takes the environment from the program, which goes on as said above. A
214
- reflex below n waits: it is judged again when the program has ended, and you are told
215
- once that it was held back (the event HELD_BACK); cancelling the program lets it act. So a
216
- program that does itself what some reflexes answer stands above those and below the rest:
217
- what happens to the agent and is not the program's business still has its reflex.
234
+ Your programs have priority 0, so every reflex takes the environment from them. An
235
+ action of a program that must not be broken off takes a place among the reflexes for as
236
+ long as it lasts: `with at_priority(n):` around that action, and no longer. During the
237
+ block a reflex whose own priority is n or more still takes the environment from the
238
+ program, which goes on as said above; a reflex below n waits: it is judged again when the
239
+ block ends, and you are told once that it was held back (the event HELD_BACK). The place is the action's, not the program's or a stage's:
240
+ while it is held, nothing below it answers what happens to the agent, so a program that
241
+ holds one for its whole length has taken the tree's work on itself and must do all of it.
242
+ Code that runs for long in the environment itself asks for a place the same way, where
243
+ the environment's page says how.
218
244
  Conditions and controllers read the supplied view. Keep them fast and free of file,
219
- network, process and input operations.
245
+ network, process and input operations. Beside the state as it is, the view holds what a
246
+ state alone does not show: view["was"][key], what that part of the state was before it
247
+ last changed; view["unchanged"][key], for how many seconds it has not changed (the senses
248
+ under ["sensed"] in both); and view["units"], the units that run, each {"name", "kind",
249
+ "reflex", "priority", "seconds"}.
220
250
  <!-- if: memory -->
221
251
  <!-- if: legacy_memory -->
222
252
  - recall(query): what earlier runs kept about a situation like this one.
@@ -1,6 +1,6 @@
1
1
  This run is practice for a task, not the task itself: {task}
2
2
 
3
- You have {minutes} minutes of live time; what your library holds and what the environment keeps for you when it is over is what the runs that do the task start with.
3
+ What your library holds and what the environment keeps for you when this run is over is what the runs that do the task start with.
4
4
 
5
5
  Something is learned when it has done its work without help, more than once, starting from what the parts before it really leave. Where the environment lets you set that starting situation up directly, do so instead of working your way to it each time. What was practised from a better start than the task gives it has shown nothing yet.
6
6
  {probe}
@@ -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):
@@ -266,7 +269,7 @@ def _continue_arguments(command, name: str):
266
269
  """The flags that go on with an earlier session in its own id instead of starting one."""
267
270
  which = command.add_mutually_exclusive_group()
268
271
  which.add_argument("--continue", dest="continue_last", action="store_true",
269
- help="go on with the most recent session: its messages and facts, in the same session id")
272
+ help="go on with the session you last messaged or resumed, in the same session id")
270
273
  which.add_argument(name, dest="session", metavar="SESSION",
271
274
  help="go on with that session (its id, as harness sessions ls --all lists it)")
272
275
 
@@ -286,6 +289,17 @@ def _continued(args):
286
289
  return host, conversation, max((int(record.get("seq", -1)) for record in records), default=-1)
287
290
 
288
291
 
292
+ def _check_continuation_options(args):
293
+ """A continuation uses its saved settings; reject new-task options before any host call."""
294
+ if not (getattr(args, "continue_last", False) or getattr(args, "session", None)):
295
+ return
296
+ selection = any(getattr(args, key, None) is not None for key in ("model", "effort", "workspace", "vm_image", "library"))
297
+ if selection or _coding(args) or _run_options(args) or getattr(args, "learn_while_working", False):
298
+ raise UsageError("continuation keeps the saved model, workspace and run settings; "
299
+ "omit --model/--effort and other new-conversation options with --continue/--resume/--session. "
300
+ "In an open terminal, /effort LEVEL changes that conversation; /model selects only new ones")
301
+
302
+
289
303
  def parser(packages: bool = True):
290
304
  root = argparse.ArgumentParser(prog="harness", description="Automatic Control for intelligence in action.",
291
305
  epilog="harness with no command: the terminal chat with the agent on this computer "
@@ -293,6 +307,8 @@ def parser(packages: bool = True):
293
307
  "packages, library)")
294
308
  root.add_argument("--version", action="version", version=f"harness {__version__}")
295
309
  _continue_arguments(root, "--resume")
310
+ root.add_argument("--model", help="an enabled model from ~/.harness/models.json (ID or provider/model)")
311
+ root.add_argument("--effort", help="the selected model's reasoning effort ID")
296
312
  run_flags(root)
297
313
  _coding_arguments(root)
298
314
  root.add_argument("--managed-workspace", action="store_true", help="use an isolated managed workspace (supported Linux hosts)")
@@ -322,7 +338,7 @@ def parser(packages: bool = True):
322
338
  _session_commands(commands.add_parser("sessions", help="Manage the session host's coding sessions"))
323
339
  install = commands.add_parser("install", help="Install packages (and what they depend on), or update them; and "
324
340
  "the services and benches they provide",
325
- epilog="harness install browser; harness install computer@^0.5; harness install "
341
+ epilog="harness install browser; harness install computer@^0.8; harness install "
326
342
  "git:github.com/x/y@main#packages/z; harness install ./my-package --link; "
327
343
  "harness install --update (all); harness install sam3 (a service). With no "
328
344
  "names in a folder with harness.toml: the project's packages, from its "
@@ -336,6 +352,8 @@ def parser(packages: bool = True):
336
352
  "without asking (they run code on this computer)")
337
353
  install.add_argument("--link", action="store_true", help="a folder: use it where it is instead of a copy (a "
338
354
  "package under development)")
355
+ install.add_argument("--tui", action="store_true", help="prepare the terminal interface's pinned libraries, "
356
+ "without starting a conversation")
339
357
  install.add_argument("--deploy", help="services: the deploy that places them (default $HARNESS_DEPLOY)")
340
358
  listed = commands.add_parser("list", help="The installed packages; --available: the registry's (QUERY "
341
359
  "searches them); one package by its name: what it provides")
@@ -357,6 +375,11 @@ def parser(packages: bool = True):
357
375
  replay.add_argument("run", help="an episode directory, a conversation (its name under conversations/), or a "
358
376
  "session (SESSION or SESSION/AGENT)")
359
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")
360
383
  doctor = commands.add_parser("doctor", help="Whether this computer can run the agent: Python, the model and its "
361
384
  "key, the packages; or services, or an experiment (the eval "
362
385
  "package's: harness doctor EXPERIMENT --help)",
@@ -439,10 +462,14 @@ def _core_report() -> dict:
439
462
  problems, notes = [], []
440
463
  if sys.version_info < (3, 11):
441
464
  problems.append(f"Python {sys.version.split()[0]}: 3.11 or newer is needed")
442
- model = providers.ready(data())
443
- if not model["ready"]:
444
- problems.append(f"no model set up ({model['provider']}: {model['key_env']} is not set): run harness once "
445
- "in a terminal, or export the key")
465
+ try:
466
+ model = providers.ready(data())
467
+ if not model["ready"]:
468
+ problems.append(model["detail"] if model.get("selection_error") else
469
+ f"no model set up ({model['provider']}: {model['detail']}): run harness once "
470
+ "in a terminal, or configure the selected model")
471
+ except (ValueError, OSError) as error:
472
+ problems.append(str(error))
446
473
  notes.append("No package places services here: hosted models only (harness install local-models for "
447
474
  "models on this machine's GPUs).")
448
475
  return {"schema_version": 1, "deploy": "none", "ok": not problems, "problems": problems, "notes": notes,
@@ -506,6 +533,9 @@ def _install(args):
506
533
  from .packages import Packages, activate, provision
507
534
  from .services.placement import load_deploy
508
535
 
536
+ terminal = getattr(args, "tui", False)
537
+ if terminal and args.update:
538
+ raise UsageError("--tui prepares the terminal; run it separately from --update")
509
539
  packages = activate(Packages())
510
540
  if args.update:
511
541
  result = packages.update(args.names, project=args.project, log=_note)
@@ -515,7 +545,7 @@ def _install(args):
515
545
  known = set(deploy.services) | set(bench_specs())
516
546
  specs = [name for name in args.names if name not in known]
517
547
  result = {"installed": [], "problems": []}
518
- if specs or (not args.names and args.project) or (not args.names and packages.project() is not None):
548
+ if specs or (not args.names and args.project) or (not args.names and not terminal and packages.project() is not None):
519
549
  def consent(found):
520
550
  for package in found:
521
551
  _print_package(package, file=sys.stderr)
@@ -532,7 +562,7 @@ def _install(args):
532
562
  result = packages.install(specs, project=project, consent=consent, link=args.link, log=_note)
533
563
  if result.get("needs_trust"):
534
564
  return 1
535
- elif not args.names:
565
+ elif not args.names and not terminal:
536
566
  return _usage("install", "name packages, services or benches (or run it where harness.toml names the "
537
567
  "project's packages)")
538
568
  # A name a package just brought (a bench) is installed as one now too: its environment.
@@ -541,6 +571,14 @@ def _install(args):
541
571
  benches = [name for name in provisioned if name in bench_specs()]
542
572
  services = [name for name in provisioned if name not in benches]
543
573
  rows = [provision.install_bench_environment(deploy, name, log=_note) for name in benches]
574
+ if terminal:
575
+ from .tui import environment
576
+ from .packages import environments
577
+
578
+ prepared = environment()
579
+ environments.install(prepared, log=_note)
580
+ rows.append({"name": "tui", "what": "frontend", "installed": True,
581
+ "environment": str(prepared.directory)})
544
582
  if services:
545
583
  # Services' environments and weights: the package that places services installs them.
546
584
  from .extensions import require
@@ -594,13 +632,19 @@ def _note(message):
594
632
  print(message, file=sys.stderr, flush=True)
595
633
 
596
634
 
597
- def _ready_model(interactive: bool) -> None:
635
+ def _ready_model(interactive: bool, *, recovery: bool = False) -> str | None:
598
636
  """A model and its key, asked for on the first run in a terminal (providers.setup)."""
599
- from . import model_list, providers
637
+ from . import providers
600
638
  from .paths import data
601
639
 
602
- if model_list.select(data()) is not None or providers.ready(data())["ready"]:
640
+ model = providers.ready(data())
641
+ if model["ready"]:
603
642
  return
643
+ if model.get("selection_error") or ((data() / "models.json").exists() and
644
+ model["detail"].startswith("add an enabled model")):
645
+ if recovery:
646
+ return f"{model['detail']}; use /model to choose an enabled model or /models to edit the list"
647
+ raise UsageError(model["detail"])
604
648
  if not (interactive and sys.stdin.isatty()):
605
649
  raise UsageError("no model is set up yet: run harness in a terminal once (it asks for the model and key), "
606
650
  "or export the provider's key")
@@ -627,6 +671,8 @@ def _run_options(args) -> dict:
627
671
  options["learn"] = args.learn
628
672
  if getattr(args, "agents", False):
629
673
  options["agents"] = True
674
+ if getattr(args, "bare", False):
675
+ options["instructions"] = {"load": "off"}
630
676
  return options
631
677
 
632
678
 
@@ -667,6 +713,12 @@ def _starter(args):
667
713
  its environment for that many minutes. It keeps the last it started."""
668
714
  def start(text, files=(), log=None, learn=None, model_entry=None, reasoning_effort=None, workspace=None,
669
715
  folder=None, agents=None):
716
+ # Effort belongs to the startup route. A route picked in the TUI with no
717
+ # effort explicitly asks for that route's default, not the CLI route's effort.
718
+ if model_entry is None and start.model_entry is not None:
719
+ model_entry = start.model_entry
720
+ if reasoning_effort is None:
721
+ reasoning_effort = start.model_effort
670
722
  runtime = {**_run_options(args), **({"learn": learn} if learn is not None else {}),
671
723
  **({"agents": True} if agents else {})}
672
724
  coding = _coding(args)
@@ -696,6 +748,23 @@ def _starter(args):
696
748
  return start.host, start.conversation
697
749
 
698
750
  start.host = start.conversation = None
751
+ start.model_entry = start.model_effort = start.model_name = None
752
+ if not _coding(args).get("agent") and not (
753
+ getattr(args, "continue_last", False) or getattr(args, "session", None)) and (
754
+ getattr(args, "model", None) is not None or getattr(args, "effort", None) is not None):
755
+ from .model_list import SelectionError, select
756
+ from .paths import data
757
+
758
+ try:
759
+ initial = select(data(), getattr(args, "model", None))
760
+ except SelectionError:
761
+ # An effort-only flag must not close the UI needed to repair a default.
762
+ if getattr(args, "model", None) is not None:
763
+ raise
764
+ initial = None
765
+ if initial is not None:
766
+ start.model_entry, start.model_effort = initial["id"], getattr(args, "effort", None)
767
+ start.model_name = initial["name"]
699
768
  # The command line already says where it works: the chat does not ask at its opening.
700
769
  start.named = bool(getattr(args, "workspace", None) or getattr(args, "folder", None)
701
770
  or getattr(args, "agent", None))
@@ -777,9 +846,11 @@ def _run_task(args):
777
846
  from .terminal import Printer
778
847
  from .transcript import answer_of
779
848
 
849
+ _check_continuation_options(args)
780
850
  if args.model and _coding(args).get("agent"):
781
851
  raise UsageError("--model selects its own provider; use either --model or --agent")
782
- if not _coding(args).get("agent") and not args.model:
852
+ if not _coding(args).get("agent") and not args.model and not (
853
+ getattr(args, "continue_last", False) or getattr(args, "session", None)):
783
854
  _ready_model(interactive=True)
784
855
  from .settings import ChoiceRequired
785
856
 
@@ -924,6 +995,9 @@ def _rpc(args):
924
995
  it ends when stdin closes, after end, or when the conversation ends."""
925
996
  from .terminal import COMMANDS, command as run_command
926
997
 
998
+ if getattr(args, "continue_last", False) or getattr(args, "session", None):
999
+ raise UsageError("run rpc starts a new conversation; use harness run --continue or --session ID "
1000
+ "for an existing conversation")
927
1001
  if args.model and _coding(args).get("agent"):
928
1002
  raise UsageError("--model selects its own provider; use either --model or --agent")
929
1003
  if not _coding(args).get("agent") and not args.model:
@@ -1028,17 +1102,26 @@ def _rpc(args):
1028
1102
  def _default(args):
1029
1103
  """harness with no command: the terminal chat with the agent on this computer, which
1030
1104
  starts a conversation with the first message; the first run asks for the model and key."""
1031
- if not _coding(args).get("agent"):
1032
- _ready_model(interactive=True)
1105
+ _check_continuation_options(args)
1106
+ selecting = getattr(args, "model", None) is not None or getattr(args, "effort", None) is not None
1107
+ if selecting and _coding(args).get("agent"):
1108
+ raise UsageError("the terminal's --agent cannot be combined with --model or --effort; "
1109
+ "use harness run --agent NAME --effort LEVEL for an explicit agent effort")
1033
1110
  if not (sys.stdin.isatty() and sys.stdout.isatty()):
1034
1111
  raise UsageError("the terminal chat needs a terminal: harness run \"task\", or harness run rpc")
1035
1112
  from . import tui
1036
1113
 
1037
1114
  continued = _continued(args)
1115
+ start = _starter(args)
1116
+ start.warning = None
1117
+ if continued is None and not _coding(args).get("agent") and not getattr(args, "model", None):
1118
+ start.warning = _ready_model(interactive=True, recovery=True)
1119
+ if getattr(args, "effort", None) is not None and start.model_entry is None:
1120
+ start.warning = (start.warning or "") + " --effort was not applied; choose a model, then use /effort LEVEL."
1038
1121
  if continued is not None:
1039
- tui.chat(continued[1], host=continued[0], start=_starter(args))
1122
+ tui.chat(continued[1], host=continued[0], start=start)
1040
1123
  else:
1041
- tui.chat(start=_starter(args))
1124
+ tui.chat(start=start)
1042
1125
  return 0
1043
1126
 
1044
1127
 
@@ -1153,6 +1236,32 @@ def _sessions(args):
1153
1236
  return 0
1154
1237
 
1155
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
+
1156
1265
  def _replay(args):
1157
1266
  """harness replay RUN: terminal records, or raw records with --json."""
1158
1267
  from .core.episodes import read_records
@@ -1207,6 +1316,11 @@ def _library_command(args):
1207
1316
 
1208
1317
 
1209
1318
  def main(argv=None):
1319
+ """Catch setup and activation failures as well as command-dispatch failures."""
1320
+ return _guarded(lambda: _main(argv))
1321
+
1322
+
1323
+ def _main(argv=None):
1210
1324
  words = list(sys.argv[1:] if argv is None else argv)
1211
1325
  if words[:1] == ["rpc"]:
1212
1326
  words.insert(0, "run")
@@ -1228,15 +1342,23 @@ def main(argv=None):
1228
1342
  return _guarded(lambda: _package_command(words[0], words[1:]))
1229
1343
  command_parser = parser()
1230
1344
  args, rest = command_parser.parse_known_args(words)
1345
+ if args.command is not None and words and words[0].startswith("-"):
1346
+ raise UsageError("put options after the command, for example: harness run \"task\" --model MODEL")
1231
1347
  if rest and args.command != "doctor":
1232
1348
  command_parser.parse_args(words) # says what it does not know, exit status 2
1233
1349
  if args.command not in (None, "install", "remove", "list"):
1234
1350
  # The enabled packages' skills load here and in the kernels it starts.
1235
1351
  from .packages import activate
1236
1352
 
1237
- activate()
1353
+ try:
1354
+ activate()
1355
+ except (ValueError, OSError, RuntimeError, ImportError) as error:
1356
+ if args.command == "doctor" and args.json:
1357
+ output({"schema_version": 1, "ok": False, "problems": [str(error)], "error": str(error)})
1358
+ return 1
1359
+ raise
1238
1360
  commands = {"install": _install, "list": _list, "remove": _remove, "library": _library_command, "sessions": _sessions,
1239
- "replay": _replay}
1361
+ "replay": _replay, "instructions": _instructions}
1240
1362
  if args.command == "run":
1241
1363
  if args.task == "rpc" and not explicit_task:
1242
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>/...
@@ -66,11 +66,31 @@ class Trace:
66
66
  def __init__(self, directory: Path, kinds: dict | None = None, *, append: bool = False):
67
67
  path = directory / "events.jsonl"
68
68
  if append:
69
- from .episodes import read_records
70
-
71
69
  if not path.is_file():
72
70
  raise ValueError("the existing session trace is missing")
73
- sequence = max((record["seq"] for record in read_records(directory)), default=-1) + 1
71
+ # The caller has reclaimed the ended conversation before opening its writer.
72
+ # Validate all complete events before repairing only the interrupted last line.
73
+ sequence = 0
74
+ with path.open("r+b") as handle:
75
+ while True:
76
+ offset = handle.tell()
77
+ line = handle.readline()
78
+ if not line:
79
+ break
80
+ if line.endswith(b"\n"):
81
+ record = json.loads(line)
82
+ else:
83
+ try:
84
+ record = json.loads(line)
85
+ except (ValueError, UnicodeError):
86
+ handle.truncate(offset)
87
+ break
88
+ # A complete JSON event without its newline is still history.
89
+ sequence = max(sequence, record["seq"] + 1)
90
+ handle.seek(0, 2)
91
+ handle.write(b"\n")
92
+ break
93
+ sequence = max(sequence, record["seq"] + 1)
74
94
  else:
75
95
  directory.mkdir(parents=True, exist_ok=False)
76
96
  path.touch()
@@ -42,6 +42,12 @@ from .ports import OwnPort
42
42
  # `by` names who takes the environment (a reflex, or a unit), for what is held to know;
43
43
  # resume(episode_id, held) is given that value and lets it go on. The run then pauses a
44
44
  # call for a unit of higher priority instead of ending it (runtime/tick.py).
45
+ #
46
+ # Priority (optional). Code that runs in the environment for long (a routine the agent saved
47
+ # there) may hold the environment for one action of it, as a program does with
48
+ # `with at_priority(n):`. The worker says so with its state: "priority", the priority that
49
+ # code asks for now (a number above 0; absent or None: none). The unit whose call runs holds
50
+ # the environment with it for as long as the state says so (runtime/tick.py _asked).
45
51
  WORKER_METHODS = ("profile", "state", "tick", "observe", "claim_outcome", "outcome", "tell_to")
46
52
 
47
53