@lmmslab/harness 0.0.0-stage → 0.81.0

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