@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,468 @@
1
+ """Sub-agents: an agent hands parts of its task to agents of its own.
2
+
3
+ An agent's program calls delegate(task, workspace, budget, model) (skills/agents); the
4
+ call reaches the conversation that runs the program as a note (runtime/execution/control.py), and
5
+ the session's Agents (this module) starts a sub-agent: a conversation of its own
6
+ (runtime/conversation.py) with the task as its instruction, written under its parent's
7
+ directory (agents/<id>/: the trace is a tree of directories), registered in the session's
8
+ tree (host/sessions.py) and run in a workspace the session's Place gives it:
9
+
10
+ new a workspace of its own, of the parent's kind (or "browser", "desktop", "apps",
11
+ "display": a new one of that kind)
12
+ share the windows the parent holds now are handed over (the session's window
13
+ ownership, `windows`: the computer package's WindowOwners.transfer): the
14
+ sub-agent owns them while it runs, the parent cannot use them meanwhile, and
15
+ they come back to the parent when the sub-agent ends.
16
+ It still runs in a worker of its own (a worker serves one episode); its
17
+ instruction names the windows it was handed.
18
+
19
+ A sub-agent may also be another harness's agent (delegate(..., agent="claude-code")): a kind
20
+ a package declares ([provides] agents of its package.toml, installed on first use as
21
+ packages.auto_install says). Its class runs that agent on the task in its own directory,
22
+ writes what it does to its own trace (so the timeline shows it as the sub-agent's lane) and
23
+ charges what it spends with `charge(calls, cost)`; it needs no workspace, and answers what
24
+ Agents asks of a sub-agent (status, summary, result, question, directory, trace,
25
+ agents_usage, start, send_message, close, charge_up).
26
+
27
+ Budgets are charged up the tree: a sub-agent's budget (model calls, cost, seconds) is
28
+ at most what its parent has left, and every call and dollar it spends counts against
29
+ its parent's budget, and its parent's, as it is spent. An agent at the session's
30
+ nesting depth (`max_depth`, default 1: the main agent's sub-agents start none) cannot
31
+ delegate.
32
+
33
+ A sub-agent works on its task alone: its <finish> (or a used-up budget) ends it, and its
34
+ report (status, result, usage, files) goes back to its parent, which wait_agents() gives
35
+ it and whose trace keeps it (agent_report). A plain reply is a question to its parent:
36
+ it waits, and wait_agents() returns, until the parent answers with send_agent(). The
37
+ user may talk to any agent of the session from any frontend; what an agent asks the user
38
+ (an approval, physical input) is listed with its session, where every frontend answers it.
39
+ """
40
+
41
+ from copy import copy
42
+ from pathlib import Path
43
+ import threading
44
+ import time
45
+
46
+ from harness.runtime.status import live
47
+
48
+
49
+
50
+ # The main agent's sub-agents start none of their own.
51
+ DEFAULT_DEPTH = 1
52
+ # What a sub-agent's workspace is (or a workspace kind: a new one of that kind).
53
+ WORKSPACES = ("new", "share")
54
+ # A budget's keys, and the names they may be given by.
55
+ BUDGET_KEYS = {"calls": "calls", "model_calls": "calls", "cost": "cost", "cost_usd": "cost",
56
+ "seconds": "seconds", "time": "seconds"}
57
+ # Files of an agent's directory that are the harness's, not results.
58
+ OWN_FILES = {"events.jsonl", "manifest.json", "summary.json", "kernel.log", "meta.json"}
59
+
60
+ # Added to a sub-agent's system prompt in place of the interactive one.
61
+ SUB_AGENT_PROMPT = (
62
+ "\n\nYou are a sub-agent: another agent (the one that started you) gave you this task, and it waits for "
63
+ "your result. When the task is done, <finish> with what it needs to know (what you found or did, and where "
64
+ "any files are); that ends your work and your result goes back to it. To ask it something, reply in plain "
65
+ "text without any block: you wait for its answer, which reaches you as \"Message from the agent that "
66
+ "started you: ...\". The user may also write to you (\"Message from the user: ...\")."
67
+ )
68
+ NO_DEEPER = " You cannot start sub-agents of your own."
69
+
70
+
71
+ class Place:
72
+ """Where a session's sub-agents run: what the server that runs the session gives them.
73
+ This one has no workspaces to give (a conversation run in a process of its own, or by
74
+ a server without a workspace pool); the app and the session host give workspaces from
75
+ their pool (app.py)."""
76
+
77
+ # The workspace kinds it can start.
78
+ kinds = ()
79
+ why_not = ("this conversation has no workspace pool to start sub-agents in: run it from the app or the "
80
+ "session host")
81
+
82
+ def config(self, parent, kind: str, model: str | None):
83
+ """A sub-agent's configuration in a workspace of `kind` with `model`: None for its
84
+ parent's (copied)."""
85
+ return None
86
+
87
+ def begin(self, child, kind: str, cancelled) -> callable:
88
+ """Give `child` a workspace of `kind` (its endpoint in child.config.environment; may
89
+ wait for one) and return what gives it back."""
90
+ raise ValueError(self.why_not)
91
+
92
+
93
+ class Child:
94
+ """A sub-agent as its session's Agents keeps it."""
95
+
96
+ def __init__(self, agent: str, conversation, parent, *, task, workspace, kind, budget, windows):
97
+ self.id = agent
98
+ self.conversation = conversation
99
+ self.parent = parent
100
+ self.task = task
101
+ self.workspace = workspace
102
+ self.kind = kind
103
+ self.budget = budget
104
+ self.windows = windows
105
+ self.run = None
106
+ self.started = time.time()
107
+ self.report = None
108
+ self.cancel_requested = False
109
+ self.error = None
110
+
111
+
112
+ def _clean_budget(budget) -> dict:
113
+ if budget is None:
114
+ return {}
115
+ if isinstance(budget, (int, float)) and not isinstance(budget, bool):
116
+ budget = {"calls": budget}
117
+ if not isinstance(budget, dict):
118
+ raise ValueError("budget is {\"calls\", \"cost\", \"seconds\"} (or a number of calls)")
119
+ clean = {}
120
+ for key, value in budget.items():
121
+ name = BUDGET_KEYS.get(str(key))
122
+ if name is None:
123
+ raise ValueError(f"a budget has calls, cost and seconds, not {key!r}")
124
+ if value is None:
125
+ continue
126
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
127
+ raise ValueError(f"budget {key} is a positive number")
128
+ clean[name] = int(value) if name == "calls" else float(value)
129
+ return clean
130
+
131
+
132
+ def left(conversation) -> dict:
133
+ """What `conversation` has left of its budget: model calls (in its turn), dollars (None:
134
+ no limit) and seconds, its sub-agents' spending counted."""
135
+ config = conversation.config
136
+ calls = int(config.max_model_calls) - int(getattr(conversation, "_iterations", 0) or 0)
137
+ cost = None
138
+ if config.max_cost_usd is not None:
139
+ spent = (conversation.summary or {}).get("cost_usd", 0.0) + conversation.agents_usage["cost_usd"]
140
+ cost = float(config.max_cost_usd) - spent
141
+ return {"calls": calls, "cost": cost, "seconds": conversation.seconds_left()}
142
+
143
+
144
+ def external_agent(name: str):
145
+ """The class of the kind of sub-agent `name` a package declares ([provides] agents), its
146
+ package installed first when none provides it (packages.auto_install); ValueError says
147
+ why there is none."""
148
+ import importlib
149
+
150
+ from harness.packages import MissingPackage, ensure
151
+
152
+ try:
153
+ package = ensure("agents", name, log=lambda message: None)
154
+ except MissingPackage as error:
155
+ raise ValueError(f"no agent {name!r}: {error}") from None
156
+ module, _, attribute = package.agents[name].partition(":")
157
+ return getattr(importlib.import_module(module), attribute)
158
+
159
+
160
+ class Agents:
161
+ """The sub-agents of one session (one Agents is shared by all its agents). `place`
162
+ gives them workspaces (Place); `sessions` (host/sessions.py) lists them in the session's
163
+ tree; `windows` is who owns which window of the computer, which `share` hands windows
164
+ over in (held(owner), transfer(window, owner, to): the computer package's WindowOwners;
165
+ None: no windows to share); `max_depth` how deep agents nest."""
166
+
167
+ def __init__(self, place: Place | None = None, *, sessions=None, windows=None, max_depth: int = DEFAULT_DEPTH):
168
+ self.place = place or Place()
169
+ self.sessions = sessions
170
+ self.windows = windows
171
+ self.max_depth = int(max_depth)
172
+ self._children = {}
173
+ self._changed = threading.Condition(threading.RLock())
174
+ self._count = 0
175
+
176
+ # What a running program asks (skills/agents), through its conversation.
177
+
178
+ def handle(self, conversation, request: dict) -> dict:
179
+ """Do what a program of `conversation` asked: {"value": ...} or {"error": ...}."""
180
+ operation = request.get("action")
181
+ try:
182
+ if operation == "delegate":
183
+ value = self.delegate(conversation, request.get("task"), workspace=request.get("workspace") or "new",
184
+ budget=request.get("budget"), model=request.get("model"),
185
+ agent=request.get("agent"), multi_turn=request.get("multi_turn", False))
186
+ elif operation == "wait":
187
+ value = self.wait(conversation, request.get("ids"), timeout=request.get("timeout"),
188
+ told=request.get("own", True), interrupt_at=request.get("interrupt_at"))
189
+ elif operation == "send":
190
+ value = self.send(conversation, request.get("agent"), request.get("text"))
191
+ elif operation == "cancel":
192
+ value = self.cancel(conversation, request.get("agent"))
193
+ elif operation == "list":
194
+ value = {child.id: self.state(child) for child in self.children(conversation)}
195
+ else:
196
+ raise ValueError(f"no operation {operation!r}")
197
+ except (ValueError, RuntimeError, OSError) as error:
198
+ return {"error": str(error)}
199
+ return {"value": value}
200
+
201
+ def children(self, conversation) -> list[Child]:
202
+ """The sub-agents `conversation` started, oldest first."""
203
+ with self._changed:
204
+ return [child for child in self._children.values() if child.parent is conversation]
205
+
206
+ def _mine(self, conversation, agent) -> Child:
207
+ child = self._children.get(str(agent))
208
+ if child is None or child.parent is not conversation:
209
+ raise ValueError(f"you started no sub-agent {agent!r}")
210
+ return child
211
+
212
+ def delegate(self, parent, task, *, workspace="new", budget=None, model=None, agent=None, multi_turn=False) -> str:
213
+ """Start a sub-agent of `parent` on `task` (see the module docstring); its id. `agent`:
214
+ another harness's agent (a kind a package declares) in place of a conversation."""
215
+ from harness.runtime.task.run import TaskRun
216
+
217
+ task = " ".join(str(task or "").split()) if task is not None else ""
218
+ if not task:
219
+ raise ValueError("say what the sub-agent is to do")
220
+ depth = parent.depth + 1
221
+ if depth > self.max_depth:
222
+ raise ValueError(f"agents at depth {parent.depth} cannot start sub-agents (the nesting depth setting is "
223
+ f"{self.max_depth})")
224
+ external = external_agent(str(agent)) if agent is not None else None
225
+ if type(multi_turn) is not bool or (multi_turn and not getattr(external, "followups", False)):
226
+ raise ValueError("multi_turn requires a supported external delegate")
227
+ kind = None if external is not None else parent.workspace_kind if workspace in WORKSPACES else str(workspace)
228
+ if external is not None:
229
+ workspace = str(agent)
230
+ elif workspace not in WORKSPACES and kind not in self.place.kinds:
231
+ raise ValueError(f"workspace is new, share or a kind ({', '.join(self.place.kinds) or 'none here'}), "
232
+ f"not {workspace!r}")
233
+ elif kind is None or kind not in self.place.kinds:
234
+ raise ValueError(self.place.why_not if not self.place.kinds else
235
+ f"this session's workspace ({kind or 'its own worker'}) is not one sub-agents can get "
236
+ f"here ({', '.join(self.place.kinds)})")
237
+ budget = self._budget(parent, _clean_budget(budget))
238
+ session = (parent.identity or {}).get("session")
239
+ windows = []
240
+ with self._changed:
241
+ self._count += 1
242
+ agent = f"a{self._count}"
243
+ while self.sessions is not None and session and self.sessions.resolve(f"{session}/{agent}"):
244
+ self._count += 1
245
+ agent = f"a{self._count}"
246
+ instruction = task
247
+ if workspace == "share":
248
+ windows = self._held(parent)
249
+ instruction += "\n\nResources lent to you until you finish: " + ", ".join(item["label"] for item in windows)
250
+ if external is not None:
251
+ conversation = external(task, Path(parent.directory) / "agents" / agent, budget=budget,
252
+ model=None if model is None else str(model), charge=parent._charge,
253
+ interactive=bool(getattr(parent, "interactive", False)),
254
+ confirmation=getattr(parent, "confirmation", "never"),
255
+ **({"multi_turn": True} if multi_turn else {}))
256
+ else:
257
+ config = self.place.config(parent, kind, model)
258
+ if config is None:
259
+ config = copy(parent.base_config)
260
+ config.main = dict(config.main)
261
+ if model:
262
+ config.main["model"] = str(model)
263
+ config.runtime = dict(config.runtime)
264
+ approvals = parent.config.runtime.get("approvals")
265
+ if approvals:
266
+ config.runtime["approvals"] = dict(approvals)
267
+ config.environment = dict(config.environment)
268
+ config.max_model_calls = budget["calls"]
269
+ config.max_cost_usd = budget["cost"]
270
+ config.max_wall_seconds = budget["seconds"]
271
+ conversation = TaskRun(config, parent.seed, Path(parent.directory) / "agents" / agent,
272
+ chat=parent.agent_chat, verifier=parent.agent_verifier,
273
+ interactive=bool(getattr(parent, "interactive", False)),
274
+ confirmation=parent.confirmation, instruction=instruction,
275
+ parent=parent, agents=self)
276
+ conversation.workspace_kind = kind
277
+ child = Child(agent, conversation, parent, task=task, workspace=workspace, kind=kind, budget=budget,
278
+ windows=[item["id"] for item in windows])
279
+ self._children[agent] = child
280
+ if self.sessions is not None and session:
281
+ child.run = self.sessions.add_agent(session, conversation, agent=agent,
282
+ parent=(parent.identity or {}).get("agent") or "main",
283
+ title=task[:80])
284
+ else:
285
+ child.run = agent
286
+ conversation.identity = {"session": session or "local", "agent": agent,
287
+ "parent": (parent.identity or {}).get("agent") or "main"}
288
+ # The windows are the sub-agent's from now until it ends.
289
+ for item in windows:
290
+ self.windows.transfer(item["id"], parent.identity, conversation.identity)
291
+ conversation.trace.subscribe(lambda record: self._watch(record, child))
292
+ parent.agents_usage["started"] += 1
293
+ parent.trace.emit("agent_delegated", agent=agent, run=child.run, task=task, workspace=workspace, kind=kind,
294
+ budget=budget, model=str(model) if model else None, windows=child.windows,
295
+ directory=str(Path(conversation.directory).resolve()))
296
+ threading.Thread(target=self._run, args=(child,), name=f"agent-{agent}", daemon=True).start()
297
+ return agent
298
+
299
+ def _budget(self, parent, wanted: dict) -> dict:
300
+ have = left(parent)
301
+ if have["calls"] < 1:
302
+ raise ValueError("you have no model calls left to give a sub-agent")
303
+ if have["cost"] is not None and have["cost"] <= 0:
304
+ raise ValueError("you have no budget left to give a sub-agent")
305
+ if have["seconds"] < 1:
306
+ raise ValueError("you have no time left to give a sub-agent")
307
+ return {"calls": min(wanted.get("calls", have["calls"]), have["calls"]),
308
+ "cost": (wanted.get("cost") if have["cost"] is None else min(wanted.get("cost", have["cost"]),
309
+ have["cost"])),
310
+ "seconds": round(min(wanted.get("seconds", have["seconds"]), have["seconds"]), 1)}
311
+
312
+ def _held(self, parent) -> list[dict]:
313
+ """The windows `parent` owns now (share hands them over)."""
314
+ if not parent.identity:
315
+ raise ValueError("share hands over the windows of an agent of a session; this conversation is in none")
316
+ held = self.windows.held(parent.identity) if self.windows is not None else []
317
+ if not held:
318
+ raise ValueError("you hold no resources to share now: use workspace=\"new\"")
319
+ return held
320
+
321
+ def _run(self, child: Child) -> None:
322
+ conversation = child.conversation
323
+ release = None
324
+ try:
325
+ if child.kind is not None:
326
+ release = self.place.begin(conversation, child.kind, cancelled=lambda: conversation._closing)
327
+ if conversation._closing:
328
+ conversation._set_status("FINISHED", reason="ended before it began")
329
+ else:
330
+ conversation.start().join()
331
+ except Exception as error:
332
+ child.error = f"{type(error).__name__}: {error}"
333
+ conversation.trace.emit("error", message=f"The sub-agent's workspace could not be prepared: {error}")
334
+ conversation._set_status("ERROR", reason="error")
335
+ finally:
336
+ if release is not None:
337
+ try:
338
+ release()
339
+ except Exception:
340
+ pass
341
+ self._ended(child)
342
+
343
+ def _ended(self, child: Child) -> None:
344
+ """A sub-agent ended: its windows go back, its last spending is charged, and its report
345
+ goes to its parent."""
346
+ conversation, parent = child.conversation, child.parent
347
+ if child.windows and conversation.identity and parent.identity:
348
+ for window in child.windows:
349
+ try:
350
+ self.windows.transfer(window, conversation.identity, parent.identity)
351
+ except ValueError:
352
+ pass # it gave the window up (or its worker's process ended): it is free
353
+ conversation.charge_up()
354
+ report = self.state(child, ended=True)
355
+ invalidate = getattr(parent, "invalidate_lookahead", None)
356
+ if invalidate is not None:
357
+ invalidate()
358
+ parent.trace.emit("agent_report", **report)
359
+ with self._changed:
360
+ child.report = report
361
+ self._changed.notify_all()
362
+ # Its entry in the parent's program ends (runtime/execution/entries.py).
363
+ kernel = getattr(parent, "kernel", None)
364
+ if kernel is not None:
365
+ kernel.agent_ended(child.id, report, cancelled=child.cancel_requested)
366
+
367
+ def state(self, child: Child, ended: bool = False) -> dict:
368
+ """A sub-agent as its parent sees it: its status (running, waiting for approval, asks
369
+ you (question), finished, closed, error, ...), its result or question, what it spent
370
+ and its files."""
371
+ if child.report is not None:
372
+ return child.report
373
+ conversation = child.conversation
374
+ summary = conversation.summary or {}
375
+ status = conversation.status
376
+ if ended or not live(status):
377
+ word = summary.get("status") or ("error" if status == "ERROR" else "finished")
378
+ elif status == "IDLE" and conversation.question:
379
+ word = "asks"
380
+ elif status == "IDLE" and getattr(conversation, "multi_turn", False) and conversation.result is not None:
381
+ word = "ready"
382
+ else:
383
+ word = {"WAITING_FOR_CONFIRMATION": "waiting for approval", "PAUSED": "paused"}.get(status, "running")
384
+ directory = Path(conversation.directory)
385
+ files = sorted(path.relative_to(directory).as_posix() for path in directory.rglob("*")
386
+ if path.is_file() and path.name not in OWN_FILES and "agents" not in
387
+ path.relative_to(directory).parts[:1]) if directory.is_dir() and word != "running" else []
388
+ error = summary.get("error") or child.error
389
+ return {"agent": child.id, "run": child.run, "status": word, "result": conversation.result,
390
+ "question": conversation.question if word == "asks" else None,
391
+ **({"error": error} if error and word == "error" else {}),
392
+ "model_calls": summary.get("model_calls", 0) + conversation.agents_usage["model_calls"],
393
+ "cost_usd": round(summary.get("cost_usd", 0.0) + conversation.agents_usage["cost_usd"], 6),
394
+ "seconds": round(time.time() - child.started, 1), "directory": str(directory.resolve()),
395
+ "files": files[:50]}
396
+
397
+ def _watch(self, record: dict, child: Child) -> None:
398
+ if record.get("event") == "state":
399
+ with self._changed:
400
+ self._changed.notify_all()
401
+ if record.get("reason") == "external_turn":
402
+ child.parent.trace.emit("agent_report", **self.state(child))
403
+
404
+ def wake(self):
405
+ with self._changed:
406
+ self._changed.notify_all()
407
+
408
+ def wait(self, parent, ids=None, timeout=None, told=True, *, interrupt_at=None) -> dict:
409
+ """Wait until each of `parent`'s sub-agents `ids` (default: all it started) has ended
410
+ or asks it something, at most `timeout` seconds (None: as long as it takes), or until
411
+ `parent` is paused or closed, or (`told`: the program's own code waits) a message
412
+ for it comes; their states."""
413
+ children = self.children(parent) if not ids else [self._mine(parent, agent) for agent in
414
+ ([ids] if isinstance(ids, str) else ids)]
415
+ if not children:
416
+ raise ValueError("you started no sub-agents")
417
+ if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout < 0):
418
+ raise ValueError("timeout is a number of seconds (or None)")
419
+ began = time.monotonic()
420
+ deadline = None if timeout is None else began + float(timeout)
421
+
422
+ def settled(child):
423
+ return child.report is not None or self.state(child)["status"] in ("asks", "ready")
424
+
425
+ if interrupt_at is None:
426
+ interrupt_at = getattr(parent, "_interruptions", 0)
427
+ with self._changed:
428
+ while not all(settled(child) for child in children):
429
+ if parent._closing or parent._pause or (told and getattr(parent, "_interruptions", 0) != interrupt_at) or (
430
+ deadline is not None and time.monotonic() >= deadline):
431
+ break
432
+ self._changed.wait(None if deadline is None else max(0, deadline - time.monotonic()))
433
+ states = {child.id: self.state(child) for child in children}
434
+ parent.trace.emit("agent_waited", agents=list(states), timeout=timeout,
435
+ seconds=round(time.monotonic() - began, 1),
436
+ states={agent: item["status"] for agent, item in states.items()})
437
+ return states
438
+
439
+ def send(self, parent, agent, text) -> dict:
440
+ """A message from `parent` to its sub-agent `agent`, for its next model call."""
441
+ child = self._mine(parent, agent)
442
+ text = str(text or "").strip()
443
+ if not text:
444
+ raise ValueError("say something")
445
+ if child.report is not None:
446
+ raise ValueError(f"sub-agent {agent} has ended ({child.report['status']})")
447
+ child.conversation.send_message(text, sender="parent")
448
+ parent.trace.emit("agent_sent", agent=child.id, text=text)
449
+ return {"ok": True}
450
+
451
+ def cancel(self, parent, agent, wait: float = 30.0) -> dict:
452
+ """End `parent`'s sub-agent `agent` (and its own); its report."""
453
+ child = self._mine(parent, agent)
454
+ parent.trace.emit("agent_cancelled", agent=child.id)
455
+ child.cancel_requested = True
456
+ child.conversation.close()
457
+ with self._changed:
458
+ self._changed.wait_for(lambda: child.report is not None, wait)
459
+ return self.state(child)
460
+
461
+ def end_all(self, parent, wait: float = 30.0) -> None:
462
+ """`parent` ends: so do its sub-agents (theirs first)."""
463
+ children = [child for child in self.children(parent) if child.report is None]
464
+ for child in children:
465
+ child.cancel_requested = True
466
+ child.conversation.close()
467
+ with self._changed:
468
+ self._changed.wait_for(lambda: all(child.report is not None for child in children), wait)