@lmmslab/harness 0.0.0-stage → 0.81.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/LICENSE +21 -0
- package/README.md +124 -2
- package/bin/harness.js +71 -0
- package/package.json +34 -4
- package/python/harness/README.md +72 -0
- package/python/harness/__init__.py +8 -0
- package/python/harness/__main__.py +3 -0
- package/python/harness/bench.py +124 -0
- package/python/harness/builtin/benches/README.md +5 -0
- package/python/harness/builtin/benches/none/bench.toml +6 -0
- package/python/harness/builtin/configs/README.md +26 -0
- package/python/harness/builtin/configs/assistant.toml +11 -0
- package/python/harness/builtin/configs/default.toml +33 -0
- package/python/harness/builtin/configs/deploy/example-api.toml +10 -0
- package/python/harness/builtin/configs/models/deepseek-api.toml +21 -0
- package/python/harness/builtin/configs/models/deepseek-flash.toml +12 -0
- package/python/harness/builtin/configs/models/grok-low.toml +8 -0
- package/python/harness/builtin/configs/models/grok-medium.toml +43 -0
- package/python/harness/builtin/configs/models/opus-5.5.toml +11 -0
- package/python/harness/builtin/environment/README.md +53 -0
- package/python/harness/builtin/environment/constraints.txt +31 -0
- package/python/harness/builtin/model-settings.js +143 -0
- package/python/harness/builtin/prompts/conversation/core.md +5 -0
- package/python/harness/builtin/prompts/conversation/pack.toml +12 -0
- package/python/harness/builtin/prompts/core/core.md +88 -0
- package/python/harness/builtin/prompts/core/pack.toml +9 -0
- package/python/harness/builtin/prompts/reflect/core.md +45 -0
- package/python/harness/builtin/prompts/reflect/pack.toml +7 -0
- package/python/harness/builtin/prompts/shared/agent-skills.md +5 -0
- package/python/harness/builtin/prompts/shared/agents.md +14 -0
- package/python/harness/builtin/prompts/shared/checklist.md +21 -0
- package/python/harness/builtin/prompts/shared/entries.md +86 -0
- package/python/harness/builtin/prompts/shared/environments.md +21 -0
- package/python/harness/builtin/prompts/shared/learning-goal.md +31 -0
- package/python/harness/builtin/prompts/shared/learning.md +27 -0
- package/python/harness/builtin/prompts/shared/mcp.md +9 -0
- package/python/harness/builtin/prompts/shared/world.md +1 -0
- package/python/harness/builtin/skills/README.md +10 -0
- package/python/harness/builtin/skills/agents/__init__.py +88 -0
- package/python/harness/builtin/skills/agents/skill.toml +11 -0
- package/python/harness/builtin/skills/checklist/__init__.py +32 -0
- package/python/harness/builtin/skills/checklist/skill.toml +9 -0
- package/python/harness/builtin/skills/conversation/__init__.py +23 -0
- package/python/harness/builtin/skills/conversation/skill.toml +8 -0
- package/python/harness/builtin/skills/entries/__init__.py +62 -0
- package/python/harness/builtin/skills/entries/skill.toml +8 -0
- package/python/harness/builtin/skills/environments/__init__.py +69 -0
- package/python/harness/builtin/skills/environments/skill.toml +9 -0
- package/python/harness/builtin/skills/experience/__init__.py +27 -0
- package/python/harness/builtin/skills/experience/skill.toml +9 -0
- package/python/harness/builtin/skills/instructions/__init__.py +29 -0
- package/python/harness/builtin/skills/instructions/skill.toml +9 -0
- package/python/harness/builtin/skills/learning/__init__.py +189 -0
- package/python/harness/builtin/skills/learning/skill.toml +7 -0
- package/python/harness/builtin/skills/mcp/__init__.py +54 -0
- package/python/harness/builtin/skills/mcp/skill.toml +10 -0
- package/python/harness/builtin/skills/memory/__init__.py +130 -0
- package/python/harness/builtin/skills/memory/skill.toml +13 -0
- package/python/harness/builtin/skills/verify/__init__.py +31 -0
- package/python/harness/builtin/skills/verify/skill.toml +7 -0
- package/python/harness/builtin/third_party/sources.toml +40 -0
- package/python/harness/cli.py +1182 -0
- package/python/harness/config/__init__.py +224 -0
- package/python/harness/config/agent.py +777 -0
- package/python/harness/core/__init__.py +52 -0
- package/python/harness/core/artifacts.py +46 -0
- package/python/harness/core/codec.py +160 -0
- package/python/harness/core/contracts.py +75 -0
- package/python/harness/core/episodes.py +150 -0
- package/python/harness/core/format.py +51 -0
- package/python/harness/core/http.py +124 -0
- package/python/harness/core/lanes.py +324 -0
- package/python/harness/core/linux_sandbox.py +55 -0
- package/python/harness/core/media.py +96 -0
- package/python/harness/core/memory.py +147 -0
- package/python/harness/core/ports.py +63 -0
- package/python/harness/core/procs.py +227 -0
- package/python/harness/core/remote.py +102 -0
- package/python/harness/core/spans.py +166 -0
- package/python/harness/core/trace.py +139 -0
- package/python/harness/core/wait.py +12 -0
- package/python/harness/core/worker.py +388 -0
- package/python/harness/core/worker_pipe.py +119 -0
- package/python/harness/embodiments.py +217 -0
- package/python/harness/extensions.py +112 -0
- package/python/harness/host/__init__.py +397 -0
- package/python/harness/host/client.py +201 -0
- package/python/harness/host/http.py +720 -0
- package/python/harness/host/listing.py +68 -0
- package/python/harness/host/server.py +189 -0
- package/python/harness/host/sessions.py +406 -0
- package/python/harness/host/tasks.py +1356 -0
- package/python/harness/host/workers.py +257 -0
- package/python/harness/host/workspaces.py +256 -0
- package/python/harness/model_list.py +117 -0
- package/python/harness/packages/__init__.py +73 -0
- package/python/harness/packages/addons.py +121 -0
- package/python/harness/packages/archive.py +122 -0
- package/python/harness/packages/describe.py +46 -0
- package/python/harness/packages/environments.py +448 -0
- package/python/harness/packages/fetch.py +57 -0
- package/python/harness/packages/manager.py +587 -0
- package/python/harness/packages/manifest.py +232 -0
- package/python/harness/packages/migrate.py +68 -0
- package/python/harness/packages/provision.py +38 -0
- package/python/harness/packages/registry.py +275 -0
- package/python/harness/packages/resolve.py +89 -0
- package/python/harness/packages/sources.py +141 -0
- package/python/harness/packages/state.py +213 -0
- package/python/harness/packages/versions.py +112 -0
- package/python/harness/paths.py +218 -0
- package/python/harness/providers.py +303 -0
- package/python/harness/runtime/__init__.py +8 -0
- package/python/harness/runtime/decision/__init__.py +1 -0
- package/python/harness/runtime/decision/loop.py +198 -0
- package/python/harness/runtime/decision/messages.py +271 -0
- package/python/harness/runtime/decision/model.py +424 -0
- package/python/harness/runtime/decision/prompts.py +248 -0
- package/python/harness/runtime/decision/protocol.py +169 -0
- package/python/harness/runtime/decision/thoughts.py +199 -0
- package/python/harness/runtime/events.py +213 -0
- package/python/harness/runtime/execution/__init__.py +1 -0
- package/python/harness/runtime/execution/attached.py +96 -0
- package/python/harness/runtime/execution/control.py +211 -0
- package/python/harness/runtime/execution/entries.py +665 -0
- package/python/harness/runtime/execution/kernel.py +811 -0
- package/python/harness/runtime/execution/noenv.py +84 -0
- package/python/harness/runtime/execution/results.py +40 -0
- package/python/harness/runtime/execution/session.py +871 -0
- package/python/harness/runtime/execution/skills.py +436 -0
- package/python/harness/runtime/learning/__init__.py +1 -0
- package/python/harness/runtime/learning/active.py +314 -0
- package/python/harness/runtime/learning/experience.py +48 -0
- package/python/harness/runtime/learning/fixtures.py +167 -0
- package/python/harness/runtime/learning/learner.py +651 -0
- package/python/harness/runtime/learning/library.py +504 -0
- package/python/harness/runtime/learning/reflect.py +151 -0
- package/python/harness/runtime/learning/usage.py +30 -0
- package/python/harness/runtime/learning/views.py +89 -0
- package/python/harness/runtime/reactive/__init__.py +1 -0
- package/python/harness/runtime/reactive/rules.py +549 -0
- package/python/harness/runtime/safety/__init__.py +1 -0
- package/python/harness/runtime/safety/approval.py +131 -0
- package/python/harness/runtime/safety/input.py +62 -0
- package/python/harness/runtime/safety/isolation.py +419 -0
- package/python/harness/runtime/safety/shield.py +129 -0
- package/python/harness/runtime/status.py +23 -0
- package/python/harness/runtime/task/__init__.py +7 -0
- package/python/harness/runtime/task/context.py +431 -0
- package/python/harness/runtime/task/delegation.py +468 -0
- package/python/harness/runtime/task/environments.py +268 -0
- package/python/harness/runtime/task/run.py +2878 -0
- package/python/harness/runtime/tick.py +909 -0
- package/python/harness/sdk/__init__.py +281 -0
- package/python/harness/services/__init__.py +6 -0
- package/python/harness/services/broker.py +35 -0
- package/python/harness/services/connectors.py +88 -0
- package/python/harness/services/mcp.py +298 -0
- package/python/harness/services/mcp_stdio.py +131 -0
- package/python/harness/services/placement.py +82 -0
- package/python/harness/services/registry.py +156 -0
- package/python/harness/settings.py +536 -0
- package/python/harness/terminal.py +79 -0
- package/python/harness/transcript.py +297 -0
- package/python/harness/tui/__init__.py +68 -0
- package/python/harness/tui/chat.py +1181 -0
- package/python/harness/tui/pty.py +81 -0
- package/python/harness/tui/renderer.py +45 -0
- package/python/harness/tui/timeline_rows.py +58 -0
- package/python/harness/tui/views.py +434 -0
|
@@ -0,0 +1,1182 @@
|
|
|
1
|
+
"""The command line:
|
|
2
|
+
|
|
3
|
+
harness the terminal chat (tui/): the first run asks for the model and key
|
|
4
|
+
harness run "task" [-p] [--json] do a task and end: -p prints only the answer, --json every record
|
|
5
|
+
harness run rpc drive the agent from another program: JSON lines both ways
|
|
6
|
+
harness install | list | remove packages (list searches the registry and shows one package)
|
|
7
|
+
harness library what the agent learned
|
|
8
|
+
harness replay RUN a run as it went, in the terminal
|
|
9
|
+
harness doctor whether this computer can run the agent
|
|
10
|
+
|
|
11
|
+
Installed packages add their own commands (package.toml [provides] commands); `harness run
|
|
12
|
+
EXPERIMENT` and `harness doctor EXPERIMENT` are the eval package's. Sessions, the session
|
|
13
|
+
host and the settings are commands of the terminal chat (/sessions, /host, /settings).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import importlib
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from queue import Queue
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
|
|
25
|
+
from . import __version__
|
|
26
|
+
from .host.sessions import ENDED
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class UsageError(ValueError):
|
|
30
|
+
"""Arguments that cannot go together: exit status 2, like argparse's own errors."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def output(value):
|
|
34
|
+
print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def table(rows, columns):
|
|
38
|
+
"""Rows of dicts as an aligned text table."""
|
|
39
|
+
cells = [[("" if row.get(column) is None else str(row.get(column))) for column in columns] for row in rows]
|
|
40
|
+
widths = [max([len(column)] + [len(line[i]) for line in cells]) for i, column in enumerate(columns)]
|
|
41
|
+
lines = [" ".join(column.ljust(width) for column, width in zip(columns, widths))]
|
|
42
|
+
lines += [" ".join(cell.ljust(width) for cell, width in zip(line, widths)) for line in cells]
|
|
43
|
+
return "\n".join(line.rstrip() for line in lines)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _is_experiment(text: str) -> bool:
|
|
47
|
+
"""Recognize a legacy experiment argument by an existing configuration."""
|
|
48
|
+
from .paths import find
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
if Path(text).suffix.lower() == ".toml" and Path(text).is_file():
|
|
52
|
+
return True
|
|
53
|
+
if Path(text).name == text and text:
|
|
54
|
+
return any(find(f"configs/{folder}/{text}.toml") for folder in ("experiments", "ablations"))
|
|
55
|
+
except (OSError, ValueError):
|
|
56
|
+
pass
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _guarded(call) -> int:
|
|
61
|
+
"""`call()`'s exit status, with the CLI's error handling."""
|
|
62
|
+
from .settings import ChoiceRequired
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
return int(call() or 0)
|
|
66
|
+
except KeyboardInterrupt:
|
|
67
|
+
return 130
|
|
68
|
+
except ChoiceRequired as error:
|
|
69
|
+
print(json.dumps({"error": str(error), "choice_required": error.choice}), file=sys.stderr, flush=True)
|
|
70
|
+
return 2
|
|
71
|
+
except UsageError as error:
|
|
72
|
+
print(json.dumps({"error": f"usage: {error}"}), file=sys.stderr, flush=True)
|
|
73
|
+
return 2
|
|
74
|
+
except (ValueError, KeyError, OSError, RuntimeError, ImportError, TimeoutError) as error:
|
|
75
|
+
print(json.dumps({"error": f"{type(error).__name__}: {error}"}), file=sys.stderr, flush=True)
|
|
76
|
+
return 1
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _package_arguments(command):
|
|
80
|
+
command.add_argument("--project", action="store_true", help="the project's packages (harness.toml and "
|
|
81
|
+
"harness.lock here or above) instead of yours")
|
|
82
|
+
command.add_argument("--json", action="store_true")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _levels(section: str):
|
|
86
|
+
"""A settings section's level choices (the computer package's physical and privacy), or
|
|
87
|
+
None where no package registers the section (then the host checks the value)."""
|
|
88
|
+
from .settings import SCHEMA
|
|
89
|
+
|
|
90
|
+
return SCHEMA[section]["level"].bounds if section in SCHEMA else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _rule_arguments(command):
|
|
94
|
+
"""harness settings rules add's flags: --level and one per field of a section's rules."""
|
|
95
|
+
from .settings import SCHEMA, rule_fields
|
|
96
|
+
|
|
97
|
+
sections = [section for section in SCHEMA if rule_fields(section)]
|
|
98
|
+
having = {}
|
|
99
|
+
for section in sections:
|
|
100
|
+
for name in rule_fields(section):
|
|
101
|
+
having.setdefault(name, []).append(section)
|
|
102
|
+
command.add_argument("--level", help="rules add: the rule's level")
|
|
103
|
+
for name, where in having.items():
|
|
104
|
+
command.add_argument(f"--{name}", help=f"rules add: the rule's {name}"
|
|
105
|
+
+ (f" ({', '.join(where)})" if len(where) < len(sections) else ""))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _run_rules(level=None, allow_apps=(), deny_apps=(), ask_apps=()) -> dict:
|
|
109
|
+
"""A run's physical-input policy from its flags: {"level", "rules"} (runtime.physical; the
|
|
110
|
+
computer's policy checks it where it is used)."""
|
|
111
|
+
rules = [*({"level": "allow", "app": app} for app in allow_apps),
|
|
112
|
+
*({"level": "ask_each", "app": app} for app in ask_apps),
|
|
113
|
+
*({"level": "never", "app": app} for app in deny_apps)]
|
|
114
|
+
return {**({"level": level} if level else {}), **({"rules": rules} if rules else {})}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_flags(command):
|
|
118
|
+
"""harness run's flags of a task's own (and an experiment's): --physical and the app rules,
|
|
119
|
+
--window-details, --think, --workspace."""
|
|
120
|
+
_physical_arguments(command)
|
|
121
|
+
_think_arguments(command)
|
|
122
|
+
_workspace_argument(command)
|
|
123
|
+
command.add_argument("--agents", action="store_true",
|
|
124
|
+
help="sub-agents on in this conversation (they are off unless the setting session.agents "
|
|
125
|
+
"is on; the agent may also ask you to switch them on)")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _coding_arguments(command):
|
|
129
|
+
command.add_argument("--agent", help="use the native agent (harness) or a configured ACP, terminal or cloud coding agent")
|
|
130
|
+
command.add_argument("--folder", type=Path, help="bind a project directory for the native Harness or an external agent")
|
|
131
|
+
command.add_argument("--isolation", choices=("folder", "worktree"), help="local project's working directory")
|
|
132
|
+
command.add_argument("--share-mcp-tool", dest="mcp_tools", action="append", choices=("project_info", "project_diff"),
|
|
133
|
+
help="grant a read-only project tool to this ACP session (repeatable)")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def run_sets(args) -> list[str]:
|
|
137
|
+
"""run_flags as experiment overrides (agent.runtime, the worker's options)."""
|
|
138
|
+
return physical_sets(args) + think_sets(args) + workspace_sets(args)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _physical_arguments(command):
|
|
142
|
+
command.add_argument("--physical", choices=_levels("physical"), help="the physical-input level for this run in place of "
|
|
143
|
+
"the default of your settings (their rules still hold)")
|
|
144
|
+
command.add_argument("--allow-app", action="append", default=[], metavar="APP",
|
|
145
|
+
help="allow physical input in APP for this run (its process name; repeatable)")
|
|
146
|
+
command.add_argument("--deny-app", action="append", default=[], metavar="APP",
|
|
147
|
+
help="never physical input in APP for this run (repeatable)")
|
|
148
|
+
command.add_argument("--ask-app", action="append", default=[], metavar="APP",
|
|
149
|
+
help="ask before each step of physical input in APP for this run (repeatable)")
|
|
150
|
+
command.add_argument("--window-details", choices=_levels("privacy"),
|
|
151
|
+
help="what the model learns of your windows the agent does not own, for this run in place "
|
|
152
|
+
"of the default of your settings (their rules still hold): none, presence (only that "
|
|
153
|
+
"another window is in front), apps, titles")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _think_arguments(command):
|
|
157
|
+
from .settings import SCHEMA
|
|
158
|
+
|
|
159
|
+
command.add_argument("--think", choices=[level for level in SCHEMA["model"]["think_while_acting"][2]
|
|
160
|
+
if level != "default"],
|
|
161
|
+
help="allow one speculative thought during a long program (on) or disable it (off). "
|
|
162
|
+
"Legacy on_events and periodic act like on.")
|
|
163
|
+
command.add_argument("--think-interval", type=float, metavar="SECONDS",
|
|
164
|
+
help="accepted for older configurations. Decision scheduling is event-driven.")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def think_sets(args) -> list[str]:
|
|
168
|
+
"""harness run and chat --think, --think-interval as experiment overrides."""
|
|
169
|
+
level, interval = getattr(args, "think", None), getattr(args, "think_interval", None)
|
|
170
|
+
if interval is not None and interval <= 0:
|
|
171
|
+
raise ValueError("--think-interval is a number of seconds above 0")
|
|
172
|
+
return [*([f"agent.runtime.think_while_acting={json.dumps(level)}"] if level else []),
|
|
173
|
+
*([f"agent.runtime.think_interval={interval:g}"] if interval is not None else [])]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _workspace_argument(command):
|
|
177
|
+
command.add_argument("--workspace", metavar="KIND",
|
|
178
|
+
help="where the agent works: none (no environment: the conversation, the model and "
|
|
179
|
+
"the connected tools only), project (one folder: give it with --folder), browser (a "
|
|
180
|
+
"background browser), desktop (your screen), apps (your applications in the "
|
|
181
|
+
"background: Windows, macOS, Linux on X11) or display (a display of its own that you "
|
|
182
|
+
"never see: a display server on Linux, a virtual machine on Windows and macOS; the "
|
|
183
|
+
"settings computer.display_backend and vm_* say which). Without it (and without "
|
|
184
|
+
"--folder) the setting session.environment decides: ask (the default) asks in an "
|
|
185
|
+
"interactive terminal and is an error elsewhere, last takes the last choice, a kind "
|
|
186
|
+
"takes that kind")
|
|
187
|
+
if command.prog.split()[-1] == "run":
|
|
188
|
+
command.add_argument("--vm-image", metavar="IMAGE",
|
|
189
|
+
help="with --workspace display: each workspace is a virtual machine started from IMAGE "
|
|
190
|
+
"(a disk image or a VMware or Tart folder) in place of the setting computer.vm_image")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def workspace_sets(args) -> list[str]:
|
|
194
|
+
"""harness run --workspace (and --vm-image) as experiment overrides (the computer
|
|
195
|
+
worker's options)."""
|
|
196
|
+
kind = getattr(args, "workspace", None)
|
|
197
|
+
if args.command != "run" or isinstance(getattr(args, "config", None), str):
|
|
198
|
+
return []
|
|
199
|
+
if kind == "browser":
|
|
200
|
+
raise ValueError("--workspace browser is for a task in words; an experiment in a browser runs the "
|
|
201
|
+
"browser bench")
|
|
202
|
+
sets = [f"worker.workspace={json.dumps(kind)}"] if kind else []
|
|
203
|
+
image = getattr(args, "vm_image", None)
|
|
204
|
+
if image:
|
|
205
|
+
if kind != "display":
|
|
206
|
+
raise ValueError("--vm-image goes with --workspace display")
|
|
207
|
+
sets += ['worker.display_backend="vm"', f"worker.vm.vm_image={json.dumps(str(Path(image).resolve()))}"]
|
|
208
|
+
return sets
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def physical_sets(args) -> list[str]:
|
|
212
|
+
"""The run's physical-input flags as an experiment override (agent.runtime.physical)."""
|
|
213
|
+
policy = _run_rules(getattr(args, "physical", None), getattr(args, "allow_app", ()), getattr(args, "deny_app", ()),
|
|
214
|
+
getattr(args, "ask_app", ()))
|
|
215
|
+
seen = getattr(args, "window_details", None)
|
|
216
|
+
if not policy and not seen:
|
|
217
|
+
return []
|
|
218
|
+
from .config import toml_value
|
|
219
|
+
|
|
220
|
+
return [*([f"agent.runtime.physical={toml_value(policy)}"] if policy else []),
|
|
221
|
+
*([f"agent.runtime.privacy={toml_value({'level': seen})}"] if seen else [])]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def package_commands() -> dict:
|
|
225
|
+
"""{name: ("module:function", package, summary)} of the commands the installed packages
|
|
226
|
+
bring. The function takes the command's arguments (a list) and returns the exit status."""
|
|
227
|
+
from .paths import packages
|
|
228
|
+
|
|
229
|
+
found = {}
|
|
230
|
+
for package in packages():
|
|
231
|
+
for name in package.provides.get("commands", ()):
|
|
232
|
+
found.setdefault(name, (package.commands[name], package.name, package.summary))
|
|
233
|
+
return found
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# Commands the core installs a package for on first use: {name: package}.
|
|
237
|
+
FIRST_USE = {"agent": "agent"}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _package_command(name: str, arguments) -> int:
|
|
241
|
+
"""An installed package's command, or (FIRST_USE) its package installed first. Its own
|
|
242
|
+
parser reads the arguments."""
|
|
243
|
+
from .packages import Packages, activate
|
|
244
|
+
|
|
245
|
+
packages = None
|
|
246
|
+
if name not in package_commands():
|
|
247
|
+
packages = Packages()
|
|
248
|
+
packages.ensure("commands", name, log=_note)
|
|
249
|
+
activate(packages)
|
|
250
|
+
module, _, function = package_commands()[name][0].partition(":")
|
|
251
|
+
return int(getattr(importlib.import_module(module), function)(list(arguments)) or 0)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _experiment(arguments) -> int:
|
|
255
|
+
"""harness run EXPERIMENT ...: the eval package's (installed first when it is not)."""
|
|
256
|
+
from .extensions import require
|
|
257
|
+
from .packages import activate
|
|
258
|
+
|
|
259
|
+
activate()
|
|
260
|
+
return int(require("run_experiment", "commands", "program")(list(arguments)) or 0)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def parser(packages: bool = True):
|
|
264
|
+
root = argparse.ArgumentParser(prog="harness", description="Automatic Control for anything that acts.",
|
|
265
|
+
epilog="harness with no command: the terminal chat with the agent on this computer "
|
|
266
|
+
"(/help lists its commands: sessions, the session host, settings, model, "
|
|
267
|
+
"packages, library)")
|
|
268
|
+
root.add_argument("--version", action="version", version=f"harness {__version__}")
|
|
269
|
+
run_flags(root)
|
|
270
|
+
_coding_arguments(root)
|
|
271
|
+
root.add_argument("--managed-workspace", action="store_true", help="use an isolated managed workspace (supported Linux hosts)")
|
|
272
|
+
commands = root.add_subparsers(dest="command")
|
|
273
|
+
run = commands.add_parser("run", help="Do a task on this computer and end (harness run \"rename the photos by "
|
|
274
|
+
"date\"); harness run rpc: drive the agent from another program",
|
|
275
|
+
epilog="harness run rpc: JSON lines on stdin ({\"type\": \"prompt\", \"text\"}, then "
|
|
276
|
+
"message, pause, continue, approve, reject, end) and the records of its trace "
|
|
277
|
+
"as JSON lines on stdout.")
|
|
278
|
+
run.add_argument("task", help="a task, or rpc for the JSON-lines protocol")
|
|
279
|
+
run.add_argument("--model", help="an enabled model from ~/.harness/models.json (ID or provider/model)")
|
|
280
|
+
run.add_argument("--effort", help="the selected model's reasoning effort ID")
|
|
281
|
+
output_mode = run.add_mutually_exclusive_group()
|
|
282
|
+
output_mode.add_argument("-p", "--print", action="store_true", help="print only the agent's answer")
|
|
283
|
+
output_mode.add_argument("--json", action="store_true", help="print every record of its trace as a JSON line")
|
|
284
|
+
run.add_argument("--learn", nargs="?", const=True, type=_minutes, metavar="MINUTES",
|
|
285
|
+
help="learn this environment for the task instead of doing it: read, try the controls, write "
|
|
286
|
+
"skills with tests, practise, for MINUTES of live time (default: the settings' "
|
|
287
|
+
"learning.active_minutes); what it learns goes into the library")
|
|
288
|
+
run.add_argument("--library", type=Path, help="explicit reusable learning library; frozen unless --learn-while-working")
|
|
289
|
+
run.add_argument("--learn-while-working", action="store_true", help="learn during the task into --library")
|
|
290
|
+
run_flags(run)
|
|
291
|
+
_coding_arguments(run)
|
|
292
|
+
run.add_argument("--managed-workspace", action="store_true", help="use an isolated managed workspace (supported Linux hosts)")
|
|
293
|
+
_session_commands(commands.add_parser("sessions", help="Manage the session host's coding sessions"))
|
|
294
|
+
install = commands.add_parser("install", help="Install packages (and what they depend on), or update them; and "
|
|
295
|
+
"the services and benches they provide",
|
|
296
|
+
epilog="harness install browser; harness install computer@^0.5; harness install "
|
|
297
|
+
"git:github.com/x/y@main#packages/z; harness install ./my-package --link; "
|
|
298
|
+
"harness install --update (all); harness install sam3 (a service). With no "
|
|
299
|
+
"names in a folder with harness.toml: the project's packages, from its "
|
|
300
|
+
"harness.lock.")
|
|
301
|
+
install.add_argument("names", nargs="*", help="packages (a registry name with an optional range, a git or archive "
|
|
302
|
+
"URL, a folder), services and benches")
|
|
303
|
+
_package_arguments(install)
|
|
304
|
+
install.add_argument("--update", action="store_true", help="update the named packages (default: all) to the "
|
|
305
|
+
"newest version in their range")
|
|
306
|
+
install.add_argument("--yes", "-y", action="store_true", help="install packages from outside the registry "
|
|
307
|
+
"without asking (they run code on this computer)")
|
|
308
|
+
install.add_argument("--link", action="store_true", help="a folder: use it where it is instead of a copy (a "
|
|
309
|
+
"package under development)")
|
|
310
|
+
install.add_argument("--deploy", help="services: the deploy that places them (default $HARNESS_DEPLOY)")
|
|
311
|
+
listed = commands.add_parser("list", help="The installed packages; --available: the registry's (QUERY "
|
|
312
|
+
"searches them); one package by its name: what it provides")
|
|
313
|
+
listed.add_argument("query", nargs="?", default="")
|
|
314
|
+
listed.add_argument("--available", action="store_true", help="the packages the registry has")
|
|
315
|
+
_package_arguments(listed)
|
|
316
|
+
remove = commands.add_parser("remove", help="Remove installed packages")
|
|
317
|
+
remove.add_argument("names", nargs="+")
|
|
318
|
+
_package_arguments(remove)
|
|
319
|
+
library = commands.add_parser("library", help="What the agent remembers (runtime/task/context.py): the libraries, a "
|
|
320
|
+
"library's entries with their evidence, tests and uses, and a run's "
|
|
321
|
+
"memory of what it saw and where beside its library's entries")
|
|
322
|
+
library.add_argument("what", nargs="?", choices=["ls", "show"], default="ls",
|
|
323
|
+
help="ls (default): the libraries under $HARNESS_HOME/libraries; show LIBRARY or RUN")
|
|
324
|
+
library.add_argument("path", nargs="?", help="show: a library's directory or its name under "
|
|
325
|
+
"$HARNESS_HOME/libraries, or a run's directory")
|
|
326
|
+
library.add_argument("--json", action="store_true", help="JSON")
|
|
327
|
+
replay = commands.add_parser("replay", help="Replay a run in the terminal")
|
|
328
|
+
replay.add_argument("run", help="an episode directory, a conversation (its name under conversations/), or a "
|
|
329
|
+
"session (SESSION or SESSION/AGENT)")
|
|
330
|
+
replay.add_argument("--json", action="store_true", help="every record of its trace as a JSON line")
|
|
331
|
+
doctor = commands.add_parser("doctor", help="Whether this computer can run the agent: Python, the model and its "
|
|
332
|
+
"key, the packages; or services, or an experiment (the eval "
|
|
333
|
+
"package's: harness doctor EXPERIMENT --help)",
|
|
334
|
+
epilog="Exit status: 0 nothing missing, 1 something missing, 2 a usage error.")
|
|
335
|
+
doctor.add_argument("names", nargs="*", help="services (default: the core), or an experiment")
|
|
336
|
+
doctor.add_argument("--deploy", help="the deploy that places the services (default $HARNESS_DEPLOY)")
|
|
337
|
+
doctor.add_argument("--json", action="store_true")
|
|
338
|
+
# The installed packages' commands, after the core's (their own parsers read their arguments).
|
|
339
|
+
for name, (_, package, summary) in (package_commands().items() if packages else ()):
|
|
340
|
+
if name in commands.choices:
|
|
341
|
+
continue
|
|
342
|
+
command = commands.add_parser(name, help=f"{summary} (package {package})", add_help=False)
|
|
343
|
+
command.add_argument("arguments", nargs=argparse.REMAINDER)
|
|
344
|
+
return root
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def core_commands() -> set:
|
|
348
|
+
"""The commands of the core itself (the others are packages')."""
|
|
349
|
+
commands = next(action for action in parser(packages=False)._actions
|
|
350
|
+
if isinstance(action, argparse._SubParsersAction))
|
|
351
|
+
return set(commands.choices) - set(FIRST_USE)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _services(args):
|
|
355
|
+
"""harness doctor of services (and without names or a deploy file, of the core): what the
|
|
356
|
+
package that places services checks (local-models), else the core's own checks."""
|
|
357
|
+
from .extensions import first
|
|
358
|
+
from .packages import Packages
|
|
359
|
+
from .services.placement import NoDeploy, load_deploy
|
|
360
|
+
|
|
361
|
+
deploy = load_deploy(args.deploy)
|
|
362
|
+
doctor = first("doctor")
|
|
363
|
+
core = isinstance(deploy, NoDeploy) or (deploy.automatic and not args.names)
|
|
364
|
+
if doctor is not None and not isinstance(deploy, NoDeploy):
|
|
365
|
+
report = doctor(deploy, names=args.names or None, core=core)
|
|
366
|
+
elif args.names:
|
|
367
|
+
return _usage("doctor", "checking services needs the local-models package (harness install local-models)")
|
|
368
|
+
else:
|
|
369
|
+
report = _core_report()
|
|
370
|
+
report["packages"] = Packages().installed()
|
|
371
|
+
if args.json:
|
|
372
|
+
output(report)
|
|
373
|
+
else:
|
|
374
|
+
print(f"deploy {report['deploy']}: {'ready' if report['ok'] else 'NOT ready'}")
|
|
375
|
+
if report.get("gpus") is not None:
|
|
376
|
+
print(table(report["gpus"], ["index", "name", "used_gb", "total_gb"]))
|
|
377
|
+
if report.get("installed"):
|
|
378
|
+
print(table(report["installed"], ["name", "what", "installed", "environment"]))
|
|
379
|
+
if report.get("to_install"):
|
|
380
|
+
print(f"the agent would still install: {', '.join(report['to_install'])} (on its first run, "
|
|
381
|
+
f"or now: harness install {' '.join(report['to_install'])})")
|
|
382
|
+
for problem in report["problems"]:
|
|
383
|
+
print(f" problem: {problem}")
|
|
384
|
+
for note in report["notes"]:
|
|
385
|
+
print(f" note: {note}")
|
|
386
|
+
_print_packages(report["packages"])
|
|
387
|
+
return 0 if report["ok"] else 1
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _core_report() -> dict:
|
|
391
|
+
"""harness doctor with nothing named: the harness itself and whether a model is set up."""
|
|
392
|
+
from . import providers
|
|
393
|
+
from .paths import data
|
|
394
|
+
|
|
395
|
+
problems, notes = [], []
|
|
396
|
+
if sys.version_info < (3, 11):
|
|
397
|
+
problems.append(f"Python {sys.version.split()[0]}: 3.11 or newer is needed")
|
|
398
|
+
model = providers.ready(data())
|
|
399
|
+
if not model["ready"]:
|
|
400
|
+
problems.append(f"no model set up ({model['provider']}: {model['key_env']} is not set): run harness once "
|
|
401
|
+
"in a terminal, or export the key")
|
|
402
|
+
notes.append("No package places services here: hosted models only (harness install local-models for "
|
|
403
|
+
"models on this machine's GPUs).")
|
|
404
|
+
return {"schema_version": 1, "deploy": "none", "ok": not problems, "problems": problems, "notes": notes,
|
|
405
|
+
"gpus": None, "services": [], "installed": [], "to_install": []}
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _print_packages(rows, columns="installed"):
|
|
409
|
+
"""Packages as harness list and doctor print them (describe()), installed or "available"."""
|
|
410
|
+
from .packages import COLUMNS, rows as package_rows
|
|
411
|
+
|
|
412
|
+
if not rows and columns == "installed":
|
|
413
|
+
print("packages: none installed (harness list --available lists the registry's; a task installs what it "
|
|
414
|
+
"needs)")
|
|
415
|
+
return
|
|
416
|
+
print(table(package_rows(rows, columns, 70), list(COLUMNS[columns])))
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _print_package(found, file=None):
|
|
420
|
+
"""One package's lines (describe()): harness list NAME, and what harness install asks to trust."""
|
|
421
|
+
from .packages import describe
|
|
422
|
+
|
|
423
|
+
first, *rest = describe(found)["lines"]
|
|
424
|
+
print("\n".join([first, *(f" {line}" for line in rest)]), file=file or sys.stdout)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _list(args):
|
|
428
|
+
"""harness list [QUERY] [--available]: the installed packages (QUERY filters them), the
|
|
429
|
+
registry's (--available; QUERY searches them), one package's description when QUERY is
|
|
430
|
+
its exact name."""
|
|
431
|
+
from .packages import Packages
|
|
432
|
+
|
|
433
|
+
packages = Packages()
|
|
434
|
+
rows = packages.search(args.query) if args.available else [
|
|
435
|
+
row for row in packages.installed() if not args.query or args.query.lower() in str(row.get("name")).lower()]
|
|
436
|
+
exact = [row for row in rows if row.get("name") == args.query]
|
|
437
|
+
if args.query and len(exact) == 1:
|
|
438
|
+
found = packages.info(args.query)
|
|
439
|
+
output(found) if args.json else _print_package(found)
|
|
440
|
+
return 0
|
|
441
|
+
if args.json:
|
|
442
|
+
output(rows)
|
|
443
|
+
elif rows or not args.available:
|
|
444
|
+
_print_packages(rows, "available" if args.available else "installed")
|
|
445
|
+
else:
|
|
446
|
+
print(f"no package matches {args.query!r}")
|
|
447
|
+
return 0 if args.available or not any("problem" in row for row in rows) else 1
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _remove(args):
|
|
451
|
+
from .packages import Packages
|
|
452
|
+
|
|
453
|
+
removed = Packages().remove(args.names, project=args.project, log=_note)
|
|
454
|
+
output(removed) if args.json else print(f"removed {', '.join(removed)}")
|
|
455
|
+
return 0
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _install(args):
|
|
459
|
+
"""harness install: packages, then the services and benches among the names; --update:
|
|
460
|
+
the named packages (default all) to the newest version in their range."""
|
|
461
|
+
from .bench import bench_specs
|
|
462
|
+
from .packages import Packages, activate, provision
|
|
463
|
+
from .services.placement import load_deploy
|
|
464
|
+
|
|
465
|
+
packages = activate(Packages())
|
|
466
|
+
if args.update:
|
|
467
|
+
result = packages.update(args.names, project=args.project, log=_note)
|
|
468
|
+
output(result) if args.json else [print(f"{row['name']} {row['version']}") for row in result["installed"]]
|
|
469
|
+
return 0
|
|
470
|
+
deploy = load_deploy(args.deploy)
|
|
471
|
+
known = set(deploy.services) | set(bench_specs())
|
|
472
|
+
specs = [name for name in args.names if name not in known]
|
|
473
|
+
result = {"installed": [], "problems": []}
|
|
474
|
+
if specs or (not args.names and args.project) or (not args.names and packages.project() is not None):
|
|
475
|
+
def consent(found):
|
|
476
|
+
for package in found:
|
|
477
|
+
_print_package(package, file=sys.stderr)
|
|
478
|
+
if args.yes:
|
|
479
|
+
return True
|
|
480
|
+
if not sys.stdin.isatty():
|
|
481
|
+
print("these packages are not from the registry and run code on this computer: "
|
|
482
|
+
"harness install --yes to install them", file=sys.stderr)
|
|
483
|
+
return False
|
|
484
|
+
return input("They are not from the registry and run code on this computer. Install? [y/N] ") \
|
|
485
|
+
.strip().lower() in ("y", "yes")
|
|
486
|
+
|
|
487
|
+
project = args.project or (not args.names and packages.project() is not None)
|
|
488
|
+
result = packages.install(specs, project=project, consent=consent, link=args.link, log=_note)
|
|
489
|
+
if result.get("needs_trust"):
|
|
490
|
+
return 1
|
|
491
|
+
elif not args.names:
|
|
492
|
+
return _usage("install", "name packages, services or benches (or run it where harness.toml names the "
|
|
493
|
+
"project's packages)")
|
|
494
|
+
# A name a package just brought (a bench) is installed as one now too: its environment.
|
|
495
|
+
known = set(deploy.services) | set(bench_specs())
|
|
496
|
+
provisioned = [name for name in args.names if name in known]
|
|
497
|
+
benches = [name for name in provisioned if name in bench_specs()]
|
|
498
|
+
services = [name for name in provisioned if name not in benches]
|
|
499
|
+
rows = [provision.install_bench_environment(deploy, name, log=_note) for name in benches]
|
|
500
|
+
if services:
|
|
501
|
+
# Services' environments and weights: the package that places services installs them.
|
|
502
|
+
from .extensions import require
|
|
503
|
+
|
|
504
|
+
rows += require("install_services", "commands", "fetch")(load_deploy(args.deploy), services, log=_note)
|
|
505
|
+
if args.json:
|
|
506
|
+
output({**result, "provisioned": rows})
|
|
507
|
+
else:
|
|
508
|
+
for row in result["installed"]:
|
|
509
|
+
print(f"{row['name']} {row['version']} ({row['source']})")
|
|
510
|
+
for problem in result["problems"]:
|
|
511
|
+
print(f" not installed: {problem}")
|
|
512
|
+
if rows:
|
|
513
|
+
print(table(rows, ["name", "what", "installed", "environment"]))
|
|
514
|
+
return 0
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _usage(command, message):
|
|
518
|
+
print(f"harness {command}: {message}", file=sys.stderr)
|
|
519
|
+
return 2
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _doctor(args, words) -> int:
|
|
523
|
+
"""harness doctor: services (or with nothing named, the core); an experiment (a name of
|
|
524
|
+
configs/experiments/ or a .toml file) or the experiment options are the eval package's,
|
|
525
|
+
which reads `words` (what followed doctor) itself."""
|
|
526
|
+
from .paths import find
|
|
527
|
+
from .services.registry import load_services
|
|
528
|
+
|
|
529
|
+
services = set(load_services())
|
|
530
|
+
experiments = [name for name in args.names if name.endswith(".toml") or "/" in name or "\\" in name
|
|
531
|
+
or bool(find(f"configs/experiments/{name}.toml"))]
|
|
532
|
+
both = [name for name in experiments if name in services]
|
|
533
|
+
if both:
|
|
534
|
+
return _usage("doctor", f"{both[0]!r} is both a service and an experiment: for the experiment give its "
|
|
535
|
+
f"file (configs/experiments/{both[0]}.toml)")
|
|
536
|
+
options = [word for word in words if word.startswith("--") and word.split("=")[0] not in ("--deploy", "--json")]
|
|
537
|
+
if args.names and all(name in services for name in args.names) and options:
|
|
538
|
+
return _usage("doctor", f"{', '.join(options)} need an experiment: harness doctor EXPERIMENT {options[0]} ...")
|
|
539
|
+
if experiments or options:
|
|
540
|
+
from .extensions import require
|
|
541
|
+
|
|
542
|
+
return int(require("doctor_experiment", "commands", "program")(list(words)) or 0)
|
|
543
|
+
unknown = [name for name in args.names if name not in services]
|
|
544
|
+
if unknown:
|
|
545
|
+
return _usage("doctor", f"no service or experiment called {unknown[0]!r}")
|
|
546
|
+
return _services(args)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _note(message):
|
|
550
|
+
print(message, file=sys.stderr, flush=True)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _ready_model(interactive: bool) -> None:
|
|
554
|
+
"""A model and its key, asked for on the first run in a terminal (providers.setup)."""
|
|
555
|
+
from . import model_list, providers
|
|
556
|
+
from .paths import data
|
|
557
|
+
|
|
558
|
+
if model_list.select(data()) is not None or providers.ready(data())["ready"]:
|
|
559
|
+
return
|
|
560
|
+
if not (interactive and sys.stdin.isatty()):
|
|
561
|
+
raise UsageError("no model is set up yet: run harness in a terminal once (it asks for the model and key), "
|
|
562
|
+
"or export the provider's key")
|
|
563
|
+
providers.setup(data())
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _run_options(args) -> dict:
|
|
567
|
+
"""A task's own runtime from its flags (--physical, --allow-app, --deny-app, --ask-app,
|
|
568
|
+
--window-details, --think, --think-interval): app.RUN_KEYS."""
|
|
569
|
+
options = {"managed_workspace": True} if getattr(args, "managed_workspace", False) else {}
|
|
570
|
+
policy = _run_rules(getattr(args, "physical", None), getattr(args, "allow_app", ()), getattr(args, "deny_app", ()),
|
|
571
|
+
getattr(args, "ask_app", ()))
|
|
572
|
+
if policy:
|
|
573
|
+
options["physical"] = policy
|
|
574
|
+
if getattr(args, "window_details", None):
|
|
575
|
+
options["privacy"] = {"level": args.window_details}
|
|
576
|
+
if getattr(args, "think", None):
|
|
577
|
+
options["think_while_acting"] = args.think
|
|
578
|
+
if getattr(args, "think_interval", None) is not None:
|
|
579
|
+
if args.think_interval <= 0:
|
|
580
|
+
raise UsageError("--think-interval is a number of seconds above 0")
|
|
581
|
+
options["think_interval"] = args.think_interval
|
|
582
|
+
if getattr(args, "learn", None) is not None:
|
|
583
|
+
options["learn"] = args.learn
|
|
584
|
+
if getattr(args, "agents", False):
|
|
585
|
+
options["agents"] = True
|
|
586
|
+
return options
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def _minutes(value: str) -> float:
|
|
590
|
+
"""--learn's MINUTES (a number; the task in words goes before --learn)."""
|
|
591
|
+
try:
|
|
592
|
+
return float(value)
|
|
593
|
+
except ValueError:
|
|
594
|
+
raise argparse.ArgumentTypeError(f"MINUTES is a number, not {value!r}: harness run \"for what\" --learn "
|
|
595
|
+
"[MINUTES]") from None
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _task(text: str, workspace=None, confirmation=None, runtime=None, files=(), log=None, **coding):
|
|
599
|
+
"""The session host (started when none runs) and a conversation of the app's agent in it
|
|
600
|
+
(Host.task); without a workspace named, the host takes the one the task asks for.
|
|
601
|
+
`log`: where starting the host is said (default stderr)."""
|
|
602
|
+
from .host import Host
|
|
603
|
+
|
|
604
|
+
host = Host.connect(log=log or _note)
|
|
605
|
+
return host, host.task(text, workspace or "auto", confirmation, runtime=runtime, files=files, **coding)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def _coding(args):
|
|
609
|
+
agent = getattr(args, "agent", None)
|
|
610
|
+
folder = getattr(args, "folder", None)
|
|
611
|
+
if folder:
|
|
612
|
+
folder = folder.expanduser().resolve()
|
|
613
|
+
if not folder and agent and agent.startswith(("acp:", "terminal:")):
|
|
614
|
+
folder = Path.cwd()
|
|
615
|
+
return {key: value for key, value in {"agent": agent, "folder": folder,
|
|
616
|
+
"isolation": getattr(args, "isolation", None),
|
|
617
|
+
"mcp_tools": getattr(args, "mcp_tools", None)}.items() if value is not None}
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _starter(args):
|
|
621
|
+
"""The terminal chat's start(text, files, log, learn): a conversation of the app's agent with
|
|
622
|
+
the options harness was given (--workspace, --physical, ...); `learn` (/learn): one that learns
|
|
623
|
+
its environment for that many minutes. It keeps the last it started."""
|
|
624
|
+
def start(text, files=(), log=None, learn=None, model_entry=None, reasoning_effort=None, workspace=None,
|
|
625
|
+
folder=None, agents=None):
|
|
626
|
+
runtime = {**_run_options(args), **({"learn": learn} if learn is not None else {}),
|
|
627
|
+
**({"agents": True} if agents else {})}
|
|
628
|
+
coding = _coding(args)
|
|
629
|
+
workspace = workspace or getattr(args, "workspace", None)
|
|
630
|
+
if folder and not coding.get("agent"):
|
|
631
|
+
coding["folder"] = Path(folder)
|
|
632
|
+
library = getattr(args, "library", None)
|
|
633
|
+
if getattr(args, "learn_while_working", False) and library is None:
|
|
634
|
+
raise UsageError("--learn-while-working requires --library PATH")
|
|
635
|
+
if library is not None:
|
|
636
|
+
coding["library"] = {"path": str(library.resolve()),
|
|
637
|
+
"learn": "on" if getattr(args, "learn_while_working", False) else "off",
|
|
638
|
+
"reflect": bool(getattr(args, "learn_while_working", False))}
|
|
639
|
+
if not coding.get("agent"):
|
|
640
|
+
from .model_list import select
|
|
641
|
+
from .paths import data
|
|
642
|
+
|
|
643
|
+
selected = select(data(), model_entry, native=bool(runtime or workspace or coding.get("folder")))
|
|
644
|
+
if selected is None:
|
|
645
|
+
raise ValueError("add an enabled model in Settings or ~/.harness/models.json")
|
|
646
|
+
model_entry = selected["id"]
|
|
647
|
+
if selected["provider"].startswith(("acp:", "terminal:")):
|
|
648
|
+
coding["folder"] = Path.cwd()
|
|
649
|
+
start.host, start.conversation = _task(text, workspace,
|
|
650
|
+
runtime=runtime, files=files, log=log, **coding,
|
|
651
|
+
model_entry=model_entry, reasoning_effort=reasoning_effort)
|
|
652
|
+
return start.host, start.conversation
|
|
653
|
+
|
|
654
|
+
start.host = start.conversation = None
|
|
655
|
+
# The command line already says where it works: the chat does not ask at its opening.
|
|
656
|
+
start.named = bool(getattr(args, "workspace", None) or getattr(args, "folder", None)
|
|
657
|
+
or getattr(args, "agent", None))
|
|
658
|
+
return start
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def _turn_over(record, answered: bool) -> bool:
|
|
662
|
+
status = record.get("status") if record.get("event") == "state" else None
|
|
663
|
+
return status in ENDED or (status == "IDLE" and (answered or record.get("reason") == "budget"))
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _choose_first_use(choice):
|
|
667
|
+
"""The interactive run command: require an explicit numbered answer."""
|
|
668
|
+
from .host import Host
|
|
669
|
+
|
|
670
|
+
print(choice["title"], file=sys.stderr)
|
|
671
|
+
for index, option in enumerate(choice["options"], 1):
|
|
672
|
+
print(f" {index}. {option['label']}", file=sys.stderr)
|
|
673
|
+
while True:
|
|
674
|
+
try:
|
|
675
|
+
answer = input("Choose a number (no default; q cancels): ").strip()
|
|
676
|
+
except EOFError:
|
|
677
|
+
raise UsageError("choice cancelled; task not started") from None
|
|
678
|
+
if answer.lower() == "q":
|
|
679
|
+
raise UsageError("choice cancelled; task not started")
|
|
680
|
+
if answer.isdigit() and 1 <= int(answer) <= len(choice["options"]):
|
|
681
|
+
value = choice["options"][int(answer) - 1]["value"]
|
|
682
|
+
Host.connect().post("/api/app/settings", {choice["section"]: {choice["key"]: value}})
|
|
683
|
+
return
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def _choose_environment(choice):
|
|
687
|
+
"""The interactive run command: where this conversation works. Enter takes the
|
|
688
|
+
highlighted last choice; with none yet an explicit number is required. (kind, folder)."""
|
|
689
|
+
options = choice["options"]
|
|
690
|
+
values = [row["value"] for row in options]
|
|
691
|
+
default = values.index(choice["selected"]) + 1 if choice.get("selected") in values else None
|
|
692
|
+
print(choice["title"], file=sys.stderr)
|
|
693
|
+
for index, option in enumerate(options, 1):
|
|
694
|
+
mark = "*" if index == default else " "
|
|
695
|
+
print(f" {mark}{index}. {option['label']}", file=sys.stderr)
|
|
696
|
+
ask = f"Choose a number ({f'Enter: {default}' if default else 'no default'}; q cancels): "
|
|
697
|
+
while True:
|
|
698
|
+
try:
|
|
699
|
+
answer = input(ask).strip()
|
|
700
|
+
except EOFError:
|
|
701
|
+
raise UsageError("choice cancelled; task not started") from None
|
|
702
|
+
if answer.lower() == "q":
|
|
703
|
+
raise UsageError("choice cancelled; task not started")
|
|
704
|
+
if not answer and default:
|
|
705
|
+
answer = str(default)
|
|
706
|
+
if answer.isdigit() and 1 <= int(answer) <= len(options):
|
|
707
|
+
row = options[int(answer) - 1]
|
|
708
|
+
break
|
|
709
|
+
if not row.get("folder"):
|
|
710
|
+
return row["value"], None
|
|
711
|
+
here = Path.cwd()
|
|
712
|
+
inside = any((parent / ".git").exists() for parent in (here, *here.parents))
|
|
713
|
+
suggested = str(here if inside or not choice.get("folder") else choice["folder"])
|
|
714
|
+
try:
|
|
715
|
+
folder = input(f"Folder to work in [{suggested}]: ").strip() or suggested
|
|
716
|
+
except EOFError:
|
|
717
|
+
raise UsageError("choice cancelled; task not started") from None
|
|
718
|
+
return row["value"], str(Path(folder).expanduser())
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _run_task(args):
|
|
722
|
+
"""harness run "task": the agent on this computer does it and the command ends when it has
|
|
723
|
+
answered; -p prints only the answer, --json every record."""
|
|
724
|
+
from .terminal import Printer
|
|
725
|
+
from .transcript import answer_of
|
|
726
|
+
|
|
727
|
+
if args.model and _coding(args).get("agent"):
|
|
728
|
+
raise UsageError("--model selects its own provider; use either --model or --agent")
|
|
729
|
+
if not _coding(args).get("agent") and not args.model:
|
|
730
|
+
_ready_model(interactive=True)
|
|
731
|
+
from .settings import ChoiceRequired
|
|
732
|
+
|
|
733
|
+
start = _starter(args)
|
|
734
|
+
place = {}
|
|
735
|
+
while True:
|
|
736
|
+
try:
|
|
737
|
+
host, conversation = start(args.task, learn=getattr(args, "learn", None),
|
|
738
|
+
model_entry=args.model, reasoning_effort=args.effort, **place)
|
|
739
|
+
break
|
|
740
|
+
except ChoiceRequired as error:
|
|
741
|
+
# Nobody to ask: the error names the flag; nothing is chosen for the user.
|
|
742
|
+
if args.json or not (sys.stdin.isatty() and sys.stdout.isatty()):
|
|
743
|
+
raise
|
|
744
|
+
if error.choice.get("per_conversation"):
|
|
745
|
+
place = dict(zip(("workspace", "folder"), _choose_environment(error.choice)))
|
|
746
|
+
else:
|
|
747
|
+
_choose_first_use(error.choice)
|
|
748
|
+
printer, answer, failed = Printer(), None, False
|
|
749
|
+
asking = threading.Lock()
|
|
750
|
+
|
|
751
|
+
def sub_agent(agent, what, request_id):
|
|
752
|
+
with asking:
|
|
753
|
+
if watch.is_set():
|
|
754
|
+
return
|
|
755
|
+
accept, reason = _answer(what)
|
|
756
|
+
try:
|
|
757
|
+
host.approve(conversation.run, accept, reason, agent, request_id=request_id)
|
|
758
|
+
except (ValueError, OSError, RuntimeError) as error:
|
|
759
|
+
print(f"harness: {error}", file=sys.stderr, flush=True)
|
|
760
|
+
|
|
761
|
+
watch = _watch_sub_agents(host, conversation, sub_agent)
|
|
762
|
+
try:
|
|
763
|
+
for record in conversation.records():
|
|
764
|
+
if args.json:
|
|
765
|
+
print(json.dumps(record, ensure_ascii=False), flush=True)
|
|
766
|
+
elif not args.print:
|
|
767
|
+
for line in printer.lines(record):
|
|
768
|
+
print(line, flush=True)
|
|
769
|
+
if args.learn is not None and record.get("event") in ("library", "cell"):
|
|
770
|
+
# Where learning the environment stands (runtime/learning/active.py progress()).
|
|
771
|
+
from harness.runtime.learning.active import progress_line
|
|
772
|
+
|
|
773
|
+
now = host.learning(conversation.run)
|
|
774
|
+
if now.get("active"):
|
|
775
|
+
print(progress_line(now), flush=True)
|
|
776
|
+
elif record.get("event") == "error":
|
|
777
|
+
# -p prints only the answer; why there is none still goes to stderr.
|
|
778
|
+
print(f"harness: {record.get('message')}", file=sys.stderr, flush=True)
|
|
779
|
+
request = record.get("request") if record.get("event") == "state" and (
|
|
780
|
+
record.get("status") == "WAITING_FOR_CONFIRMATION") else None
|
|
781
|
+
if request is not None:
|
|
782
|
+
with asking:
|
|
783
|
+
accept, reason = _answer(_waits_for(request))
|
|
784
|
+
try:
|
|
785
|
+
conversation.confirm(accept, reason, request_id=request["id"])
|
|
786
|
+
except (ValueError, RuntimeError) as error:
|
|
787
|
+
print(f"harness: {error}", file=sys.stderr, flush=True)
|
|
788
|
+
found = answer_of(record)
|
|
789
|
+
if found is not None:
|
|
790
|
+
answer = found
|
|
791
|
+
failed = failed or (record.get("event") == "state" and record.get("status") == "ERROR")
|
|
792
|
+
if _turn_over(record, answer is not None):
|
|
793
|
+
break
|
|
794
|
+
finally:
|
|
795
|
+
watch.set()
|
|
796
|
+
try:
|
|
797
|
+
conversation.close()
|
|
798
|
+
except Exception:
|
|
799
|
+
pass
|
|
800
|
+
if args.print:
|
|
801
|
+
print(answer or "")
|
|
802
|
+
return 1 if failed or answer is None else 0
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def _waits_for(record) -> str:
|
|
806
|
+
"""What a waiting record asks the user, in every frontend's words (transcript.py)."""
|
|
807
|
+
from .transcript import items
|
|
808
|
+
|
|
809
|
+
if "code" in record:
|
|
810
|
+
return f"Run this program?\n{record['code']}"
|
|
811
|
+
return next((item["text"] for item in items({**record, "event": "physical_request"}, {}) if item.get("text")),
|
|
812
|
+
"the agent waits for you")
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def _answer(what: str) -> tuple[bool, str]:
|
|
816
|
+
"""The user's answer in this terminal to what an agent of harness run "task" waits for (a
|
|
817
|
+
program under approvals.ask = programs, a sensitive step, physical input); without a
|
|
818
|
+
terminal, no, with the reason."""
|
|
819
|
+
if not sys.stdin.isatty():
|
|
820
|
+
return False, "nobody to ask: harness run without a terminal (harness, or harness run rpc, can answer)"
|
|
821
|
+
try:
|
|
822
|
+
print(f"{what}\nAllow it? [y/N] ", file=sys.stderr, end="", flush=True)
|
|
823
|
+
answer = input().strip().lower()
|
|
824
|
+
except EOFError:
|
|
825
|
+
answer = ""
|
|
826
|
+
return (True, "") if answer in ("y", "yes") else (False, "the user declined")
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def _watch_sub_agents(host, conversation, ask, seconds: float = 1.0) -> threading.Event:
|
|
830
|
+
"""Follow the session of `conversation` for sub-agents that wait for the user (their
|
|
831
|
+
records are not in the main agent's): ask(agent, what, request_id) once for each wait. Returns the
|
|
832
|
+
event that ends the watch."""
|
|
833
|
+
done, seen = threading.Event(), {}
|
|
834
|
+
|
|
835
|
+
def watch():
|
|
836
|
+
while not done.wait(seconds):
|
|
837
|
+
try:
|
|
838
|
+
agents = list(host.session(conversation.run, lines=0).agents())
|
|
839
|
+
for agent in agents:
|
|
840
|
+
request_id = agent.get("approval_id")
|
|
841
|
+
if (agent.get("depth") and agent.get("status") == "WAITING_FOR_CONFIRMATION" and request_id
|
|
842
|
+
and seen.get(agent["id"]) != request_id):
|
|
843
|
+
seen[agent["id"]] = request_id
|
|
844
|
+
what = agent.get("waiting") or "waits for approval"
|
|
845
|
+
threading.Thread(target=ask, args=(agent["id"], what, request_id), daemon=True).start()
|
|
846
|
+
except (ValueError, OSError, RuntimeError):
|
|
847
|
+
continue
|
|
848
|
+
|
|
849
|
+
threading.Thread(target=watch, name="sub-agents", daemon=True).start()
|
|
850
|
+
return done
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _rpc(args):
|
|
854
|
+
"""harness run rpc: one conversation driven by JSON lines on stdin, its records on stdout.
|
|
855
|
+
In: {"type": "prompt", "text", "files"} (the first starts the conversation, later ones are
|
|
856
|
+
messages; files: paths it attaches), {"type": "message", "text", "files"}, and the terminal
|
|
857
|
+
chat's commands with a method (terminal.COMMANDS): pause, continue, {"type": "approve",
|
|
858
|
+
"remember", "reason"}, {"type": "reject", "reason"}, end; {"type": "confirm", "accept",
|
|
859
|
+
"reason", "remember"} is approve or reject, stop is end; with "agent", they answer that
|
|
860
|
+
sub-agent. Out: {"type": "started", "run"}, {"type": "record", "record"}, {"type":
|
|
861
|
+
"waiting", "agent", "what"} (a sub-agent waits for the user), {"type": "error", "message"};
|
|
862
|
+
it ends when stdin closes, after end, or when the conversation ends."""
|
|
863
|
+
from .terminal import COMMANDS, command as run_command
|
|
864
|
+
|
|
865
|
+
if args.model and _coding(args).get("agent"):
|
|
866
|
+
raise UsageError("--model selects its own provider; use either --model or --agent")
|
|
867
|
+
if not _coding(args).get("agent") and not args.model:
|
|
868
|
+
_ready_model(interactive=False)
|
|
869
|
+
start = _starter(args)
|
|
870
|
+
lock = threading.Lock()
|
|
871
|
+
|
|
872
|
+
def send(message):
|
|
873
|
+
with lock:
|
|
874
|
+
sys.stdout.write(json.dumps(message, ensure_ascii=False) + "\n")
|
|
875
|
+
sys.stdout.flush()
|
|
876
|
+
|
|
877
|
+
conversation, streaming, watching = None, None, None
|
|
878
|
+
commands = Queue()
|
|
879
|
+
|
|
880
|
+
def read_input():
|
|
881
|
+
try:
|
|
882
|
+
for line in sys.stdin:
|
|
883
|
+
commands.put(line)
|
|
884
|
+
finally:
|
|
885
|
+
commands.put(None)
|
|
886
|
+
|
|
887
|
+
def stream(conversation):
|
|
888
|
+
try:
|
|
889
|
+
for record in conversation.records():
|
|
890
|
+
send({"type": "record", "record": record})
|
|
891
|
+
if record.get("event") == "state" and record.get("status") in ENDED:
|
|
892
|
+
break
|
|
893
|
+
except Exception as error: # the host went away
|
|
894
|
+
send({"type": "error", "message": str(error)})
|
|
895
|
+
finally:
|
|
896
|
+
commands.put(None)
|
|
897
|
+
|
|
898
|
+
threading.Thread(target=read_input, name="rpc-input", daemon=True).start()
|
|
899
|
+
for line in iter(commands.get, None):
|
|
900
|
+
if not line.strip():
|
|
901
|
+
continue
|
|
902
|
+
try:
|
|
903
|
+
command = json.loads(line)
|
|
904
|
+
if not isinstance(command, dict) or not isinstance(command.get("type"), str):
|
|
905
|
+
raise ValueError("a command must be an object with a string type")
|
|
906
|
+
kind = command["type"]
|
|
907
|
+
if kind in ("prompt", "message") and conversation is None:
|
|
908
|
+
host, conversation = start(str(command.get("text") or ""), files=command.get("files") or (),
|
|
909
|
+
model_entry=args.model, reasoning_effort=args.effort)
|
|
910
|
+
send({"type": "started", "run": conversation.run})
|
|
911
|
+
watching = _watch_sub_agents(host, conversation, lambda agent, what, request_id: send(
|
|
912
|
+
{"type": "waiting", "agent": agent, "what": what, "request_id": request_id}))
|
|
913
|
+
streaming = threading.Thread(target=stream, args=(conversation,), daemon=True)
|
|
914
|
+
streaming.start()
|
|
915
|
+
elif conversation is None:
|
|
916
|
+
raise ValueError("start with {\"type\": \"prompt\", \"text\": ...}")
|
|
917
|
+
elif kind in ("prompt", "message"):
|
|
918
|
+
conversation.send_message(str(command.get("text") or ""),
|
|
919
|
+
**({"files": command["files"]} if command.get("files") else {}))
|
|
920
|
+
elif kind == "steer":
|
|
921
|
+
conversation.steer(str(command.get("text") or ""), command.get("files") or ())
|
|
922
|
+
elif kind == "cancel":
|
|
923
|
+
conversation.cancel()
|
|
924
|
+
elif kind == "terminal":
|
|
925
|
+
conversation.terminal_input(str(command.get("text") or ""))
|
|
926
|
+
elif kind == "config":
|
|
927
|
+
send({"type": "config", **conversation.set_config(command.get("id"), command.get("value"))})
|
|
928
|
+
elif kind == "answer":
|
|
929
|
+
conversation.answer(command.get("request_id"), command.get("content"))
|
|
930
|
+
elif kind in ("approve", "reject", "confirm"):
|
|
931
|
+
if kind == "confirm" and type(command.get("accept")) is not bool:
|
|
932
|
+
raise ValueError("confirm requires a boolean accept")
|
|
933
|
+
accept = kind == "approve" or (kind == "confirm" and command["accept"])
|
|
934
|
+
agent, request_id = command.get("agent"), command.get("request_id")
|
|
935
|
+
reason = str(command.get("reason") or "")
|
|
936
|
+
remember = command.get("remember") if accept else None
|
|
937
|
+
remember = "once" if remember == "step" else remember
|
|
938
|
+
if agent:
|
|
939
|
+
if not isinstance(request_id, str) or not request_id:
|
|
940
|
+
raise ValueError("a sub-agent answer requires the request_id from its waiting message")
|
|
941
|
+
host.approve(conversation.run, accept, reason, str(agent), remember, request_id=request_id)
|
|
942
|
+
else:
|
|
943
|
+
conversation.confirm(accept, reason, remember,
|
|
944
|
+
**({"request_id": request_id} if request_id else {}))
|
|
945
|
+
else:
|
|
946
|
+
name = {"stop": "end", "confirm": "approve" if command.get("accept") else "reject"}.get(kind, kind)
|
|
947
|
+
if not COMMANDS.get(name, COMMANDS["help"]).method:
|
|
948
|
+
raise ValueError(f"unknown type {kind!r}")
|
|
949
|
+
run_command(conversation, name, {key: str(command[key]) for key in ("remember", "reason")
|
|
950
|
+
if command.get(key) is not None})
|
|
951
|
+
if name == "end":
|
|
952
|
+
break
|
|
953
|
+
except (ValueError, KeyError, OSError, RuntimeError) as error:
|
|
954
|
+
send({"type": "error", "message": f"{type(error).__name__}: {error}"})
|
|
955
|
+
if watching is not None:
|
|
956
|
+
watching.set()
|
|
957
|
+
if conversation is not None and streaming is not None:
|
|
958
|
+
try:
|
|
959
|
+
conversation.close()
|
|
960
|
+
except Exception:
|
|
961
|
+
pass
|
|
962
|
+
streaming.join(5)
|
|
963
|
+
return 0
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def _default(args):
|
|
967
|
+
"""harness with no command: the terminal chat with the agent on this computer, which
|
|
968
|
+
starts a conversation with the first message; the first run asks for the model and key."""
|
|
969
|
+
if not _coding(args).get("agent"):
|
|
970
|
+
_ready_model(interactive=True)
|
|
971
|
+
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
|
972
|
+
raise UsageError("the terminal chat needs a terminal: harness run \"task\", or harness run rpc")
|
|
973
|
+
from . import tui
|
|
974
|
+
|
|
975
|
+
tui.chat(start=_starter(args))
|
|
976
|
+
return 0
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
def _session_commands(parser):
|
|
980
|
+
actions = parser.add_subparsers(dest="action", required=True)
|
|
981
|
+
listing = actions.add_parser("ls")
|
|
982
|
+
listing.add_argument("--kind")
|
|
983
|
+
listing.add_argument("--project")
|
|
984
|
+
listing.add_argument("--all", action="store_true")
|
|
985
|
+
listing.add_argument("--json", action="store_true")
|
|
986
|
+
importing = actions.add_parser("import")
|
|
987
|
+
importing.add_argument("provider", choices=("claude-code", "codex"))
|
|
988
|
+
importing.add_argument("file", type=Path)
|
|
989
|
+
importing.add_argument("--follow", action="store_true")
|
|
990
|
+
discover = actions.add_parser("discover")
|
|
991
|
+
discover.add_argument("agent")
|
|
992
|
+
discover.add_argument("--folder", type=Path)
|
|
993
|
+
discover.add_argument("--cursor")
|
|
994
|
+
observe = actions.add_parser("observe")
|
|
995
|
+
observe.add_argument("agent")
|
|
996
|
+
observe.add_argument("external_id")
|
|
997
|
+
observe.add_argument("--folder", type=Path)
|
|
998
|
+
reconnect = actions.add_parser("reconnect")
|
|
999
|
+
reconnect.add_argument("session")
|
|
1000
|
+
reconnect.add_argument("--agent")
|
|
1001
|
+
reconnect.add_argument("--released", action="store_true", help="the previous controller has stopped")
|
|
1002
|
+
for name in ("show", "stop", "cancel", "diff", "merge", "discard", "attach"):
|
|
1003
|
+
actions.add_parser(name).add_argument("session")
|
|
1004
|
+
for name in ("send", "steer", "terminal"):
|
|
1005
|
+
send = actions.add_parser(name)
|
|
1006
|
+
send.add_argument("session")
|
|
1007
|
+
send.add_argument("text")
|
|
1008
|
+
config = actions.add_parser("config")
|
|
1009
|
+
config.add_argument("session")
|
|
1010
|
+
config.add_argument("id")
|
|
1011
|
+
config.add_argument("value")
|
|
1012
|
+
approve = actions.add_parser("approve")
|
|
1013
|
+
approve.add_argument("session")
|
|
1014
|
+
approve.add_argument("request_id")
|
|
1015
|
+
approve.add_argument("--agent")
|
|
1016
|
+
approve.add_argument("--reject", action="store_true")
|
|
1017
|
+
answer = actions.add_parser("answer")
|
|
1018
|
+
answer.add_argument("session")
|
|
1019
|
+
answer.add_argument("request_id")
|
|
1020
|
+
answer.add_argument("content", type=json.loads, help="JSON object, or null to decline")
|
|
1021
|
+
handoff = actions.add_parser("handoff")
|
|
1022
|
+
handoff.add_argument("session")
|
|
1023
|
+
handoff.add_argument("agent")
|
|
1024
|
+
handoff.add_argument("context")
|
|
1025
|
+
handoff.add_argument("--folder", type=Path)
|
|
1026
|
+
handoff.add_argument("--isolation", choices=("folder", "worktree"))
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def _sessions(args):
|
|
1030
|
+
from .host import Host
|
|
1031
|
+
from .host.sessions import COLUMNS, table_rows
|
|
1032
|
+
|
|
1033
|
+
host = Host.connect(start=False)
|
|
1034
|
+
if host is None:
|
|
1035
|
+
host = Host.connect()
|
|
1036
|
+
action = args.action
|
|
1037
|
+
if action == "ls":
|
|
1038
|
+
project = str(Path(args.project).resolve()) if args.project else None
|
|
1039
|
+
rows = [session.row for session in host.sessions(all=args.all, limit=0)
|
|
1040
|
+
if (not args.kind or session.row.get("kind") == args.kind)
|
|
1041
|
+
and (not project or session.row.get("project") in (project, args.project))]
|
|
1042
|
+
if args.json:
|
|
1043
|
+
output(rows)
|
|
1044
|
+
else:
|
|
1045
|
+
print(table(table_rows(rows), COLUMNS))
|
|
1046
|
+
elif action == "import":
|
|
1047
|
+
output({"run": host.import_session(args.file.resolve(), args.provider, follow=args.follow).run})
|
|
1048
|
+
elif action == "discover":
|
|
1049
|
+
output(host.discover_sessions(args.agent, args.folder.resolve() if args.folder else None, args.cursor))
|
|
1050
|
+
elif action == "observe":
|
|
1051
|
+
output({"run": host.observe_external(args.agent, args.external_id,
|
|
1052
|
+
folder=args.folder.resolve() if args.folder else None).run})
|
|
1053
|
+
elif action == "reconnect":
|
|
1054
|
+
output({"run": host.reconnect_session(args.session, released=args.released, agent=args.agent).run})
|
|
1055
|
+
elif action == "show":
|
|
1056
|
+
output(host.session(args.session).row)
|
|
1057
|
+
elif action == "stop":
|
|
1058
|
+
output({"stopped": host.stop_session(args.session)})
|
|
1059
|
+
elif action == "approve":
|
|
1060
|
+
output({"agent": host.approve(args.session, not args.reject, agent=args.agent, request_id=args.request_id)})
|
|
1061
|
+
else:
|
|
1062
|
+
conversation = host.conversation(args.session)
|
|
1063
|
+
if action == "attach":
|
|
1064
|
+
from . import tui
|
|
1065
|
+
|
|
1066
|
+
row = conversation.describe()
|
|
1067
|
+
if os.name == "posix" and row.get("kind") == "terminal":
|
|
1068
|
+
from .tui.pty import attach
|
|
1069
|
+
|
|
1070
|
+
attach(conversation, host)
|
|
1071
|
+
else:
|
|
1072
|
+
tui.chat(conversation, host=host)
|
|
1073
|
+
elif action in ("diff", "merge", "discard", "cancel"):
|
|
1074
|
+
output(getattr(conversation, action)() or {"ok": True})
|
|
1075
|
+
elif action == "handoff":
|
|
1076
|
+
next_session = conversation.handoff(args.agent, args.context, folder=args.folder, isolation=args.isolation)
|
|
1077
|
+
output({"run": next_session.run})
|
|
1078
|
+
elif action == "config":
|
|
1079
|
+
output(conversation.set_config(args.id, args.value))
|
|
1080
|
+
elif action == "answer":
|
|
1081
|
+
conversation.answer(args.request_id, args.content)
|
|
1082
|
+
else:
|
|
1083
|
+
method = {"send": "send_message", "steer": "steer", "terminal": "terminal_input"}[action]
|
|
1084
|
+
getattr(conversation, method)(args.text)
|
|
1085
|
+
return 0
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def _replay(args):
|
|
1089
|
+
"""harness replay RUN: terminal records, or raw records with --json."""
|
|
1090
|
+
from .core.episodes import read_records
|
|
1091
|
+
from .host import resolve_run
|
|
1092
|
+
|
|
1093
|
+
directory = resolve_run(args.run)
|
|
1094
|
+
records = read_records(directory)
|
|
1095
|
+
if not records:
|
|
1096
|
+
raise ValueError(f"no trace at {directory}")
|
|
1097
|
+
from .terminal import Printer
|
|
1098
|
+
|
|
1099
|
+
printer = Printer()
|
|
1100
|
+
for record in records:
|
|
1101
|
+
if args.json:
|
|
1102
|
+
print(json.dumps(record, ensure_ascii=False), flush=True)
|
|
1103
|
+
else:
|
|
1104
|
+
for line in printer.lines(record):
|
|
1105
|
+
print(line, flush=True)
|
|
1106
|
+
return 0
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _library_command(args):
|
|
1110
|
+
"""harness library: the libraries, and a library's or a run's memory (runtime/task/context.py
|
|
1111
|
+
rows), as the app and the terminal chat show them."""
|
|
1112
|
+
from .paths import home
|
|
1113
|
+
from harness.runtime.learning import learner
|
|
1114
|
+
from harness.core import memory as memory_view
|
|
1115
|
+
|
|
1116
|
+
if args.what == "ls":
|
|
1117
|
+
rows = learner.libraries()
|
|
1118
|
+
if args.json:
|
|
1119
|
+
output(rows)
|
|
1120
|
+
elif rows:
|
|
1121
|
+
print(table([{**row, "version": row["version"][:12], "entries": str(row["entries"])} for row in rows],
|
|
1122
|
+
["name", "entries", "version", "directory"]))
|
|
1123
|
+
else:
|
|
1124
|
+
print(f"No library under {home() / 'libraries'}")
|
|
1125
|
+
return 0
|
|
1126
|
+
if not args.path:
|
|
1127
|
+
raise ValueError("harness library show LIBRARY or RUN (a directory, or a library's name under "
|
|
1128
|
+
"$HARNESS_HOME/libraries)")
|
|
1129
|
+
path = Path(args.path)
|
|
1130
|
+
if not path.is_dir():
|
|
1131
|
+
path = home() / "libraries" / args.path
|
|
1132
|
+
found = memory_view.rows(run=path) if (path / "events.jsonl").is_file() else memory_view.rows(library=path)
|
|
1133
|
+
if args.json:
|
|
1134
|
+
output(found)
|
|
1135
|
+
else:
|
|
1136
|
+
print(table([dict(zip(memory_view.COLUMNS, row["cells"])) for row in found], list(memory_view.COLUMNS))
|
|
1137
|
+
if found else "(empty)")
|
|
1138
|
+
return 0
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def main(argv=None):
|
|
1142
|
+
words = list(sys.argv[1:] if argv is None else argv)
|
|
1143
|
+
if words[:1] == ["rpc"]:
|
|
1144
|
+
words.insert(0, "run")
|
|
1145
|
+
if words[:1] == ["chat"]:
|
|
1146
|
+
words.pop(0)
|
|
1147
|
+
if words[:2] == ["host", "serve"]:
|
|
1148
|
+
from .host.server import main as serve
|
|
1149
|
+
|
|
1150
|
+
return _guarded(lambda: serve(words[2:]))
|
|
1151
|
+
if words[:2] == ["run", "experiment"]:
|
|
1152
|
+
return _guarded(lambda: _experiment(words[2:]))
|
|
1153
|
+
explicit_task = "--" in words
|
|
1154
|
+
if words[:1] == ["run"] and len(words) > 1 and not explicit_task:
|
|
1155
|
+
first = words[1]
|
|
1156
|
+
if _is_experiment(first) or first.partition("=")[0] in ("--resume", "--dry-run", "--script"):
|
|
1157
|
+
return _guarded(lambda: _experiment(words[1:]))
|
|
1158
|
+
if words and not words[0].startswith("-") and words[0] not in core_commands() and (
|
|
1159
|
+
words[0] in FIRST_USE or words[0] in package_commands()):
|
|
1160
|
+
return _guarded(lambda: _package_command(words[0], words[1:]))
|
|
1161
|
+
command_parser = parser()
|
|
1162
|
+
args, rest = command_parser.parse_known_args(words)
|
|
1163
|
+
if rest and args.command != "doctor":
|
|
1164
|
+
command_parser.parse_args(words) # says what it does not know, exit status 2
|
|
1165
|
+
if args.command not in (None, "install", "remove", "list"):
|
|
1166
|
+
# The enabled packages' skills load here and in the kernels it starts.
|
|
1167
|
+
from .packages import activate
|
|
1168
|
+
|
|
1169
|
+
activate()
|
|
1170
|
+
commands = {"install": _install, "list": _list, "remove": _remove, "library": _library_command, "sessions": _sessions,
|
|
1171
|
+
"replay": _replay}
|
|
1172
|
+
if args.command == "run":
|
|
1173
|
+
if args.task == "rpc" and not explicit_task:
|
|
1174
|
+
if args.print or args.json:
|
|
1175
|
+
command_parser.error("harness run rpc already uses JSON lines")
|
|
1176
|
+
return _guarded(lambda: _rpc(args))
|
|
1177
|
+
return _guarded(lambda: _run_task(args))
|
|
1178
|
+
if args.command == "doctor":
|
|
1179
|
+
return _guarded(lambda: _doctor(args, words[words.index("doctor") + 1:]))
|
|
1180
|
+
if args.command is None:
|
|
1181
|
+
return _guarded(lambda: _default(args))
|
|
1182
|
+
return _guarded(lambda: commands[args.command](args))
|