@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,1356 @@
|
|
|
1
|
+
"""Host bounded natural-language tasks for CLI, Python and package frontends.
|
|
2
|
+
|
|
3
|
+
The host owns execution configuration, workers, run records and resource cleanup.
|
|
4
|
+
Each task has its own budget and working state. Persistent identities, conversation
|
|
5
|
+
history and personal memory are supplied by the optional agent package through the
|
|
6
|
+
public task API; this module neither loads nor imports that package.
|
|
7
|
+
|
|
8
|
+
POST /api/tasks starts a task with an optional explicit library and budget. Existing
|
|
9
|
+
run/session routes expose its evidence, steering and approvals. Workspace providers
|
|
10
|
+
own target selection and environment-specific behavior. The generic package/model
|
|
11
|
+
settings routes retain their /api/app prefix for existing frontend clients.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from http import HTTPStatus
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
import secrets
|
|
19
|
+
import sys
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
import tomllib
|
|
23
|
+
|
|
24
|
+
from .. import providers
|
|
25
|
+
from ..core import episodes as runs
|
|
26
|
+
from ..core.remote import RemoteEnvironment
|
|
27
|
+
from ..packages import MissingPackage, Packages, RegistryError, activate, addons, describe
|
|
28
|
+
from ..paths import ROOT, data
|
|
29
|
+
from harness.runtime.task.delegation import Agents, Place
|
|
30
|
+
from harness.runtime.task.environments import Place as Attaching
|
|
31
|
+
from ..settings import ChoiceRequired, Credentials, Settings
|
|
32
|
+
from .http import Handler, Server
|
|
33
|
+
from .sessions import title as session_title
|
|
34
|
+
|
|
35
|
+
CONVERSATION = ROOT / "configs" / "assistant.toml"
|
|
36
|
+
# What one conversation may set for itself (agent.runtime keys): harness run "task" --physical,
|
|
37
|
+
# --window-details, --think; and `learn`, a conversation that learns its environment for live
|
|
38
|
+
# minutes (true: learning.active_minutes) instead of doing a task (runtime/learning/active.py).
|
|
39
|
+
# `agents`: sub-agents on in this conversation whatever session.agents says.
|
|
40
|
+
RUN_KEYS = ("physical", "privacy", "think_while_acting", "think_interval", "learn", "managed_workspace", "agents")
|
|
41
|
+
# The keys of a conversation profile's file (profiles()).
|
|
42
|
+
PROFILE_KEYS = {
|
|
43
|
+
"description": "one line: what conversations of this profile are for",
|
|
44
|
+
"skills": "optional skills these conversations have on top of the assistant's; conversations of other "
|
|
45
|
+
"profiles (or none) do not have them",
|
|
46
|
+
"prompt": "a file (relative to the profile's) whose text is added to the system prompt",
|
|
47
|
+
}
|
|
48
|
+
# What the agent is told when the user gives the computer back (the page shows it as a note).
|
|
49
|
+
HANDBACK = "I took over the computer for a moment and have handed it back. Look at the screen again before you go on."
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class TaskHost:
|
|
53
|
+
"""The app's state: its data directory, the model key, this computer's worker and
|
|
54
|
+
the conversations it started."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, directory: Path | None = None, *, chat=None, verifier=None):
|
|
57
|
+
self.directory = Path(directory or data()).expanduser().resolve()
|
|
58
|
+
# Models in place of the configured ones (tests).
|
|
59
|
+
self._models = {"chat": chat, "verifier": verifier}
|
|
60
|
+
self.conversations_dir = self.directory / "conversations"
|
|
61
|
+
self.conversations_dir.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
self.credentials = Credentials(self.directory)
|
|
63
|
+
self.credentials.load()
|
|
64
|
+
self.settings = Settings(self.directory)
|
|
65
|
+
# The skills of the user's packages load beside the built-in ones, here and in kernels;
|
|
66
|
+
# first, as the settings a package adds are checked by its own code.
|
|
67
|
+
self.packages = activate(Packages(self.directory))
|
|
68
|
+
self.prune()
|
|
69
|
+
# Where conversations run: a package's (the computer's), made when first asked for.
|
|
70
|
+
self._workspaces = None
|
|
71
|
+
self.starting = {}
|
|
72
|
+
# Brings the chat's browser window to the front (the app package's focus, set by run()).
|
|
73
|
+
self.focus_chat = None
|
|
74
|
+
self._threads = {}
|
|
75
|
+
# The workspace kind of each conversation started here.
|
|
76
|
+
self._kinds = {}
|
|
77
|
+
# One reclaim at a time: conversations waiting for a workspace pick together.
|
|
78
|
+
self._reclaiming = threading.Lock()
|
|
79
|
+
self._external_start_lock = threading.Lock()
|
|
80
|
+
from ..services.mcp import Resources
|
|
81
|
+
self._mcp_resources = Resources()
|
|
82
|
+
|
|
83
|
+
def llm(self) -> dict:
|
|
84
|
+
"""The model the user chose, and whether its provider's key is there."""
|
|
85
|
+
settings = providers.load(self.directory)
|
|
86
|
+
provider = providers.PROVIDERS[settings["provider"]]
|
|
87
|
+
key = self.credentials.status(provider.key_env) if provider.key_env else {"set": True, "source": None}
|
|
88
|
+
return {**settings, "key_env": provider.key_env, "key": key, "ready": key["set"]}
|
|
89
|
+
|
|
90
|
+
def status(self) -> dict:
|
|
91
|
+
workspaces = self.available_workspaces()
|
|
92
|
+
return {"llm": self.llm(), "providers": providers.described(),
|
|
93
|
+
"workspaces": workspaces.status(), **workspaces.presentation()}
|
|
94
|
+
|
|
95
|
+
def conversations(self, server) -> list[dict]:
|
|
96
|
+
from .listing import conversations
|
|
97
|
+
|
|
98
|
+
return conversations(server)
|
|
99
|
+
|
|
100
|
+
def available_workspaces(self):
|
|
101
|
+
"""The workspaces a package of this process gives (harness/extensions.py), or None."""
|
|
102
|
+
if self._workspaces is None:
|
|
103
|
+
from .workspaces import Workspaces
|
|
104
|
+
self._workspaces = Workspaces(self.directory, self.settings)
|
|
105
|
+
return self._workspaces
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def workspaces(self):
|
|
109
|
+
"""Workspace providers from installed packages."""
|
|
110
|
+
return self.available_workspaces()
|
|
111
|
+
|
|
112
|
+
def kind(self, workspace: str | None = None, text: str | None = None) -> str:
|
|
113
|
+
"""The workspace kind a new conversation takes: `workspace` ("auto": the one its task
|
|
114
|
+
in words asks for), else the computer's mode."""
|
|
115
|
+
return self.workspaces.kind(workspace, text)
|
|
116
|
+
|
|
117
|
+
def environments(self, model_entry: str | None = None) -> dict:
|
|
118
|
+
"""What a new conversation may work in, for a frontend's choice: {"options": each
|
|
119
|
+
kind the core and the installed packages give ({"value", "label", "about"} and its
|
|
120
|
+
"folder", "views" and "physical" flags), "selected": what the choice highlights (the
|
|
121
|
+
last conversation's, else a saved computer.mode, else None: nothing is preselected),
|
|
122
|
+
"folder": the last project folder, "setting": session.environment}. An environment
|
|
123
|
+
with a screen carries a `note` when the model (`model_entry`, default the chosen
|
|
124
|
+
one) reads no images: the user is told before they choose."""
|
|
125
|
+
options = self.workspaces.environments()
|
|
126
|
+
have = {row["value"] for row in options}
|
|
127
|
+
options += [row for row in self.installable_environments() if row["value"] not in have]
|
|
128
|
+
note = self.reads_no_images(model_entry)
|
|
129
|
+
if note:
|
|
130
|
+
options = [{**row, "note": note} if row.get("views") else row for row in options]
|
|
131
|
+
kinds = [row["value"] for row in options]
|
|
132
|
+
last = self.settings.remembered("session", "last_environment")
|
|
133
|
+
if last not in kinds:
|
|
134
|
+
last = self.settings.remembered("computer", "mode")
|
|
135
|
+
return {"options": options, "selected": last if last in kinds else None,
|
|
136
|
+
"folder": self.settings.remembered("session", "last_folder") or None,
|
|
137
|
+
"setting": self.settings.get()["session"]["environment"]}
|
|
138
|
+
|
|
139
|
+
def installable_environments(self) -> list[dict]:
|
|
140
|
+
"""What a new installation can choose before any environment package is installed:
|
|
141
|
+
the environments of the registry's packages, as rows of the choice ({"value",
|
|
142
|
+
"label", "about", "package"}); choosing one installs its package as
|
|
143
|
+
packages.auto_install says. None when that is off, when the registry cannot be read
|
|
144
|
+
(asked again after ten minutes), or once a package gives an environment: from then
|
|
145
|
+
on the choice lists what is installed, and naming another one still installs it."""
|
|
146
|
+
if self.packages.auto_install() == "off" or self.workspaces.providers():
|
|
147
|
+
return []
|
|
148
|
+
if time.monotonic() < getattr(self, "_registry_unread_until", 0):
|
|
149
|
+
return []
|
|
150
|
+
try:
|
|
151
|
+
rows = self.packages.registry.search()
|
|
152
|
+
except (RegistryError, OSError, ValueError):
|
|
153
|
+
self._registry_unread_until = time.monotonic() + 600
|
|
154
|
+
return []
|
|
155
|
+
installed = {row["name"] for row in self.packages.installed()}
|
|
156
|
+
found = {}
|
|
157
|
+
for row in rows:
|
|
158
|
+
if row["name"] in installed:
|
|
159
|
+
continue
|
|
160
|
+
for kind in row.get("provides", {}).get("workspaces", []):
|
|
161
|
+
found.setdefault(kind, {"value": kind, "label": kind.replace("-", " ").capitalize(),
|
|
162
|
+
"about": f"{row['summary']} (installs the package {row['name']})",
|
|
163
|
+
"package": row["name"]})
|
|
164
|
+
from .workspaces import ORDER
|
|
165
|
+
return [found[kind] for kind in (*[k for k in ORDER if k in found], *sorted(set(found) - set(ORDER)))]
|
|
166
|
+
|
|
167
|
+
def install_environment(self, workspace: str) -> bool:
|
|
168
|
+
"""Install the registry's package of an environment no installed package gives
|
|
169
|
+
(packages.auto_install); False when there is none or it is not to be installed."""
|
|
170
|
+
try:
|
|
171
|
+
self.packages.ensure("workspaces", workspace, log=lambda message: None)
|
|
172
|
+
except (MissingPackage, RegistryError, OSError):
|
|
173
|
+
return False
|
|
174
|
+
return workspace in self.workspaces.kinds()
|
|
175
|
+
|
|
176
|
+
def reads_no_images(self, model_entry: str | None = None) -> str:
|
|
177
|
+
"""What to say beside an environment with a screen when the model reads no images
|
|
178
|
+
(its entry of the model list); empty when it reads them."""
|
|
179
|
+
from .. import model_list
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
row = next((item for item in self.models() if item["id"] == model_entry), None) if model_entry else None
|
|
183
|
+
choice = row or providers.load(self.directory)
|
|
184
|
+
if (row.get("images") is not False) if row else model_list.reads_images(self.directory, choice):
|
|
185
|
+
return ""
|
|
186
|
+
except (ValueError, OSError):
|
|
187
|
+
return ""
|
|
188
|
+
vision = self.settings.get()["model"].get("vision")
|
|
189
|
+
name = choice.get("model") or "the model"
|
|
190
|
+
return (f"{name} reads no images: {vision} describes what it looks at" if vision else
|
|
191
|
+
f"needs a model that reads images: {name} reads none, so no picture is sent and it works "
|
|
192
|
+
"from text only")
|
|
193
|
+
|
|
194
|
+
def environment(self, workspace=None, folder=None, *, last=False, model_entry=None) -> tuple:
|
|
195
|
+
"""Where a new conversation works, as (kind, folder): the `workspace` it names; a
|
|
196
|
+
`folder` alone names a project; with neither, session.environment decides: a fixed
|
|
197
|
+
kind, `last` (the last conversation's choice; `last=True` asks for that whatever the
|
|
198
|
+
setting says: a frontend with no way to ask or to name one), or `ask`, which raises
|
|
199
|
+
ChoiceRequired with the choice for the frontend to put to the user. Nothing is ever
|
|
200
|
+
chosen for the user."""
|
|
201
|
+
offered = self.environments(model_entry)
|
|
202
|
+
by = {row["value"]: row for row in offered["options"]}
|
|
203
|
+
if workspace in (None, "auto") and folder is not None:
|
|
204
|
+
if any(provider.accepts({"folder": folder}) for provider in self.workspaces.providers()):
|
|
205
|
+
workspace = self.workspaces.kind(None, None, binding={"folder": folder})
|
|
206
|
+
else:
|
|
207
|
+
# No installed package takes a folder: a folder alone names a project.
|
|
208
|
+
workspace = "project"
|
|
209
|
+
if workspace in (None, "auto"):
|
|
210
|
+
setting = "last" if last else offered["setting"]
|
|
211
|
+
if setting == "last" and offered["selected"]:
|
|
212
|
+
workspace = offered["selected"]
|
|
213
|
+
elif setting not in ("ask", "last"):
|
|
214
|
+
if setting not in by:
|
|
215
|
+
raise ValueError(f"session.environment is {setting!r}, which no installed package provides; "
|
|
216
|
+
f"it is ask, last or one of {', '.join(by)}")
|
|
217
|
+
workspace = setting
|
|
218
|
+
else:
|
|
219
|
+
names = ", ".join(by)
|
|
220
|
+
raise ChoiceRequired({
|
|
221
|
+
"section": "session", "key": "environment", "per_conversation": True,
|
|
222
|
+
"title": "Where should Harness work?", "selected": offered["selected"],
|
|
223
|
+
"folder": offered["folder"],
|
|
224
|
+
"options": [{**row, "label": (f"{row['label']} — {row['about']}" if row.get("about") else
|
|
225
|
+
row["label"]) + (f" ({row['note']})" if row.get("note") else ""),
|
|
226
|
+
"name": row["label"]} for row in offered["options"]],
|
|
227
|
+
"message": "Choose where this conversation works: --workspace KIND (workspace=KIND in Python), "
|
|
228
|
+
f"one of {names}; or set session.environment to last or to one of them"})
|
|
229
|
+
if by.get(workspace, {}).get("folder") and folder is None:
|
|
230
|
+
folder = offered["folder"]
|
|
231
|
+
# An environment of a package that is not installed yet: installed the first time.
|
|
232
|
+
if (workspace not in by or by[workspace].get("package")) and self.install_environment(workspace):
|
|
233
|
+
offered = self.environments(model_entry)
|
|
234
|
+
by = {row["value"]: row for row in offered["options"]}
|
|
235
|
+
if workspace not in by or by[workspace].get("package"):
|
|
236
|
+
raise ValueError(f"no installed package provides workspace {workspace!r}; there are "
|
|
237
|
+
f"{', '.join(kind for kind, row in by.items() if not row.get('package'))}")
|
|
238
|
+
kind = self.workspaces.kind(workspace)
|
|
239
|
+
if by[workspace].get("folder") and not folder:
|
|
240
|
+
raise ValueError(f"a {kind} conversation works in one folder: name it with --folder PATH (folder=PATH)")
|
|
241
|
+
return kind, folder
|
|
242
|
+
|
|
243
|
+
def models(self, change=None):
|
|
244
|
+
from .. import model_list
|
|
245
|
+
|
|
246
|
+
return model_list.models(self.directory, change)
|
|
247
|
+
|
|
248
|
+
def set_model(self, body: dict) -> dict:
|
|
249
|
+
"""Choose a provider and model (and give its key): checked with the provider before
|
|
250
|
+
anything is kept."""
|
|
251
|
+
settings = providers.check(body)
|
|
252
|
+
provider = providers.PROVIDERS[settings["provider"]]
|
|
253
|
+
key = str(body.get("key") or "").strip() or (os.environ.get(provider.key_env) if provider.key_env else None)
|
|
254
|
+
if provider.key_env and not key:
|
|
255
|
+
return {"ok": False, "detail": "no key"}
|
|
256
|
+
result = providers.reach(settings, key)
|
|
257
|
+
if result["ok"]:
|
|
258
|
+
if provider.key_env and body.get("key"):
|
|
259
|
+
self.credentials.save(key, provider.key_env)
|
|
260
|
+
providers.save(self.directory, settings)
|
|
261
|
+
from .. import model_list
|
|
262
|
+
|
|
263
|
+
row = model_list.entry(settings)
|
|
264
|
+
if not any(item["id"] == row["id"] for item in self.models()):
|
|
265
|
+
self.models({"action": "save", **settings})
|
|
266
|
+
return result
|
|
267
|
+
|
|
268
|
+
def config(self, model=None, kind=None, profile=None, *, choice=None, effort=None, agents=None):
|
|
269
|
+
"""The configuration (TaskConfig) of an assistant conversation with the user's model (or
|
|
270
|
+
`model`, another id of the same provider) and settings, in a workspace of `kind`
|
|
271
|
+
(default: the computer's mode), of a package's `profile` (profiles()); its endpoint is
|
|
272
|
+
set when the workspace runs."""
|
|
273
|
+
from ..bench import bench_specs, declares_channels
|
|
274
|
+
from ..extensions import hosts
|
|
275
|
+
from ..config.agent import overridden_agent, task_config
|
|
276
|
+
from ..services.placement import load_deploy
|
|
277
|
+
|
|
278
|
+
values = self.settings.get()
|
|
279
|
+
kind = self.kind(kind)
|
|
280
|
+
from .. import model_list
|
|
281
|
+
|
|
282
|
+
current = providers.load(self.directory)
|
|
283
|
+
advanced = values["model"]
|
|
284
|
+
if choice is not None:
|
|
285
|
+
advanced = {**advanced, "reasoning_effort": effort}
|
|
286
|
+
if any(choice.get(key) != current.get(key) for key in ("provider", "base_url")):
|
|
287
|
+
advanced.pop("checker", None)
|
|
288
|
+
advanced.pop("vision", None)
|
|
289
|
+
choice = choice or current
|
|
290
|
+
if model:
|
|
291
|
+
choice = {**choice, "model": str(model)}
|
|
292
|
+
# A model the list says reads no images is sent none (its role's `images`).
|
|
293
|
+
try:
|
|
294
|
+
if not model_list.reads_images(self.directory, choice):
|
|
295
|
+
advanced = {**advanced, "images": False}
|
|
296
|
+
except (ValueError, OSError):
|
|
297
|
+
pass
|
|
298
|
+
path = providers.model_file(choice, self.directory, advanced)
|
|
299
|
+
tree = self.conversation_tree(values, kind)
|
|
300
|
+
skills = self.skills_on(values, kind, profile, agents=agents)
|
|
301
|
+
embodiment = bench_specs()[tree["bench"]].kind
|
|
302
|
+
embodiment_config = tree.setdefault("overrides", {}).setdefault("agent", {}).setdefault(embodiment, {})
|
|
303
|
+
embodiment_config["skills"] = {**embodiment_config.get("skills", {}), "enable": skills["enable"]}
|
|
304
|
+
# What waits for the user in this conversation (its lock records it; the conversation's
|
|
305
|
+
# confirmation follows it, confirmation_policy).
|
|
306
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), "approvals": {"ask": values["approvals"]["ask"]}}
|
|
307
|
+
# The skills the user installed: the prompt's installed section (runtime/decision/prompts.py).
|
|
308
|
+
if skills["installed"]:
|
|
309
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), "installed_skills": skills["installed"]}
|
|
310
|
+
if skills["agent"]:
|
|
311
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}),
|
|
312
|
+
"agent_skills": addons.agent_skill_options(self.packages, skills["agent"])}
|
|
313
|
+
# No implicit cross-task knowledge. A caller can explicitly bind a learning library.
|
|
314
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), "library": None}
|
|
315
|
+
servers = self.mcp_servers()
|
|
316
|
+
if servers:
|
|
317
|
+
# The MCP servers a package connects (the app's connectors, through its gateway).
|
|
318
|
+
embodiment_config["skills"]["enable"] = [*embodiment_config["skills"]["enable"], "mcp"]
|
|
319
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), "mcp": servers}
|
|
320
|
+
spec = bench_specs()[tree["bench"]]
|
|
321
|
+
agent = overridden_agent(tree.get("overrides", {}), model=str(path), deploy=load_deploy(None),
|
|
322
|
+
embodiment=spec.kind, channels=declares_channels(spec),
|
|
323
|
+
package_paths=[spec.path, *profile_paths().get(profile, ()),
|
|
324
|
+
*(package.path for package, module in hosts()
|
|
325
|
+
if servers and hasattr(module, "mcp_servers"))])
|
|
326
|
+
config = task_config(agent, "free", [0], budget=tree.get("budget"), endpoint="http://127.0.0.1:1",
|
|
327
|
+
path=CONVERSATION)
|
|
328
|
+
viewer = providers.viewer_role(choice, advanced)
|
|
329
|
+
if viewer:
|
|
330
|
+
config.runtime = {**config.runtime, "viewer": viewer}
|
|
331
|
+
additions = ""
|
|
332
|
+
if servers:
|
|
333
|
+
additions += "\nConnectors the user added:\n" + "".join(
|
|
334
|
+
f" {name}: {server['description']}\n" for name, server in servers.items())
|
|
335
|
+
if profile and profiles()[profile]["prompt"]:
|
|
336
|
+
additions += "\n" + profiles()[profile]["prompt"] + "\n"
|
|
337
|
+
config.system_prompt += additions
|
|
338
|
+
config.base_prompt += additions
|
|
339
|
+
return config
|
|
340
|
+
|
|
341
|
+
def learning(self, config, minutes):
|
|
342
|
+
"""`config` as a conversation that learns its environment for `minutes` of live time
|
|
343
|
+
(true: the settings' learning.active_minutes), its entries' tests run again at its start
|
|
344
|
+
(runtime/learning/active.py active_config). ValueError when learning is frozen."""
|
|
345
|
+
from harness.runtime.learning import active
|
|
346
|
+
|
|
347
|
+
library = config.runtime.get("library") or {}
|
|
348
|
+
if library.get("learn") != "on":
|
|
349
|
+
raise ValueError("learning is frozen in the settings (learning.mode): nothing would be kept")
|
|
350
|
+
minutes = self.settings.get()["learning"]["active_minutes"] if minutes is True else minutes
|
|
351
|
+
config.runtime = {**config.runtime, "library": {**library, "replay": True, "active_minutes": minutes}}
|
|
352
|
+
return active.active_config(config)
|
|
353
|
+
|
|
354
|
+
def progress(self, server, run: str) -> dict:
|
|
355
|
+
"""Where a conversation that learns its environment stands (runtime/learning/active.py
|
|
356
|
+
progress()); {"active": False} for any other."""
|
|
357
|
+
from harness.runtime.learning import active
|
|
358
|
+
|
|
359
|
+
conversation = server.conversations.get(run)
|
|
360
|
+
if conversation is None or not active.is_active(conversation.config.runtime):
|
|
361
|
+
return {"active": False}
|
|
362
|
+
return {"active": True, "status": conversation.status, "library": conversation._learner().directory.name,
|
|
363
|
+
**conversation._learning_progress()}
|
|
364
|
+
|
|
365
|
+
def skills_on(self, values: dict | None = None, kind: str | None = None, profile: str | None = None, *,
|
|
366
|
+
agents: bool | None = None) -> dict:
|
|
367
|
+
"""The skills a new conversation enables: checklist unless the user turned it off, chat
|
|
368
|
+
(stay_on_screen), screens (several monitors), the installed ones that are on;
|
|
369
|
+
instructions when an Agent Skill is on; browser in a browser workspace, physical
|
|
370
|
+
(asking for the real mouse and keyboard up front) on the desktop; environments
|
|
371
|
+
(taking another environment, asking for sub-agents); agents (sub-agents) only when
|
|
372
|
+
they are on (`agents`, default the setting session.agents) and the nesting depth
|
|
373
|
+
allows one; entries (parts of the work that run beside the programs). An installed
|
|
374
|
+
skill a profile names is on only in the conversations of that profile."""
|
|
375
|
+
from harness.runtime.execution.skills import load_skills
|
|
376
|
+
|
|
377
|
+
values = values or self.settings.get()
|
|
378
|
+
off = set((values.get("skills") or {}).get("off", []))
|
|
379
|
+
loaded = load_skills()
|
|
380
|
+
given = profiles()
|
|
381
|
+
if profile is not None and profile not in given:
|
|
382
|
+
raise ValueError(f"no profile {profile}" + (f"; profiles: {', '.join(sorted(given))}" if given else ""))
|
|
383
|
+
mine = set(given[profile]["skills"]) if profile else set()
|
|
384
|
+
off |= {name for found in given.values() for name in found["skills"]} - mine
|
|
385
|
+
rows = [row for row in addons.skills(self.packages) if "problem" not in row and row["name"] not in off]
|
|
386
|
+
# The app's agent works on this computer: the packages' skills for it.
|
|
387
|
+
from ..bench import bench_spec
|
|
388
|
+
embodiment = bench_spec(self.workspaces.bench(kind)).kind
|
|
389
|
+
installed = [row["name"] for row in rows if row["format"] == "harness" and row["name"] in loaded
|
|
390
|
+
and embodiment in row.get("embodiments", ())]
|
|
391
|
+
agent = [row["name"] for row in rows if row["format"] == "agent"]
|
|
392
|
+
enable = [*(["checklist"] if not {"checklist", "plan"} & off else []), "entries", *installed,
|
|
393
|
+
*sorted(mine - set(installed)), *(["instructions"] if agent else [])]
|
|
394
|
+
enable += list(self.workspaces.provider(kind).extra_skills(kind))
|
|
395
|
+
enable.append("environments")
|
|
396
|
+
if agents is None:
|
|
397
|
+
agents = values["session"]["agents"] == "on"
|
|
398
|
+
if agents and values["limits"]["agent_depth"] > 0:
|
|
399
|
+
enable.append("agents")
|
|
400
|
+
return {"enable": enable, "installed": installed, "agent": agent}
|
|
401
|
+
|
|
402
|
+
def skills(self) -> dict:
|
|
403
|
+
"""The skills as Settings lists them: the built-in ones of this computer and the
|
|
404
|
+
installed ones, each on or off; why an installed one cannot load."""
|
|
405
|
+
from harness.runtime.execution.skills import USER_PROBLEMS, load_skills
|
|
406
|
+
|
|
407
|
+
off = set((self.settings.get().get("skills") or {}).get("off", []))
|
|
408
|
+
loaded = load_skills()
|
|
409
|
+
from ..bench import bench_spec
|
|
410
|
+
embodiment = bench_spec(self.workspaces.bench(self.kind())).kind
|
|
411
|
+
rows = [{"name": embodiment, "format": "built-in", "summary": loaded[embodiment].summary, "locked": True,
|
|
412
|
+
"on": True},
|
|
413
|
+
{"name": "checklist", "format": "built-in", "summary": loaded["checklist"].summary,
|
|
414
|
+
"on": not {"checklist", "plan"} & off}]
|
|
415
|
+
for name in self.workspaces.provider().builtin_skills(self.kind()):
|
|
416
|
+
if name != embodiment:
|
|
417
|
+
rows.append({"name": name, "format": "built-in", "summary": loaded[name].summary,
|
|
418
|
+
"locked": True, "on": True})
|
|
419
|
+
for row in addons.skills(self.packages):
|
|
420
|
+
if row["format"] == "harness" and "embodiments" in row and embodiment not in row["embodiments"]:
|
|
421
|
+
continue
|
|
422
|
+
problem = row.get("problem") or USER_PROBLEMS.get(row["path"]) if row["format"] == "harness" else \
|
|
423
|
+
row.get("problem")
|
|
424
|
+
if row["format"] == "harness" and not problem and row["name"] not in loaded:
|
|
425
|
+
problem = "did not load"
|
|
426
|
+
rows.append({**row, "on": row["name"] not in off and not problem, **({"problem": problem} if problem else {})})
|
|
427
|
+
return {"skills": rows}
|
|
428
|
+
|
|
429
|
+
def switch_skill(self, name: str, on: bool) -> dict:
|
|
430
|
+
known = {row["name"]: row for row in self.skills()["skills"]}
|
|
431
|
+
if name not in known or known[name].get("locked"):
|
|
432
|
+
raise ValueError(f"no skill {name} to switch")
|
|
433
|
+
section = dict(self.settings.get().get("skills") or {})
|
|
434
|
+
names = {"checklist", "plan"} if name == "checklist" else {name}
|
|
435
|
+
off = [item for item in section.get("off", []) if item not in names] + ([] if on else [name])
|
|
436
|
+
self.settings.put("skills", {**section, "off": off})
|
|
437
|
+
return self.skills()
|
|
438
|
+
|
|
439
|
+
def packages_state(self) -> dict:
|
|
440
|
+
"""The Packages page: the installed packages (`shown`: describe()), the skills, the settings."""
|
|
441
|
+
return {"packages": [{**row, "shown": describe(row)} for row in self.packages.installed()], **self.skills(),
|
|
442
|
+
"auto_install": self.packages.auto_install(), "registry": self.packages.registry.base}
|
|
443
|
+
|
|
444
|
+
def install_packages(self, body: dict) -> dict:
|
|
445
|
+
"""Install from a source (a registry name, a git or archive URL, a folder) or an
|
|
446
|
+
uploaded archive. One from outside the registry runs code nobody reviewed: it is
|
|
447
|
+
installed only with `trust`, after the page showed what it brings. A folder of
|
|
448
|
+
skills becomes a package per skill, taken only when it runs on this computer."""
|
|
449
|
+
import base64
|
|
450
|
+
from ..bench import bench_spec
|
|
451
|
+
|
|
452
|
+
zip_bytes = base64.b64decode(body["zip"]) if body.get("zip") else None
|
|
453
|
+
if not zip_bytes and not body.get("source"):
|
|
454
|
+
raise ValueError("give a package name, a folder, an archive or a git URL")
|
|
455
|
+
|
|
456
|
+
def kernel_python():
|
|
457
|
+
# A skill's requirements are for the kernel: the environment of the computer's mode.
|
|
458
|
+
return self.workspaces.provider().python(self.kind(), log=lambda message: None)
|
|
459
|
+
|
|
460
|
+
result = self.packages.install([body["source"]] if body.get("source") else [], zip_bytes=zip_bytes,
|
|
461
|
+
consent=lambda found: bool(body.get("trust")), python=kernel_python,
|
|
462
|
+
embodiment=bench_spec(self.workspaces.bench(self.kind())).kind,
|
|
463
|
+
log=lambda message: None)
|
|
464
|
+
if result.get("found"):
|
|
465
|
+
result = {**result, "found": [{**found, "shown": describe(found)} for found in result["found"]]}
|
|
466
|
+
return {**result, **self.packages_state()}
|
|
467
|
+
|
|
468
|
+
def conversation_tree(self, values: dict, kind: str | None = None) -> dict:
|
|
469
|
+
"""The assistant's configuration (configs/assistant.toml) with the user's limits, in a
|
|
470
|
+
workspace of `kind` (default: the computer's mode)."""
|
|
471
|
+
from ..config import load_layered
|
|
472
|
+
|
|
473
|
+
tree = load_layered(CONVERSATION)
|
|
474
|
+
limits = values["limits"]
|
|
475
|
+
tree["budget"] = {**tree.get("budget", {}), "max_model_calls": int(limits["max_steps"]),
|
|
476
|
+
"max_wall_seconds": int(limits["max_minutes"]) * 60,
|
|
477
|
+
"max_cost_usd": float(limits["max_cost_usd"])}
|
|
478
|
+
# The workspace's own (a background browser's prompt).
|
|
479
|
+
tree = self.workspaces.tree(tree, kind)
|
|
480
|
+
# When the model thinks while the agent acts (Settings, Model).
|
|
481
|
+
model = values.get("model") or {}
|
|
482
|
+
thinks = {**({"think_while_acting": model["think_while_acting"]}
|
|
483
|
+
if model.get("think_while_acting", "default") != "default" else {}),
|
|
484
|
+
**({"think_interval": int(model["think_interval"])} if model.get("think_interval") else {})}
|
|
485
|
+
if thinks:
|
|
486
|
+
from ..bench import bench_spec
|
|
487
|
+
embodiment = bench_spec(tree["bench"]).kind
|
|
488
|
+
embodiment_config = tree.setdefault("overrides", {}).setdefault("agent", {}).setdefault(embodiment, {})
|
|
489
|
+
embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), **thinks}
|
|
490
|
+
return tree
|
|
491
|
+
|
|
492
|
+
def prune(self) -> list[str]:
|
|
493
|
+
"""Delete the conversations older than the user keeps them (data.keep_days)."""
|
|
494
|
+
import shutil
|
|
495
|
+
|
|
496
|
+
days = self.settings.get()["data"]["keep_days"]
|
|
497
|
+
if not days:
|
|
498
|
+
return []
|
|
499
|
+
limit = time.time() - days * 86400
|
|
500
|
+
gone = []
|
|
501
|
+
for directory in sorted(self.conversations_dir.iterdir()):
|
|
502
|
+
trace = directory / "events.jsonl"
|
|
503
|
+
if directory.is_dir() and trace.is_file() and trace.stat().st_mtime < limit:
|
|
504
|
+
shutil.rmtree(directory, ignore_errors=True)
|
|
505
|
+
gone.append(directory.name)
|
|
506
|
+
return gone
|
|
507
|
+
|
|
508
|
+
def _meta(self, server, run) -> tuple[Path, dict]:
|
|
509
|
+
directory = (server.root / str(run)).resolve()
|
|
510
|
+
if self.conversations_dir.resolve() not in directory.parents or not directory.is_dir():
|
|
511
|
+
raise ValueError(f"no conversation {run}")
|
|
512
|
+
try:
|
|
513
|
+
meta = json.loads((directory / "meta.json").read_text(encoding="utf-8"))
|
|
514
|
+
except (OSError, ValueError):
|
|
515
|
+
meta = {}
|
|
516
|
+
return directory, meta
|
|
517
|
+
|
|
518
|
+
def model_changed(self, server, run, changed: dict) -> None:
|
|
519
|
+
"""Keep a conversation's model and reasoning effort as they are now in its meta.json
|
|
520
|
+
(the app's conversations only)."""
|
|
521
|
+
try:
|
|
522
|
+
directory, meta = self._meta(server, run)
|
|
523
|
+
except ValueError:
|
|
524
|
+
return
|
|
525
|
+
meta.update(model=changed.get("model"), reasoning_effort=changed.get("reasoning_effort"))
|
|
526
|
+
(directory / "meta.json").write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def start(self, server, text: str, model: str | None = None, confirmation: str | None = None,
|
|
530
|
+
workspace: str | None = None, runtime: dict | None = None, files=(),
|
|
531
|
+
reasoning_effort: str | None = None, profile: str | None = None, *,
|
|
532
|
+
agent: str | None = None, folder: str | None = None, isolation: str | None = None,
|
|
533
|
+
frontend: str | None = None, mcp_tools=(), execution: str | None = None,
|
|
534
|
+
budget: dict | None = None, library: dict | None = None, title: str | None = None, model_entry: str | None = None) -> str:
|
|
535
|
+
"""Start a conversation with the user's first message: its directory and record
|
|
536
|
+
now, its workspace (of kind `workspace`: "none" takes none; without one and without a
|
|
537
|
+
`folder`, session.environment decides, environment(); installed on first use) and the
|
|
538
|
+
episode on a thread of their own. `runtime`: this conversation's
|
|
539
|
+
own physical-input policy, what the model learns of other windows and when it
|
|
540
|
+
thinks while acting (RUN_KEYS, as harness run "task" --physical ... gives them).
|
|
541
|
+
`files`: paths the first message attaches. `reasoning_effort`: the main model's provider option ID.
|
|
542
|
+
`profile`: a package's (profiles()), its skills and prompt. Returns its run (a path under
|
|
543
|
+
the conversations directory)."""
|
|
544
|
+
from .. import model_list
|
|
545
|
+
from harness.runtime.decision.model import valid_effort
|
|
546
|
+
|
|
547
|
+
choice = None
|
|
548
|
+
if reasoning_effort == "default":
|
|
549
|
+
reasoning_effort = ""
|
|
550
|
+
if reasoning_effort is not None and not valid_effort(reasoning_effort):
|
|
551
|
+
raise ValueError("invalid reasoning effort ID")
|
|
552
|
+
if not model_entry and not model and not agent and frontend == "taptab":
|
|
553
|
+
default = model_list.select(self.directory, native=True)
|
|
554
|
+
if default is None:
|
|
555
|
+
raise ValueError("add an enabled Harness model in Settings")
|
|
556
|
+
model_entry = default["id"]
|
|
557
|
+
if model_entry:
|
|
558
|
+
choice = next((row for row in self.models()
|
|
559
|
+
if row["id"] == model_entry and row["enabled"]), None)
|
|
560
|
+
if choice is None:
|
|
561
|
+
raise ValueError("the selected model is no longer enabled")
|
|
562
|
+
model = choice["model"] or None
|
|
563
|
+
if choice["provider"] not in providers.PROVIDERS:
|
|
564
|
+
if agent and agent != choice["provider"]:
|
|
565
|
+
raise ValueError("the selected model uses a different agent")
|
|
566
|
+
agent = choice["provider"]
|
|
567
|
+
elif agent and agent != "harness":
|
|
568
|
+
raise ValueError("the selected model uses a different provider")
|
|
569
|
+
if reasoning_effort and reasoning_effort not in choice["efforts"]:
|
|
570
|
+
raise ValueError("this model does not offer that reasoning effort")
|
|
571
|
+
if agent and agent != "harness":
|
|
572
|
+
if execution is not None or budget is not None:
|
|
573
|
+
raise ValueError("this adapter does not accept execution bounds")
|
|
574
|
+
if runtime or profile or confirmation or workspace not in (None, "auto"):
|
|
575
|
+
raise ValueError("native workspace, isolation and approval settings apply only to the Harness agent")
|
|
576
|
+
return self.start_external(server, agent, str(text or ""), files, folder, isolation,
|
|
577
|
+
frontend, model, reasoning_effort or None, mcp_tools=mcp_tools)
|
|
578
|
+
if isolation or mcp_tools:
|
|
579
|
+
raise ValueError("isolation and mcp_tools are options for external agents")
|
|
580
|
+
from harness.runtime.learning import active
|
|
581
|
+
from harness.runtime.task.run import TaskRun
|
|
582
|
+
from harness.runtime.safety.approval import confirmation_policy
|
|
583
|
+
|
|
584
|
+
text = str(text or "").strip()
|
|
585
|
+
if not text:
|
|
586
|
+
raise ValueError("say what to do")
|
|
587
|
+
if choice:
|
|
588
|
+
provider = providers.PROVIDERS[choice["provider"]]
|
|
589
|
+
if provider.key_env:
|
|
590
|
+
self.credentials.load()
|
|
591
|
+
if not os.environ.get(provider.key_env):
|
|
592
|
+
raise ValueError(f"configure credentials for {provider.name} in Settings")
|
|
593
|
+
elif not self.llm()["ready"]:
|
|
594
|
+
raise ValueError("no model key yet")
|
|
595
|
+
kind, folder = self.environment(workspace, folder, last=frontend == "taptab", model_entry=model_entry)
|
|
596
|
+
request = {"folder": folder} if folder is not None else {}
|
|
597
|
+
self.workspaces.require_choices(kind, runtime)
|
|
598
|
+
# The package of the workspace's bench (computer, browser), installed the first
|
|
599
|
+
# time as packages.auto_install says.
|
|
600
|
+
if self.workspaces.environment(kind) is None:
|
|
601
|
+
self.packages.ensure("benches", self.workspaces.bench(kind), log=lambda message: None)
|
|
602
|
+
switched = (runtime or {}).get("agents")
|
|
603
|
+
if switched is not None and type(switched) is not bool:
|
|
604
|
+
raise ValueError("agents must be a boolean")
|
|
605
|
+
config = self.config(model, kind, profile, choice=choice, effort=reasoning_effort, agents=switched)
|
|
606
|
+
if budget is not None:
|
|
607
|
+
import math
|
|
608
|
+
|
|
609
|
+
for key, limit in budget.items():
|
|
610
|
+
if key not in ("max_wall_seconds", "max_model_calls", "max_cost_usd"):
|
|
611
|
+
raise ValueError(f"unknown execution budget {key!r}")
|
|
612
|
+
if type(limit) not in (int, float) or not math.isfinite(limit) or limit <= 0:
|
|
613
|
+
raise ValueError(f"{key} must be a finite positive number")
|
|
614
|
+
if key == "max_model_calls" and type(limit) is not int:
|
|
615
|
+
raise ValueError("max_model_calls must be an integer")
|
|
616
|
+
current = getattr(config, key)
|
|
617
|
+
setattr(config, key, min(limit, current) if current is not None else limit)
|
|
618
|
+
unknown = set(runtime or {}) - set(RUN_KEYS)
|
|
619
|
+
if unknown:
|
|
620
|
+
raise ValueError(f"a conversation's own runtime keys are {', '.join(RUN_KEYS)}, not {sorted(unknown)}")
|
|
621
|
+
runtime = dict(runtime or {})
|
|
622
|
+
learn = runtime.pop("learn", None)
|
|
623
|
+
runtime.pop("agents", None)
|
|
624
|
+
managed = runtime.pop("managed_workspace", False)
|
|
625
|
+
if type(managed) is not bool:
|
|
626
|
+
raise ValueError("managed_workspace must be a boolean")
|
|
627
|
+
if managed:
|
|
628
|
+
self.workspaces.provider(kind).validate_managed(kind)
|
|
629
|
+
profile_skills = profiles()[profile].get("skills") if profile and execution is not None else None
|
|
630
|
+
if (runtime or learn
|
|
631
|
+
or profile is not None and (execution is None or profile_skills)):
|
|
632
|
+
raise ValueError("A managed workspace requires a prompt-only profile without runtime overrides")
|
|
633
|
+
config.runtime = {**config.runtime, **runtime}
|
|
634
|
+
if library is not None:
|
|
635
|
+
from harness.runtime.learning.learner import settings as library_settings
|
|
636
|
+
if not isinstance(library, dict) or not library.get("path"):
|
|
637
|
+
raise ValueError("library requires an explicit path and learning settings")
|
|
638
|
+
library_settings(library)
|
|
639
|
+
config.runtime = {**config.runtime, "library": dict(library)}
|
|
640
|
+
name = runs.new_name()
|
|
641
|
+
directory = self.conversations_dir / name
|
|
642
|
+
if learn is not None and learn is not False:
|
|
643
|
+
if library is None:
|
|
644
|
+
config.runtime = {**config.runtime, "library": {"path": str(directory / "library"),
|
|
645
|
+
"learn": "on", "reflect": True}}
|
|
646
|
+
config = self.learning(config, learn)
|
|
647
|
+
if managed:
|
|
648
|
+
config.runtime = {**config.runtime, "library": None, "agent_skills": [], "think_while_acting": False}
|
|
649
|
+
if reasoning_effort:
|
|
650
|
+
config.main = {**config.main, "reasoning_effort": reasoning_effort}
|
|
651
|
+
elif reasoning_effort == "":
|
|
652
|
+
config.main.pop("reasoning_effort", None)
|
|
653
|
+
options, metadata = self.workspaces.bind(kind, directory, request)
|
|
654
|
+
conversation = TaskRun(config, 0, directory, interactive=True,
|
|
655
|
+
confirmation=confirmation_policy(confirmation), instruction=text,
|
|
656
|
+
agents=None if managed else self.sub_agents(server, kind, assistant=True), **self._models)
|
|
657
|
+
from ..extensions import hosts
|
|
658
|
+
|
|
659
|
+
conversation.workspace_kind = kind
|
|
660
|
+
conversation.workspace_options = options
|
|
661
|
+
if not managed:
|
|
662
|
+
from harness.runtime.task.environments import Environments
|
|
663
|
+
|
|
664
|
+
place = AttachPlace(self, server, run_name=name)
|
|
665
|
+
place.kind = kind
|
|
666
|
+
conversation.environments = Environments(conversation, place)
|
|
667
|
+
conversation.session_metadata = {"workspace": metadata} if metadata else {}
|
|
668
|
+
if execution is not None:
|
|
669
|
+
conversation.session_metadata = {**getattr(conversation, "session_metadata", {}), "execution": execution}
|
|
670
|
+
conversation.mcp_resources = self._mcp_resources
|
|
671
|
+
conversation.mcp_authorize = self.authorize_mcp
|
|
672
|
+
conversation.mcp_prepare = next((lambda *args, module=module: module.prepare_mcp(self, *args)
|
|
673
|
+
for _, module in hosts() if hasattr(module, "prepare_mcp")), None)
|
|
674
|
+
conversation.send_message("", files=files)
|
|
675
|
+
meta = {"title": session_title(title or text, 60), "text": text, "created": time.time(), "model": config.main.get("model"),
|
|
676
|
+
"reasoning_effort": config.main.get("reasoning_effort"), "workspace": kind,
|
|
677
|
+
**metadata,
|
|
678
|
+
**({"model_entry": model_entry} if model_entry else {}),
|
|
679
|
+
**({"learning": config.max_wall_seconds / 60} if active.is_active(config.runtime) else {}),
|
|
680
|
+
**({"profile": profile} if profile else {})}
|
|
681
|
+
(directory / "meta.json").write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
|
682
|
+
run = directory.relative_to(server.root).as_posix()
|
|
683
|
+
self._kinds[run] = kind
|
|
684
|
+
# What the next conversation's choice highlights (and session.environment = last takes).
|
|
685
|
+
self.settings.remember("session", "last_environment", kind)
|
|
686
|
+
if metadata.get("folder"):
|
|
687
|
+
self.settings.remember("session", "last_folder", metadata["folder"])
|
|
688
|
+
if frontend is None:
|
|
689
|
+
server.conversations[run] = conversation
|
|
690
|
+
else:
|
|
691
|
+
server.conversations.add(run, conversation, title=meta["title"], frontend=frontend)
|
|
692
|
+
self.starting[run] = "preparing the workspace"
|
|
693
|
+
# Its trace begins now, so the page lists and follows it while the computer is
|
|
694
|
+
# prepared (the first time installs its environment).
|
|
695
|
+
conversation.trace.emit("state", status=conversation.status, reason="preparing the workspace")
|
|
696
|
+
if execution is None:
|
|
697
|
+
conversation.trace.subscribe(self._watcher())
|
|
698
|
+
|
|
699
|
+
def begin():
|
|
700
|
+
recording = None
|
|
701
|
+
workspaces = self.workspaces
|
|
702
|
+
try:
|
|
703
|
+
if conversation._closing:
|
|
704
|
+
raise workspaces.Cancelled()
|
|
705
|
+
local = workspaces.environment(kind)
|
|
706
|
+
if local is not None:
|
|
707
|
+
# No worker: the kind's environment lives in this process (none).
|
|
708
|
+
conversation.env = local
|
|
709
|
+
elif managed:
|
|
710
|
+
lease = workspaces.provider(kind).acquire_managed(
|
|
711
|
+
run, kind, log=lambda message: self._note(run, message),
|
|
712
|
+
evict=lambda runs: self._evict(server, runs, run), cancelled=lambda: conversation._closing)
|
|
713
|
+
conversation.env = conversation._managed_workspace = lease
|
|
714
|
+
else:
|
|
715
|
+
worker = workspaces.acquire(run, kind, log=lambda message: self._note(run, message),
|
|
716
|
+
evict=lambda runs: self._evict(server, runs, run),
|
|
717
|
+
cancelled=lambda: conversation._closing,
|
|
718
|
+
options=conversation.workspace_options)
|
|
719
|
+
conversation.config.environment = {**conversation.config.environment, "endpoint": worker.endpoint}
|
|
720
|
+
if key := getattr(worker, "approval_key", None):
|
|
721
|
+
conversation.env = RemoteEnvironment(worker.endpoint, timeout=600, approval_key=key)
|
|
722
|
+
recording = workspaces.record(directory, kind, conversation.trace)
|
|
723
|
+
if worker.python and worker.python != sys.executable:
|
|
724
|
+
conversation.config.runtime = {**conversation.config.runtime, "python": worker.python}
|
|
725
|
+
thread = self._threads[run] = conversation.start()
|
|
726
|
+
except workspaces.Cancelled:
|
|
727
|
+
workspaces.release(run)
|
|
728
|
+
conversation._set_status("FINISHED", reason="ended before it began")
|
|
729
|
+
return
|
|
730
|
+
except Exception as error:
|
|
731
|
+
if recording is not None:
|
|
732
|
+
recording.stop()
|
|
733
|
+
workspaces.release(run)
|
|
734
|
+
self.starting[run] = f"error: {error}"
|
|
735
|
+
conversation.trace.emit("error", message=f"The workspace could not be prepared: {error}")
|
|
736
|
+
conversation._set_status("ERROR", reason="error")
|
|
737
|
+
return
|
|
738
|
+
finally:
|
|
739
|
+
if not str(self.starting.get(run, "")).startswith("error"):
|
|
740
|
+
self.starting.pop(run, None)
|
|
741
|
+
# The workspace is given back when the episode ends.
|
|
742
|
+
thread.join()
|
|
743
|
+
workspaces.release(run)
|
|
744
|
+
if recording is not None:
|
|
745
|
+
# screen.json has the times; the trace has ended.
|
|
746
|
+
recording.stop()
|
|
747
|
+
|
|
748
|
+
threading.Thread(target=begin, name=f"start-{name}", daemon=True).start()
|
|
749
|
+
return run
|
|
750
|
+
|
|
751
|
+
def start_external(self, server, agent, text, files, folder, isolation, frontend, model, effort, *,
|
|
752
|
+
handoff=None, reconnect=None, observe=None, mcp_tools=()):
|
|
753
|
+
from ..core import atomic_write
|
|
754
|
+
from ..extensions import modules
|
|
755
|
+
|
|
756
|
+
cwd = Path(folder).expanduser().resolve() if folder else None
|
|
757
|
+
if cwd is not None and not cwd.is_dir():
|
|
758
|
+
raise ValueError("the project directory does not exist")
|
|
759
|
+
directory = Path(reconnect["directory"]) if reconnect else self.conversations_dir / runs.new_name()
|
|
760
|
+
if mcp_tools and (not isinstance(mcp_tools, (list, tuple))
|
|
761
|
+
or not isinstance(agent, str) or not agent.startswith("acp:")
|
|
762
|
+
or any(name not in ("project_info", "project_diff") for name in mcp_tools)):
|
|
763
|
+
raise ValueError("MCP grants for external sessions are explicit ACP project tool names")
|
|
764
|
+
for module in modules():
|
|
765
|
+
factory = getattr(module, "session_adapter", None)
|
|
766
|
+
adapter = factory(agent, directory, cwd=cwd, isolation=isolation, model=model, effort=effort,
|
|
767
|
+
**({"restore": reconnect["metadata"]} if reconnect else {}),
|
|
768
|
+
**({"observe": observe} if observe else {})) if factory else None
|
|
769
|
+
if adapter is not None:
|
|
770
|
+
break
|
|
771
|
+
else:
|
|
772
|
+
raise ValueError(f"no enabled session adapter for {agent!r}")
|
|
773
|
+
|
|
774
|
+
if observe:
|
|
775
|
+
from .sessions import history
|
|
776
|
+
|
|
777
|
+
index = server.conversations.index
|
|
778
|
+
known = server.conversations.sessions()
|
|
779
|
+
known += history(index, skip={row["id"] for row in known}) if index else []
|
|
780
|
+
keys = ("adapter_id", "account_scope", "external_id")
|
|
781
|
+
for row in known:
|
|
782
|
+
if all(row["metadata"].get(key) == adapter.session_metadata.get(key) for key in keys):
|
|
783
|
+
(directory / "events.jsonl").unlink()
|
|
784
|
+
directory.rmdir()
|
|
785
|
+
return row["run"]
|
|
786
|
+
run = directory.relative_to(server.root).as_posix()
|
|
787
|
+
adapter.instruction = text
|
|
788
|
+
if mcp_tools:
|
|
789
|
+
adapter.mcp_tools = tuple(mcp_tools)
|
|
790
|
+
if handoff:
|
|
791
|
+
adapter.session_metadata["handoff_from"] = handoff
|
|
792
|
+
if reconnect:
|
|
793
|
+
server.conversations.reconnect(reconnect, adapter)
|
|
794
|
+
else:
|
|
795
|
+
atomic_write(directory / "meta.json", json.dumps({"title": session_title(text or agent, 60),
|
|
796
|
+
"created": time.time()}))
|
|
797
|
+
server.conversations.add(run, adapter, title=session_title(text or agent, 60), frontend=frontend)
|
|
798
|
+
adapter.trace.subscribe(self._watcher())
|
|
799
|
+
adapter.identity_changed = lambda: server.conversations.save_metadata(run)
|
|
800
|
+
adapter.start(text, files)
|
|
801
|
+
return run
|
|
802
|
+
|
|
803
|
+
# Records after which the user is needed in the chat: the agent waits for an approval,
|
|
804
|
+
# or it stopped on an error. And the end of the agent's turn (an answer, a question, its
|
|
805
|
+
# task done, the budget used up), unless the agent kept the screen (stay_on_screen).
|
|
806
|
+
NEEDS_THE_USER = ("confirmation_request", "error", "kernel_died", "external_notice", "external_question")
|
|
807
|
+
TURN_ENDS = ("message", "finish", "budget")
|
|
808
|
+
|
|
809
|
+
def _watcher(self):
|
|
810
|
+
"""A conversation's watcher (a subscriber of its trace): brings the app's window to
|
|
811
|
+
the front when the conversation needs the user (only where run() set focus_chat:
|
|
812
|
+
the app the user opened)."""
|
|
813
|
+
turn = {"stay": False}
|
|
814
|
+
|
|
815
|
+
def watch(record: dict) -> None:
|
|
816
|
+
event = record.get("event")
|
|
817
|
+
if record.get("replay"):
|
|
818
|
+
return
|
|
819
|
+
if event == "stay_on_screen":
|
|
820
|
+
turn["stay"] = True
|
|
821
|
+
elif event == "user_message":
|
|
822
|
+
turn["stay"] = False
|
|
823
|
+
needed = event in self.NEEDS_THE_USER or (
|
|
824
|
+
event == "state" and record.get("status") == "IDLE" and record.get("reason") in self.TURN_ENDS
|
|
825
|
+
and not turn["stay"])
|
|
826
|
+
if needed and self.focus_chat is not None:
|
|
827
|
+
threading.Thread(target=self.focus_chat, name="show-chat", daemon=True).start()
|
|
828
|
+
|
|
829
|
+
return watch
|
|
830
|
+
|
|
831
|
+
def sub_agents(self, server, kind: str | None, assistant: bool = False) -> Agents:
|
|
832
|
+
"""The sub-agents of a session `server` runs, in workspaces of this pool: of any kind
|
|
833
|
+
this machine serves for the assistant's conversations (each kind has its
|
|
834
|
+
configuration), else (an experiment's session) of the session's own kind only."""
|
|
835
|
+
workspaces = self.available_workspaces()
|
|
836
|
+
# (A sub-agent works somewhere: never in the kind without an environment.)
|
|
837
|
+
served = tuple(name for name in workspaces.kinds() if workspaces.environment(name) is None) if workspaces is not None else ()
|
|
838
|
+
kinds = tuple(served) if assistant else ((kind,) if kind in served else ())
|
|
839
|
+
return Agents(PoolPlace(self, server, kinds, assistant), sessions=server.conversations,
|
|
840
|
+
windows=workspaces.windows() if workspaces is not None else None,
|
|
841
|
+
max_depth=self.settings.get()["limits"]["agent_depth"])
|
|
842
|
+
|
|
843
|
+
def _evict(self, server, runs, run) -> bool:
|
|
844
|
+
"""Make room for `run`: end the conversation among `runs` that has waited longest
|
|
845
|
+
for the user (IDLE after its turn); its workspace comes back when its episode ends.
|
|
846
|
+
Whether one was ended (none is while all of them work)."""
|
|
847
|
+
with self._reclaiming:
|
|
848
|
+
idle = []
|
|
849
|
+
for other in runs:
|
|
850
|
+
conversation = server.conversations.get(other)
|
|
851
|
+
if other == run or conversation is None or conversation.status != "IDLE" or conversation._closing:
|
|
852
|
+
continue
|
|
853
|
+
# IDLE before its first turn too, while its workspace starts: only a turn
|
|
854
|
+
# that ended waits for the user.
|
|
855
|
+
since = getattr(conversation, "waiting_since", None)
|
|
856
|
+
if since is None:
|
|
857
|
+
continue
|
|
858
|
+
idle.append((since, other, conversation))
|
|
859
|
+
if not idle:
|
|
860
|
+
return False
|
|
861
|
+
_, other, conversation = min(idle, key=lambda item: item[0])
|
|
862
|
+
self._note(run, "ending the conversation that waited longest, for its workspace")
|
|
863
|
+
conversation.trace.emit("workspace_reclaimed", by=run)
|
|
864
|
+
conversation.close()
|
|
865
|
+
return True
|
|
866
|
+
|
|
867
|
+
def _note(self, run, message):
|
|
868
|
+
self.starting[run] = str(message)
|
|
869
|
+
|
|
870
|
+
def authorize_mcp(self, config, tool=None):
|
|
871
|
+
from ..services.connectors import authorize_connector
|
|
872
|
+
|
|
873
|
+
authorize_connector(self.settings.get(), self.credentials, config, tool)
|
|
874
|
+
|
|
875
|
+
def mcp_servers(self) -> dict:
|
|
876
|
+
"""{name: client config} of the MCP servers the packages' host modules connect for the
|
|
877
|
+
conversations (`mcp_servers(app)`: the app's connectors)."""
|
|
878
|
+
from ..extensions import hosts
|
|
879
|
+
from ..packages import activate
|
|
880
|
+
|
|
881
|
+
from ..services.connectors import configured_servers
|
|
882
|
+
servers = configured_servers(self.settings.get(), self.credentials)
|
|
883
|
+
catalog_connectors = [row for row in self.settings.get().get("connectors", [])
|
|
884
|
+
if row.get("enabled", True) and row.get("catalog")]
|
|
885
|
+
if catalog_connectors and not any(hasattr(module, "mcp_servers") for _, module in hosts()):
|
|
886
|
+
self.packages.ensure("commands", "app")
|
|
887
|
+
activate(self.packages)
|
|
888
|
+
for _, module in hosts():
|
|
889
|
+
connect = getattr(module, "mcp_servers", None)
|
|
890
|
+
if connect is not None:
|
|
891
|
+
servers.update(connect(self))
|
|
892
|
+
return servers
|
|
893
|
+
|
|
894
|
+
def close(self):
|
|
895
|
+
if self._workspaces is not None:
|
|
896
|
+
self._workspaces.close()
|
|
897
|
+
from ..extensions import modules
|
|
898
|
+
|
|
899
|
+
for module in modules():
|
|
900
|
+
closing = getattr(module, "close_app", None)
|
|
901
|
+
if closing is not None:
|
|
902
|
+
closing(self)
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
class AttachPlace(Attaching):
|
|
906
|
+
"""What the session host gives a conversation that asks for another environment
|
|
907
|
+
(runtime/task/environments.py): a workspace of the app's pools, under the user's
|
|
908
|
+
settings environments.attach and its rules."""
|
|
909
|
+
|
|
910
|
+
def __init__(self, app: TaskHost, server, run_name: str):
|
|
911
|
+
self.app, self.server, self.run_name = app, server, run_name
|
|
912
|
+
|
|
913
|
+
def kinds(self):
|
|
914
|
+
workspaces = self.app.workspaces
|
|
915
|
+
return {row["value"]: row for row in workspaces.environments()
|
|
916
|
+
if workspaces.environment(row["value"]) is None}
|
|
917
|
+
|
|
918
|
+
def level(self, kind, runtime):
|
|
919
|
+
settings = self.app.settings
|
|
920
|
+
values = settings.get()["environments"]
|
|
921
|
+
rule = next((row for row in values["rules"] if row.get("kind") == kind), None)
|
|
922
|
+
# Skipping confirmations is the user's own switch for their real mouse and keyboard:
|
|
923
|
+
# this run's level, else the one they saved (never the schema's default).
|
|
924
|
+
physical = (runtime.get("physical") or {}).get("level") or settings.remembered("physical", "level")
|
|
925
|
+
return (rule["level"] if rule else values["attach"]), physical == "allow"
|
|
926
|
+
|
|
927
|
+
def begin(self, conversation, kind, folder, cancelled):
|
|
928
|
+
from harness.runtime.decision.prompts import assemble_prompt, features_for
|
|
929
|
+
from harness.runtime.task.environments import Refused
|
|
930
|
+
from ..bench import bench_spec, declares_channels
|
|
931
|
+
|
|
932
|
+
app, workspaces = self.app, self.app.workspaces
|
|
933
|
+
try:
|
|
934
|
+
workspaces.require_choices(kind, conversation.config.runtime)
|
|
935
|
+
except ChoiceRequired as error:
|
|
936
|
+
raise Refused(f"{kind} needs the user's own choice first ({error.choice['section']}."
|
|
937
|
+
f"{error.choice['key']}: {error.choice['title']}). Tell them to set it in the settings; "
|
|
938
|
+
"go on without it meanwhile.") from None
|
|
939
|
+
key = f"{self.run_name}+{kind}"
|
|
940
|
+
directory = Path(conversation.directory) / "environments" / kind
|
|
941
|
+
options, metadata = workspaces.bind(kind, directory, {"folder": folder} if folder else {})
|
|
942
|
+
values = app.settings.get()
|
|
943
|
+
tree = app.conversation_tree(values, kind)
|
|
944
|
+
spec = bench_spec(tree["bench"])
|
|
945
|
+
provider = workspaces.provider(kind)
|
|
946
|
+
skills = list(dict.fromkeys([*provider.builtin_skills(kind), *provider.extra_skills(kind)]))
|
|
947
|
+
runtime = (tree["overrides"]["agent"].get(spec.kind) or {}).get("runtime") or {}
|
|
948
|
+
prompt = assemble_prompt(tree["overrides"]["agent"]["prompt"][spec.kind], skills,
|
|
949
|
+
features=features_for(runtime, declares_channels(spec), embodiment=spec.kind),
|
|
950
|
+
embodiment=spec.kind, own=True)
|
|
951
|
+
app.packages.ensure("benches", workspaces.bench(kind), log=lambda message: None)
|
|
952
|
+
worker = workspaces.acquire(key, kind, log=lambda message: app._note(key, message),
|
|
953
|
+
evict=lambda runs: app._evict(self.server, runs, key), cancelled=cancelled,
|
|
954
|
+
**({"options": options} if options else {}))
|
|
955
|
+
app.starting.pop(key, None)
|
|
956
|
+
env = RemoteEnvironment(worker.endpoint, timeout=600, approval_key=getattr(worker, "approval_key", None))
|
|
957
|
+
return {"env": env, "embodiment": spec.kind, "task": "free", "skills": skills, "prompt": prompt,
|
|
958
|
+
"metadata": metadata, "release": lambda: workspaces.release(key)}
|
|
959
|
+
|
|
960
|
+
def agents(self):
|
|
961
|
+
from harness.runtime.decision.prompts import assemble_prompt, features_for
|
|
962
|
+
from ..bench import bench_spec, declares_channels
|
|
963
|
+
|
|
964
|
+
values = self.app.settings.get()
|
|
965
|
+
return {"mode": values["session"]["agents"], "depth": values["limits"]["agent_depth"],
|
|
966
|
+
"prompt": self._agents_prompt(values)}
|
|
967
|
+
|
|
968
|
+
def _agents_prompt(self, values):
|
|
969
|
+
from harness.runtime.decision.prompts import assemble_prompt, features_for
|
|
970
|
+
from ..bench import bench_spec, declares_channels
|
|
971
|
+
|
|
972
|
+
kind = getattr(self, "kind", None)
|
|
973
|
+
try:
|
|
974
|
+
tree = self.app.conversation_tree(values, kind) if kind else None
|
|
975
|
+
if tree is None:
|
|
976
|
+
return ""
|
|
977
|
+
spec = bench_spec(tree["bench"])
|
|
978
|
+
runtime = (tree["overrides"]["agent"].get(spec.kind) or {}).get("runtime") or {}
|
|
979
|
+
return assemble_prompt(tree["overrides"]["agent"]["prompt"][spec.kind], ["agents", "environments"],
|
|
980
|
+
features=features_for(runtime, declares_channels(spec), embodiment=spec.kind),
|
|
981
|
+
embodiment=spec.kind, only=["agents"])
|
|
982
|
+
except (ValueError, KeyError, OSError):
|
|
983
|
+
return ""
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
class PoolPlace(Place):
|
|
987
|
+
"""Where the sub-agents of the app's sessions run (runtime/task/delegation.py): each takes a
|
|
988
|
+
workspace of the app's pool, like a conversation, until it ends."""
|
|
989
|
+
|
|
990
|
+
why_not = "this session has no package-provided workspace lease"
|
|
991
|
+
|
|
992
|
+
def __init__(self, app: TaskHost, server, kinds, assistant: bool):
|
|
993
|
+
self.app, self.server, self.kinds, self.assistant = app, server, tuple(kinds), assistant
|
|
994
|
+
|
|
995
|
+
def config(self, parent, kind, model):
|
|
996
|
+
# The assistant's configuration of another kind (or model) is the app's to build.
|
|
997
|
+
if self.assistant and (kind != parent.workspace_kind or model):
|
|
998
|
+
config = self.app.config(model, kind)
|
|
999
|
+
# A sub-agent can propose while working. Its parent reflects on the result.
|
|
1000
|
+
library = config.runtime.get("library")
|
|
1001
|
+
if library:
|
|
1002
|
+
config.runtime = {**config.runtime, "library": {**library, "reflect": False}}
|
|
1003
|
+
return config
|
|
1004
|
+
return None
|
|
1005
|
+
|
|
1006
|
+
def begin(self, child, kind, cancelled):
|
|
1007
|
+
app = self.app
|
|
1008
|
+
app.workspaces.require_choices(kind, child.config.runtime)
|
|
1009
|
+
identity = child.identity or {}
|
|
1010
|
+
run = f"{identity.get('session')}/{identity.get('agent')}"
|
|
1011
|
+
options, metadata = app.workspaces.bind(kind, child.directory, {}, child.parent)
|
|
1012
|
+
child.workspace_kind, child.workspace_options = kind, options
|
|
1013
|
+
child.session_metadata = {"workspace": metadata} if metadata else {}
|
|
1014
|
+
worker = app.workspaces.acquire(run, kind, log=lambda message: app._note(run, message),
|
|
1015
|
+
evict=lambda runs: app._evict(self.server, runs, run), cancelled=cancelled,
|
|
1016
|
+
**({"options": options} if options else {}))
|
|
1017
|
+
app.starting.pop(run, None)
|
|
1018
|
+
app._kinds[run] = kind
|
|
1019
|
+
child.config.environment = {**child.config.environment, "endpoint": worker.endpoint}
|
|
1020
|
+
if key := getattr(worker, "approval_key", None):
|
|
1021
|
+
child.env = RemoteEnvironment(worker.endpoint, timeout=600, approval_key=key)
|
|
1022
|
+
if worker.python and worker.python != sys.executable:
|
|
1023
|
+
child.config.runtime = {**child.config.runtime, "python": worker.python}
|
|
1024
|
+
return lambda: app.workspaces.release(run)
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def profile_paths() -> dict:
|
|
1028
|
+
from ..extensions import modules
|
|
1029
|
+
|
|
1030
|
+
found = {}
|
|
1031
|
+
for module in modules():
|
|
1032
|
+
for name, path in (getattr(module, "profiles", None) or {}).items():
|
|
1033
|
+
found.setdefault(name, (path,))
|
|
1034
|
+
return found
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
def profiles() -> dict:
|
|
1038
|
+
"""The conversation profiles the packages give ({name: path} as `profiles` of their host
|
|
1039
|
+
modules, harness/extensions.py), read: {name: {"description", "skills", "prompt"}}
|
|
1040
|
+
(PROFILE_KEYS; the prompt as its text). The first package to give a name has it."""
|
|
1041
|
+
return {name: load_profile(paths[0]) for name, paths in profile_paths().items()}
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
def load_profile(path) -> dict:
|
|
1045
|
+
"""A conversation profile's file (PROFILE_KEYS), its prompt read; ValueError says what is wrong."""
|
|
1046
|
+
path = Path(path)
|
|
1047
|
+
try:
|
|
1048
|
+
with path.open("rb") as handle:
|
|
1049
|
+
data = tomllib.load(handle)
|
|
1050
|
+
except (OSError, tomllib.TOMLDecodeError) as error:
|
|
1051
|
+
raise ValueError(f"profile {path}: {error}") from None
|
|
1052
|
+
unknown = set(data) - set(PROFILE_KEYS)
|
|
1053
|
+
if unknown:
|
|
1054
|
+
raise ValueError(f"profile {path}: unknown keys {sorted(unknown)} (it has {', '.join(PROFILE_KEYS)})")
|
|
1055
|
+
skills = data.get("skills", [])
|
|
1056
|
+
if not isinstance(skills, list) or not all(isinstance(name, str) for name in skills):
|
|
1057
|
+
raise ValueError(f"profile {path}: skills is a list of skill names")
|
|
1058
|
+
prompt = (path.parent / data["prompt"]).read_text(encoding="utf-8").strip() if data.get("prompt") else ""
|
|
1059
|
+
return {"description": str(data.get("description", "")), "skills": list(skills), "prompt": prompt}
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
class TaskHandler(Handler):
|
|
1063
|
+
# A skill's .zip comes in the body.
|
|
1064
|
+
body_limits = {"/api/app/packages/install": 40 * 1024 * 1024}
|
|
1065
|
+
|
|
1066
|
+
def get_app(self, query):
|
|
1067
|
+
self._json(self.server.app.status())
|
|
1068
|
+
|
|
1069
|
+
def get_app_agents(self, query):
|
|
1070
|
+
from ..extensions import modules
|
|
1071
|
+
|
|
1072
|
+
self._json({"agents": [agent for module in modules()
|
|
1073
|
+
for agent in getattr(module, "agents", lambda: [])()]})
|
|
1074
|
+
|
|
1075
|
+
def get_app_agent_models(self, query):
|
|
1076
|
+
"""Discover the installed adapter's model options without opening a user conversation."""
|
|
1077
|
+
from tempfile import TemporaryDirectory
|
|
1078
|
+
|
|
1079
|
+
from ..extensions import modules
|
|
1080
|
+
|
|
1081
|
+
identifier = (query.get("agent") or [""])[0]
|
|
1082
|
+
for module in modules():
|
|
1083
|
+
factory = getattr(module, "session_adapter", None)
|
|
1084
|
+
if factory and any(agent["id"] == identifier and agent["kind"] == "acp" and agent["installed"]
|
|
1085
|
+
for agent in getattr(module, "agents", lambda: [])()):
|
|
1086
|
+
break
|
|
1087
|
+
else:
|
|
1088
|
+
raise ValueError("choose an installed ACP adapter")
|
|
1089
|
+
|
|
1090
|
+
with TemporaryDirectory() as temporary:
|
|
1091
|
+
folder = Path(temporary)
|
|
1092
|
+
adapter = factory(identifier, folder / "probe", cwd=folder, isolation=None, model=None, effort=None)
|
|
1093
|
+
try:
|
|
1094
|
+
adapter.open("", ())
|
|
1095
|
+
selected = (query.get("model") or [""])[0]
|
|
1096
|
+
if selected:
|
|
1097
|
+
adapter.set_model(model=selected)
|
|
1098
|
+
config = adapter.capabilities.get("config_options") or []
|
|
1099
|
+
option = next((item for item in config if item.get("category") == "model"), {})
|
|
1100
|
+
choices = [choice for item in option.get("options", [])
|
|
1101
|
+
for choice in item.get("options", [item])]
|
|
1102
|
+
models = [{"id": choice["value"], "name": choice.get("name") or choice["value"]}
|
|
1103
|
+
for choice in choices if isinstance(choice.get("value"), str) and choice["value"]]
|
|
1104
|
+
effort = next((item for item in config if item.get("category") == "thought_level"), {})
|
|
1105
|
+
efforts = [choice["value"] for item in effort.get("options", [])
|
|
1106
|
+
for choice in item.get("options", [item])
|
|
1107
|
+
if isinstance(choice.get("value"), str) and choice["value"]]
|
|
1108
|
+
except (RuntimeError, OSError) as error:
|
|
1109
|
+
raise ValueError(str(error)) from error
|
|
1110
|
+
finally:
|
|
1111
|
+
adapter.close()
|
|
1112
|
+
self._json({"models": models, "efforts": efforts})
|
|
1113
|
+
|
|
1114
|
+
def get_app_models(self, query):
|
|
1115
|
+
app = self.server.app
|
|
1116
|
+
self._json({"models": app.models(), "path": str(app.directory / "models.json")})
|
|
1117
|
+
|
|
1118
|
+
def post_app_models(self, body):
|
|
1119
|
+
self._json({"models": self.server.app.models(body)})
|
|
1120
|
+
|
|
1121
|
+
def get_app_models_settings(self, query):
|
|
1122
|
+
self._file(Path(__file__).parents[1] / "builtin" / "model-settings.js", "text/javascript; charset=utf-8")
|
|
1123
|
+
|
|
1124
|
+
def get_app_models_catalog(self, query):
|
|
1125
|
+
identifier = (query.get("provider") or [""])[0]
|
|
1126
|
+
if identifier.startswith("acp:"):
|
|
1127
|
+
return self.get_app_agent_models({**query, "agent": [identifier]})
|
|
1128
|
+
app = self.server.app
|
|
1129
|
+
app.credentials.load()
|
|
1130
|
+
self._json({"models": providers.catalog(app.directory, identifier)})
|
|
1131
|
+
|
|
1132
|
+
def post_app_model(self, body):
|
|
1133
|
+
self._json(self.server.app.set_model(body))
|
|
1134
|
+
|
|
1135
|
+
def post_tasks(self, body):
|
|
1136
|
+
confirmation = {"always": "always", "never": "never"}.get(body.get("confirmation"))
|
|
1137
|
+
self._json({"run": self.server.app.start(self.server, body.get("text"), body.get("model"), confirmation,
|
|
1138
|
+
body.get("workspace") or None, body.get("runtime") or None,
|
|
1139
|
+
body.get("files") or (), body.get("reasoning_effort"),
|
|
1140
|
+
body.get("profile") or None,
|
|
1141
|
+
agent=body.get("agent"), folder=body.get("folder"),
|
|
1142
|
+
isolation=body.get("isolation"), frontend=body.get("frontend"),
|
|
1143
|
+
mcp_tools=body.get("mcp_tools") or (),
|
|
1144
|
+
model_entry=body.get("model_entry"), library=body.get("library"), budget=body.get("budget"))})
|
|
1145
|
+
|
|
1146
|
+
def post_conversations_handoff(self, body):
|
|
1147
|
+
source = self.server.conversations.resolve(body.get("run"))
|
|
1148
|
+
if source is None:
|
|
1149
|
+
self.server.directory(body.get("run"))
|
|
1150
|
+
source = body["run"]
|
|
1151
|
+
current = self.server.conversations.get(source)
|
|
1152
|
+
metadata = getattr(current, "session_metadata", {})
|
|
1153
|
+
agent, context = body.get("agent"), str(body.get("context") or "").strip()
|
|
1154
|
+
if not context or not isinstance(agent, str) or not agent:
|
|
1155
|
+
raise ValueError("handoff requires an agent and the context approved by the user")
|
|
1156
|
+
if getattr(current, "status", None) in ("RUNNING", "WAITING_FOR_CONFIRMATION", "WAITING_FOR_INPUT"):
|
|
1157
|
+
raise ValueError("stop the active turn before handing off")
|
|
1158
|
+
if agent == "harness":
|
|
1159
|
+
folder = metadata.get("project") or (metadata.get("workspace") or {}).get("folder")
|
|
1160
|
+
run = self.server.app.start(self.server, context, workspace=getattr(current, "workspace_kind", None),
|
|
1161
|
+
folder=folder if getattr(current, "workspace_kind", None) == "project" else None)
|
|
1162
|
+
conversation = self.server.conversations[run]
|
|
1163
|
+
conversation.session_metadata = {"handoff_from": source, "project": metadata.get("project")}
|
|
1164
|
+
self.server.conversations.save_metadata(run)
|
|
1165
|
+
else:
|
|
1166
|
+
run = self.server.app.start_external(
|
|
1167
|
+
self.server, agent, context, (), body.get("folder") or metadata.get("project"),
|
|
1168
|
+
body.get("isolation"), body.get("frontend"), None, None, handoff=source)
|
|
1169
|
+
self._json({"run": run})
|
|
1170
|
+
|
|
1171
|
+
def post_sessions_import(self, body):
|
|
1172
|
+
from ..core import atomic_write
|
|
1173
|
+
from ..extensions import first
|
|
1174
|
+
from .sessions import history
|
|
1175
|
+
|
|
1176
|
+
importer = first("import_session")
|
|
1177
|
+
if importer is None or not isinstance(body.get("file"), str) or not body["file"]:
|
|
1178
|
+
raise ValueError("enable the external-agents package and choose one native transcript")
|
|
1179
|
+
app = self.server.app
|
|
1180
|
+
with app._external_start_lock:
|
|
1181
|
+
directory = app.conversations_dir / runs.new_name()
|
|
1182
|
+
adapter = importer(directory, body.get("provider"), body["file"], body.get("follow") is True)
|
|
1183
|
+
rows = self.server.conversations.sessions()
|
|
1184
|
+
index = self.server.conversations.index
|
|
1185
|
+
rows += history(index, skip={row["id"] for row in rows}) if index else []
|
|
1186
|
+
fields = ("kind", "adapter_id", "external_id", "cwd")
|
|
1187
|
+
duplicate = next((row for row in rows if all(
|
|
1188
|
+
row["metadata"].get(key) == adapter.session_metadata.get(key) for key in fields)), None)
|
|
1189
|
+
if duplicate is not None:
|
|
1190
|
+
# The new trace is still empty and belongs to this request.
|
|
1191
|
+
(directory / "events.jsonl").unlink()
|
|
1192
|
+
directory.rmdir()
|
|
1193
|
+
return self._json({"run": duplicate["run"], "id": duplicate["id"]})
|
|
1194
|
+
name = session_title(f"{body['provider']} {adapter.session_metadata['external_id']}", 60)
|
|
1195
|
+
atomic_write(directory / "meta.json", json.dumps({"title": name, "created": time.time()}))
|
|
1196
|
+
run = directory.relative_to(self.server.root).as_posix()
|
|
1197
|
+
identifier = self.server.conversations.add(run, adapter, title=name, frontend="import")
|
|
1198
|
+
adapter.trace.subscribe(app._watcher())
|
|
1199
|
+
adapter.start("", ())
|
|
1200
|
+
self._json({"run": run, "id": identifier})
|
|
1201
|
+
|
|
1202
|
+
def post_sessions_discover(self, body):
|
|
1203
|
+
from ..extensions import first
|
|
1204
|
+
|
|
1205
|
+
discover = first("discover_sessions")
|
|
1206
|
+
agent = str(body.get("agent") or "")
|
|
1207
|
+
if discover is None or not agent or not (body.get("folder") or agent.startswith("cloud:")):
|
|
1208
|
+
raise ValueError("choose a configured agent and project directory")
|
|
1209
|
+
self._json(discover(agent, body.get("folder"), body.get("cursor")))
|
|
1210
|
+
|
|
1211
|
+
def post_sessions_observe(self, body):
|
|
1212
|
+
agent, identifier = body.get("agent"), body.get("external_id")
|
|
1213
|
+
if (not isinstance(agent, str) or not agent.startswith(("cloud:", "acp:")) or not isinstance(identifier, str)
|
|
1214
|
+
or not identifier or len(identifier) > 256):
|
|
1215
|
+
raise ValueError("choose an ACP or cloud adapter and an external session ID")
|
|
1216
|
+
with self.server.app._external_start_lock:
|
|
1217
|
+
run = self.server.app.start_external(self.server, agent, "", (), body.get("folder"), None,
|
|
1218
|
+
body.get("frontend"), None, None, observe=identifier)
|
|
1219
|
+
self._json({"run": run})
|
|
1220
|
+
|
|
1221
|
+
def post_conversations_reconnect(self, body):
|
|
1222
|
+
from .sessions import history
|
|
1223
|
+
|
|
1224
|
+
if body.get("released") is not True:
|
|
1225
|
+
raise ValueError("confirm the previous controller has stopped before reconnecting")
|
|
1226
|
+
app = self.server.app
|
|
1227
|
+
with app._external_start_lock:
|
|
1228
|
+
active = self.server.conversations.sessions()
|
|
1229
|
+
index = self.server.conversations.index
|
|
1230
|
+
rows = active + (history(index, skip={row["id"] for row in active}) if index else [])
|
|
1231
|
+
row = next((row for row in rows if body.get("run") in (row["run"], row["id"])), None)
|
|
1232
|
+
if row is None or row["live"]:
|
|
1233
|
+
raise ValueError("the original session must be known and disconnected")
|
|
1234
|
+
metadata = row["metadata"]
|
|
1235
|
+
name = body.get("agent") or metadata.get("adapter_id")
|
|
1236
|
+
if not isinstance(name, str) or not name.startswith("acp:") or not metadata.get("external_id"):
|
|
1237
|
+
raise ValueError("original session recovery needs an ACP adapter and native session ID")
|
|
1238
|
+
if metadata.get("kind") == "acp" and name != metadata.get("adapter_id"):
|
|
1239
|
+
raise ValueError("use the original adapter to reconnect an ACP session")
|
|
1240
|
+
if metadata.get("kind") not in ("acp", "observed"):
|
|
1241
|
+
raise ValueError("this source does not support ACP recovery")
|
|
1242
|
+
run = app.start_external(self.server, name, "", (), metadata.get("cwd"), None,
|
|
1243
|
+
row["frontend"], None, None, reconnect=row)
|
|
1244
|
+
self._json({"run": run, "id": row["id"]})
|
|
1245
|
+
|
|
1246
|
+
def get_app_screen(self, query):
|
|
1247
|
+
run = (query.get("run") or [""])[0] or None
|
|
1248
|
+
try:
|
|
1249
|
+
image = self.server.app.workspaces.screen(run)
|
|
1250
|
+
except (OSError, ValueError, KeyError) as error:
|
|
1251
|
+
return self._error(HTTPStatus.SERVICE_UNAVAILABLE, f"no screen: {error}")
|
|
1252
|
+
if image is None:
|
|
1253
|
+
return self._error(HTTPStatus.SERVICE_UNAVAILABLE, "no workspace of this conversation is running")
|
|
1254
|
+
self._send(HTTPStatus.OK, image, "image/jpeg")
|
|
1255
|
+
|
|
1256
|
+
def get_app_environments(self, query):
|
|
1257
|
+
self._json(self.server.app.environments((query.get("model_entry") or [""])[0] or None))
|
|
1258
|
+
|
|
1259
|
+
def get_app_settings(self, query):
|
|
1260
|
+
from ..settings import described
|
|
1261
|
+
|
|
1262
|
+
self._json({"values": self.server.app.settings.get(), "schema": described()})
|
|
1263
|
+
|
|
1264
|
+
def post_app_settings(self, body):
|
|
1265
|
+
self._json({"values": self.server.app.settings.update(body)})
|
|
1266
|
+
|
|
1267
|
+
def get_app_learning(self, query):
|
|
1268
|
+
self._json(self.server.app.progress(self.server, (query.get("run") or [""])[0]))
|
|
1269
|
+
|
|
1270
|
+
def get_app_skills(self, query):
|
|
1271
|
+
self._json(self.server.app.skills())
|
|
1272
|
+
|
|
1273
|
+
def post_app_skills_switch(self, body):
|
|
1274
|
+
self._json(self.server.app.switch_skill(str(body.get("name")), bool(body.get("on"))))
|
|
1275
|
+
|
|
1276
|
+
def get_app_packages(self, query):
|
|
1277
|
+
self._json(self.server.app.packages_state())
|
|
1278
|
+
|
|
1279
|
+
def get_app_packages_search(self, query):
|
|
1280
|
+
try:
|
|
1281
|
+
found = self.server.app.packages.search((query.get("q") or [""])[0])
|
|
1282
|
+
self._json({"results": [{**row, "shown": describe(row)} for row in found]})
|
|
1283
|
+
except RegistryError as error:
|
|
1284
|
+
self._json({"results": [], "error": str(error)})
|
|
1285
|
+
|
|
1286
|
+
def get_app_packages_info(self, query):
|
|
1287
|
+
found = self.server.app.packages.info((query.get("name") or [""])[0])
|
|
1288
|
+
self._json({**found, "shown": describe(found)})
|
|
1289
|
+
|
|
1290
|
+
def post_app_packages_install(self, body):
|
|
1291
|
+
self._json(self.server.app.install_packages(body))
|
|
1292
|
+
|
|
1293
|
+
def post_app_packages_remove(self, body):
|
|
1294
|
+
self.server.app.packages.remove([str(body.get("name"))], log=lambda message: None)
|
|
1295
|
+
self._json(self.server.app.packages_state())
|
|
1296
|
+
|
|
1297
|
+
def post_app_packages_update(self, body):
|
|
1298
|
+
self.server.app.packages.update(body.get("names") or [], log=lambda message: None)
|
|
1299
|
+
self._json(self.server.app.packages_state())
|
|
1300
|
+
|
|
1301
|
+
def post_app_packages_enable(self, body):
|
|
1302
|
+
self.server.app.packages.enable(str(body.get("name")), bool(body.get("on")))
|
|
1303
|
+
self._json(self.server.app.packages_state())
|
|
1304
|
+
|
|
1305
|
+
def post_conversations_agents(self, body):
|
|
1306
|
+
"""Switch sub-agents on for a running conversation (the user's own switch)."""
|
|
1307
|
+
self._conversation(body).enable_agents()
|
|
1308
|
+
self._json({"ok": True})
|
|
1309
|
+
|
|
1310
|
+
def post_app_takeover(self, body):
|
|
1311
|
+
self._conversation(body).pause()
|
|
1312
|
+
self._json({"ok": True})
|
|
1313
|
+
|
|
1314
|
+
def post_app_handback(self, body):
|
|
1315
|
+
self._conversation(body).send_message(HANDBACK)
|
|
1316
|
+
self._json({"ok": True})
|
|
1317
|
+
|
|
1318
|
+
|
|
1319
|
+
class TaskServer(Server):
|
|
1320
|
+
"""The GUI's server with the app's routes, over the app's conversations."""
|
|
1321
|
+
|
|
1322
|
+
page = "app.html"
|
|
1323
|
+
handler_class = TaskHandler
|
|
1324
|
+
|
|
1325
|
+
def __init__(self, address, app: TaskHost, token: str | None = None):
|
|
1326
|
+
self.app = app
|
|
1327
|
+
super().__init__(address, app.directory, token=token)
|
|
1328
|
+
|
|
1329
|
+
def sub_agents(self, kind):
|
|
1330
|
+
return self.app.sub_agents(self, kind)
|
|
1331
|
+
|
|
1332
|
+
def model_changed(self, run, changed):
|
|
1333
|
+
self.app.model_changed(self, run, changed)
|
|
1334
|
+
|
|
1335
|
+
def info(self) -> dict:
|
|
1336
|
+
return {**super().info(), "app": True, "handback": HANDBACK}
|
|
1337
|
+
|
|
1338
|
+
def workspace(self, request: dict, experiment):
|
|
1339
|
+
"""A workspace of the kind the conversation asked for (POST /api/conversations {workspace}),
|
|
1340
|
+
from the app's pool, for an experiment of the bench that serves it."""
|
|
1341
|
+
kind = request.get("workspace")
|
|
1342
|
+
if not kind:
|
|
1343
|
+
return None
|
|
1344
|
+
workspaces = self.app.workspaces
|
|
1345
|
+
kind = workspaces.kind(kind)
|
|
1346
|
+
workspaces.require_choices(kind)
|
|
1347
|
+
if workspaces.bench(kind) != experiment.bench:
|
|
1348
|
+
raise ValueError(f"a {kind} workspace runs the {workspaces.bench(kind)} bench; this experiment runs "
|
|
1349
|
+
f"{experiment.bench}")
|
|
1350
|
+
key = f"session-{secrets.token_hex(4)}"
|
|
1351
|
+
worker = workspaces.acquire(key, kind, log=lambda message: None)
|
|
1352
|
+
return {"kind": kind, "endpoint": worker.endpoint,
|
|
1353
|
+
"environment": (RemoteEnvironment(worker.endpoint, timeout=600, approval_key=worker.approval_key)
|
|
1354
|
+
if getattr(worker, "approval_key", None) else None),
|
|
1355
|
+
"python": worker.python if worker.python != sys.executable else None,
|
|
1356
|
+
"release": lambda: workspaces.release(key)}
|