@yahyahammad/venastine 0.3.8 → 0.3.9

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 (128) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2030 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1034 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +528 -528
  14. package/bin/venastine.py +71 -71
  15. package/cli_commands.py +838 -835
  16. package/config.yaml +13 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +971 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2715 -2715
  28. package/core/commands.py +460 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +234 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +458 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +108 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +733 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +295 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +267 -267
  102. package/tools/builtin/arxiv.py +681 -681
  103. package/tools/builtin/fetch_url.py +371 -371
  104. package/tools/builtin/file_ops.py +720 -720
  105. package/tools/builtin/geometry.py +184 -184
  106. package/tools/builtin/load_skill.py +76 -76
  107. package/tools/builtin/pin.py +227 -227
  108. package/tools/builtin/probability_stats.py +224 -224
  109. package/tools/builtin/project_docs.py +464 -464
  110. package/tools/builtin/remember.py +175 -175
  111. package/tools/builtin/shell.py +980 -980
  112. package/tools/builtin/todo.py +149 -149
  113. package/tools/builtin/web_search.py +328 -328
  114. package/tools/context.py +159 -159
  115. package/tools/isolation.py +387 -387
  116. package/tools/registry.py +1242 -1242
  117. package/tui/app.py +8318 -8307
  118. package/tui/app.tcss +747 -739
  119. package/tui/commands.py +26 -26
  120. package/tui/diffs.py +286 -286
  121. package/tui/history.py +128 -128
  122. package/tui/hosted_driver.py +102 -102
  123. package/tui/markdown.py +1329 -1329
  124. package/tui/meters.py +364 -364
  125. package/tui/ravens.py +146 -146
  126. package/tui/screens.py +1255 -1197
  127. package/tui/themes.py +599 -599
  128. package/tui/widgets.py +3813 -3796
@@ -1,472 +1,472 @@
1
- """
2
- agents/subagent_tool.py
3
-
4
- ROADMAP_v2 §18, D6: the model-initiated half of agent invocation. The
5
- model spawns a named agent to handle a task; the run is scope-capped by
6
- the parent's ToolContext (C6), depth-limited (C3), and returns only the
7
- subagent's final text -- distilled, matching the pipeline's own "don't
8
- share raw history" principle.
9
-
10
- The handler declares `parent_context` and `parent_run`, which
11
- tools/registry.dispatch() injects by signature inspection (§18). The
12
- Rev. 1 sketch's `depth: int` parameter and `allowed_tools=` kwarg are
13
- both gone: depth lives on ToolContext.subagent_depth, and §15 replaced
14
- allowed_tools with context= everywhere.
15
-
16
- §47 added two more declared names, `memory` and `call_id`, and they are
17
- what the child's thread records as its PARENT. The spawn already returned
18
- `subagent_thread_id` to the model, so the edge existed -- as a repr
19
- inside a JSON blob in one message row, which nothing could query and
20
- replay skips. Stored on the child's own row, it survives the process and
21
- lets a `▸ spawn_subagent` line still open its run tomorrow.
22
-
23
- core.loop is imported INSIDE run(), not at module top: tools/registry.py
24
- imports this module to register it, and core.loop imports tools.registry
25
- -- a top-level import here would close that cycle at import time.
26
- """
27
-
28
- import config
29
- from core import agent_activity
30
- from storage import THREAD_KIND_SUBAGENT
31
- from tools.context import ToolContext
32
-
33
- TOOL_SCHEMA = {
34
- "name": "spawn_subagent",
35
- "description": "Spawn a named agent to handle a self-contained task "
36
- "and return its final answer. The subagent runs in its "
37
- "own thread with its own methodology and a tool set "
38
- "capped by your current restrictions. Use it when a "
39
- "task matches a listed agent's specialty; do the work "
40
- "yourself otherwise.",
41
- "input_schema": {
42
- "type": "object",
43
- "properties": {
44
- "agent_name": {
45
- "type": "string",
46
- "description": "Agent name exactly as listed in the "
47
- "Available agents catalog.",
48
- },
49
- "task": {
50
- "type": "string",
51
- "description": "The self-contained task description the "
52
- "subagent receives as its first message.",
53
- },
54
- },
55
- "required": ["agent_name", "task"],
56
- },
57
- }
58
-
59
-
60
- def has_agents() -> bool:
61
- """ToolSpec.available_check (TECHNICAL_DEBT 13, batch 110).
62
-
63
- The schema above tells the model to name an "Agent name exactly as
64
- listed in the Available agents catalog". With no SPAWNABLE agent
65
- discovered there is no such catalog, so the tool's only possible
66
- answer is `Unknown agent` -- a schema the model can see, choose, and
67
- never get value from, which is the fetch_url damage class §15 exists
68
- to fix. `load_skill.has_skills` is the same declaration for the same
69
- reason, and `pin`, `unpin` and `remember` each carry one.
70
-
71
- Reads the SAME function prompt assembly uses (agent_catalog_text, via
72
- prompts/system_prompts.with_catalogs) rather than a parallel check, so
73
- "advertised" and "catalogued" cannot drift apart. That is the whole
74
- point of the choice: batch 51 shipped two spawnable agents, so the
75
- live instance of this was gone and only the asymmetry remained.
76
-
77
- ROSTER-WIDE, NOT PER-RUN, because `available_check` takes no context.
78
- It answers "is there any spawnable agent at all". A run whose
79
- `spawn_targets` empties the list is still the business of
80
- `refusal_reason` and of `agent_catalog_text(targets)`, which read the
81
- same restriction from the two sides it has.
82
-
83
- Imported inside the function for the reason the module docstring
84
- gives about core.loop: tools/registry.py imports this module, and
85
- prompts/system_prompts.py imports the registry.
86
- """
87
- from prompts import system_prompts
88
-
89
- return bool(system_prompts.agent_catalog_text())
90
-
91
-
92
- def refusal_reason(params: dict, context=None):
93
- """Why this spawn would be refused, or None (§32 A7, #70).
94
-
95
- ONE function, TWO callers: the loop consults it before deciding to
96
- ask, and run() below calls it before doing anything. That is the
97
- point rather than a tidiness -- the sign-off shown and the error
98
- returned have to be about the same refusal, and the way to
99
- guarantee it is to have one place that decides.
100
-
101
- THE ORDER MATCHES run()'s ORIGINAL ORDER, depth before params
102
- before name, because these strings are what the model already
103
- sees and reordering them would change a live contract for no
104
- reason.
105
-
106
- Returns None for anything it cannot settle in advance -- an agent
107
- that exists and a depth that is fine can still fail once it runs,
108
- and this function is deliberately not in the business of
109
- predicting that.
110
- """
111
- parent = context or ToolContext()
112
- if parent.subagent_depth >= config.SUBAGENT_MAX_DEPTH:
113
- return (f"Maximum subagent nesting depth "
114
- f"({config.SUBAGENT_MAX_DEPTH}) reached")
115
- # Depth first, which is the order the docstring above pins; then
116
- # whether there are arguments to read at all (batch 146). A refusal
117
- # rather than a raise, because this runs above dispatch()'s
118
- # containment -- tools/base.py carries the one copy of what that costs.
119
- if not isinstance(params, dict):
120
- return "spawn_subagent requires an object of arguments."
121
- name = params.get("agent_name")
122
- task = params.get("task")
123
- if not name or not task:
124
- return ("spawn_subagent requires both 'agent_name' and "
125
- "'task'.")
126
- from agents.manager import manager
127
-
128
- agent = manager.get(name)
129
- if agent is None:
130
- # "the roster", not "the catalog", and the distinction is the one
131
- # A16 turns on: `manager.get` reads the ROSTER (every agent the
132
- # loader discovered) while `agent_catalog_text()` is the CATALOG
133
- # (the spawnable subset). This message claimed the catalog was the
134
- # membership test for as long as it was not -- so for an agent that
135
- # was in the roster and off the catalog, the catalog's answer was
136
- # "absent" and this function's was "spawn it", and the one string a
137
- # model ever sees about membership described a test that was not
138
- # being run. Defect shape 9 inside the function that owns the
139
- # contract. The wording was wrong whichever way A16 had gone.
140
- return (f"Unknown agent: {name!r} is not one of this harness's "
141
- f"agents.")
142
- # A16 (ROADMAP_v3 §62), which REVERSES §32 A3/A4's "advertisement
143
- # only". Before this, `refusal_reason` never read `spawnable`, so
144
- # `spawn_subagent` would spawn any agent the loader had discovered, by
145
- # name -- including one that A3's asymmetry had deliberately left OFF
146
- # the catalog. A3 argued that a stranger's silence must get the safe
147
- # answer, and the measured consequence of "reads as false" was that the
148
- # agent became INVISIBLE rather than unreachable: a project-tier agent
149
- # omitting the field was absent from the prompt a user might read and
150
- # callable by any text that named it. For the careless author the
151
- # default was safe; for the adversarial one it was the quieter option,
152
- # which is the opposite ranking from the one A3 argues.
153
- #
154
- # BEFORE spawn_targets and after the unknown-agent check: an unknown
155
- # name must still report that it is unknown rather than that it is not
156
- # permitted, and this is a property of the agent being spawned where
157
- # spawn_targets is a property of the parent.
158
- #
159
- # `is not True` rather than `not`, because `None` means undeclared at
160
- # the user and project tiers and A3's reading of silence is unchanged --
161
- # only its consequence is.
162
- if getattr(agent, "spawnable", None) is not True:
163
- return (f"{name!r} is not a spawnable agent. It can be used by hand "
164
- f"with /agent, which is unaffected.")
165
- # LAST, because the checks above are the live contract this
166
- # docstring describes and an unknown name must still report that it
167
- # is unknown rather than that it is not permitted.
168
- #
169
- # A REFUSAL RATHER THAN A NARROWING, which is the whole point of the
170
- # field. C6 caps the child's tools at the parent's, so without this
171
- # a parent that should not be delegating the work at all gets a
172
- # child that runs anyway with pieces missing -- `plan` spawning
173
- # `build` came back unable to `write` or `edit`, and neither side
174
- # could tell. Refusing says so in a sentence the model can act on,
175
- # and A7 means it says so BEFORE a human is asked to sign anything.
176
- if parent.spawn_targets is not None and name not in parent.spawn_targets:
177
- return (f"{name!r} is not an agent this one may spawn. "
178
- f"Available here: "
179
- f"{', '.join(sorted(parent.spawn_targets)) or 'none'}.")
180
- return None
181
-
182
-
183
- def approval_notice(params: dict, context=None) -> str:
184
- """What approving this spawn actually authorises (§18 S1).
185
-
186
- The params alone say only which agent and which task. What the user
187
- is really being asked is whether that agent may run a set of tools
188
- without asking again -- so the prompt has to name them. Computed
189
- through manager.candidate_approvals(), the SAME helper that builds
190
- the grant, so the list shown and the list granted cannot drift.
191
- """
192
- from agents.manager import manager
193
-
194
- agent = manager.get(params.get("agent_name", ""))
195
- if agent is None:
196
- return ""
197
- child = manager.child_context(agent, context or ToolContext())
198
- candidates = manager.candidate_approvals(child)
199
- if not candidates:
200
- return f"{agent.name} needs no approval-gated tools."
201
- listed = "\n".join(f" - {name}" for name in candidates)
202
- return (f"{agent.name} may use these without asking again, for the "
203
- f"rest of this turn:\n{listed}")
204
-
205
-
206
- def request_payload(params: dict, context=None) -> dict:
207
- """What the sign-off question is ABOUT (§23 AC1b).
208
-
209
- Carries the agent's name as the memo `subject` and the candidate tool
210
- list as the options the user picks from. Computed through
211
- manager.candidate_approvals(), the SAME helper approval_notice uses
212
- and the same one that used to build the grant wholesale -- so the list
213
- shown, the list offered and the list granted cannot drift apart.
214
-
215
- Lives on the TOOL rather than in core/loop.py because which tools a
216
- child could reach is agents/manager.py's knowledge. The loop asks the
217
- registry for this the same way it asks for the notice.
218
- """
219
- from agents.manager import manager
220
-
221
- agent = manager.get(params.get("agent_name", ""))
222
- if agent is None:
223
- return {}
224
- child = manager.child_context(agent, context or ToolContext())
225
- return {"subject": agent.name, "agent": agent.name,
226
- "candidates": manager.candidate_approvals(child)}
227
-
228
-
229
- def _child_pair(agent, parent_run) -> tuple:
230
- """`(model, provider)` a spawned child runs on.
231
-
232
- THREE TIERS, read top to bottom (ROADMAP_v3 §57, SM2):
233
-
234
- * The agent's OWN pin, which is its identity: an agent that names a
235
- model for being a different model must get it. A HALF pin keeps
236
- today's rule exactly -- the named half, the other from the parent
237
- run -- and opts the agent out of `/submodel` WHOLE (SM6), because
238
- a pinned model name against the submodel's provider is a pair
239
- nobody chose.
240
- * `/submodel`'s pair, for an agent that pins neither half. It beats
241
- the parent run's pair at every depth (SM7): it is the model for
242
- subagents as a class, and a parent's pin is that parent's identity
243
- rather than its children's. Read at SPAWN time, so a choice made
244
- between turns reaches the next spawn without a restart.
245
- * The parent run's pair, then the harness default -- what every
246
- spawn got before §57, and still what one gets with nothing set.
247
- """
248
- from core import pipeline_models
249
- from core.loop import DEFAULT_PROVIDER
250
-
251
- if not agent.pins_model:
252
- chosen = pipeline_models.resolve("subagent")
253
- if chosen is not None:
254
- return chosen["model"], chosen["provider_name"]
255
- model = agent.model or (parent_run.model if parent_run else None) \
256
- or config.MODEL_NAME
257
- provider = agent.provider \
258
- or (parent_run.provider_name if parent_run else None) \
259
- or DEFAULT_PROVIDER
260
- return model, provider
261
-
262
-
263
- def run(params: dict, parent_context=None, parent_run=None,
264
- response_channel=None, signoff=None, activity=None,
265
- memory=None, call_id=None, cancel=None) -> dict:
266
- from agents.manager import manager
267
- from core.loop import (
268
- DEFAULT_SYSTEM_PROMPT,
269
- RunAgentLoop,
270
- with_persona,
271
- )
272
-
273
- parent = parent_context or ToolContext()
274
- # §32 A7. The SAME function the loop consulted before deciding
275
- # whether to ask and dispatch() applied before its approval gate,
276
- # so all three agree about what is being refused. It covers the
277
- # depth limit, the missing-params case (.get not [], because no
278
- # provider validates tool inputs against the schema and a bare
279
- # KeyError escapes _run and takes down the turn) and the
280
- # unknown-agent case.
281
- #
282
- # Kept here even though dispatch now short-circuits first: this is
283
- # the backstop for a caller that reaches run() directly, which is
284
- # every test in the suite and anything future that composes agents
285
- # without going through the registry. Two layers, one predicate.
286
- refusal = refusal_reason(params, parent)
287
- if refusal:
288
- return {"error": refusal}
289
-
290
- name = params.get("agent_name")
291
- task = params.get("task")
292
- agent = manager.get(name)
293
-
294
- child = manager.child_context(agent, parent)
295
- # The channel is inherited, and it is NOT redundant with the grant.
296
- # The grant covers what approval_needed(name, {}) can enumerate; a
297
- # path-dependent approval_check (file_ops outside the workspace, shell
298
- # on a non-inert command) only resolves once the call exists, so those
299
- # still have to reach a human mid-run. Without the channel the child
300
- # ran headless and lost every approval-gated tool silently.
301
- #
302
- # §23 AC1b: the grant is the SUBSET the user ticked, not every
303
- # candidate. §18 shipped this all-or-nothing (S1) because a boolean
304
- # channel could not carry a list out and a subset back; approving a
305
- # spawn therefore authorised the child's entire approval-gated set.
306
- # `signoff` is injected by dispatch() and is None only when nothing
307
- # asked -- a headless run, where the child gets no grant anyway.
308
- granted = set(signoff) if signoff else set()
309
-
310
- model, provider = _child_pair(agent, parent_run)
311
- # The parent's level, unvalidated here on purpose: a child on its own
312
- # pin or on the /submodel pair may be a model that refuses it, and
313
- # core.client.effort_for drops a level the receiving model does not
314
- # list at the send, with a warning. One validator at the wire rather
315
- # than a guess at each site that can change the model.
316
- effort = parent_run.effort if parent_run else None
317
-
318
- # Batch 59. THE SPAN AND THE PASS-DOWN ARE ONE CHANGE, and the
319
- # pass-down is the half that does the work: `activity=activity` on the
320
- # call below is what lets the child's OWN spawn_subagent open a span
321
- # too, so a shell sees depth 2 rather than only the spawn it can
322
- # already infer from tool_call_start. Without it this reports exactly
323
- # what the TUI knew before the batch.
324
- #
325
- # A context manager rather than a pair of calls, because the exit has
326
- # to happen when the child RAISES -- a provider error inside a
327
- # subagent must not leave a row on screen describing a run that is
328
- # over. run_agent_conversation does not contain its own exceptions
329
- # (core/events.py: "exceptions raised mid-loop propagate naturally"),
330
- # so this is a reachable path rather than a defensive one.
331
- #
332
- # `child.subagent_depth` and not a local count: C3 already maintains
333
- # that number and a second one would be free to disagree with it.
334
- from core import shell_sessions
335
-
336
- # ROADMAP_v3 §49 (SS9). Everything the child's first turn and any wake
337
- # turn after it share. A wake IS that run continuing -- the same
338
- # prompt, context, channel, grant and sink -- so the two calls take one
339
- # dict rather than two argument lists that could drift apart.
340
- common = dict(
341
- model=model,
342
- provider_name=provider,
343
- max_steps=agent.max_steps or config.MAX_ITERATIONS,
344
- context=child,
345
- effort=effort,
346
- # `child`, not the agent's own context: C6 intersects with
347
- # the parent, so a parent that excluded spawn_subagent must not
348
- # have the catalog re-invite its child to spawn one (review
349
- # f19).
350
- # #68: the child's own facts, not the parent's. A subagent
351
- # spawned from a headless run inherits no channel, so its
352
- # catalogs must be decided by what IT can call -- the same
353
- # values handed to run_agent_conversation below.
354
- system_prompt=manager.system_prompt_for(
355
- agent, with_persona(DEFAULT_SYSTEM_PROMPT, model, provider),
356
- context=child,
357
- callable_only=response_channel is None,
358
- granted=granted),
359
- response_channel=response_channel,
360
- granted_tools=granted if (response_channel is not None
361
- and granted) else None,
362
- # The recursion. Inherited exactly as response_channel is, and
363
- # for the same reason: the child is a run in its own right and
364
- # whatever is watching this stack is watching that one too.
365
- activity=activity,
366
- # ROADMAP_v3 §61 (CN7). Inherited exactly as `activity` above is,
367
- # and for a sharper version of the same reason: the child is a
368
- # run in its own right, and a stop aimed at the turn that spawned
369
- # it has to reach it, or the parent waits out a child it has
370
- # already asked to end.
371
- cancel=cancel,
372
- )
373
- with agent_activity.span(activity, agent.name, child.subagent_depth,
374
- call_id) as span:
375
- # ROADMAP_v3 §49 (SS17). The child is a wake CONSUMER: a session it
376
- # starts is reported inside this call and nowhere else, which is
377
- # what makes starting one allowed at all in this run.
378
- with shell_sessions.consuming():
379
- try:
380
- response = RunAgentLoop.run_agent_conversation(
381
- user_goal=task,
382
- # §27 AC1. A spawned agent's thread is not a
383
- # conversation anyone will resume, and one goal-mode
384
- # turn can spawn several.
385
- thread_kind=THREAD_KIND_SUBAGENT,
386
- # §47. WHO spawned this thread, stored on the child's
387
- # own row.
388
- #
389
- # `memory` and `call_id` are injected by dispatch() the
390
- # same way the values in `common` are -- the parent's
391
- # live ConversationMemory, and the model's id for THIS
392
- # call. Both are None on a path that reaches run()
393
- # directly (every test that calls it by hand), and the
394
- # child is then simply a thread with no recorded
395
- # parent, which is what it was before that batch.
396
- #
397
- # THE CALL ID IS WHAT MAKES THE EDGE SPECIFIC. One turn
398
- # can spawn `explore` three times, so the agent name
399
- # identifies the roster entry and not the run; the call
400
- # id is the only thing that ties one child to one
401
- # `▸ spawn_subagent` line.
402
- thread_parent=getattr(memory, "thread_id", None),
403
- thread_parent_call=call_id,
404
- thread_agent=agent.name,
405
- **common,
406
- )
407
- # SS9. The child does not answer its parent while its own
408
- # background sessions are still running: it sleeps HERE, is
409
- # woken here, and returns once there is nothing left to
410
- # report. D6 is untouched -- what crosses back is still one
411
- # distilled answer.
412
- response = _sleep_for_sessions(response, common)
413
- except BaseException:
414
- # A child that RAISED has no thread to report to, and its
415
- # sessions would outlive the run that started them --
416
- # holding slots against the process-wide cap for as long
417
- # as their timeouts. The SPAN is the handle: it is frozen
418
- # and carries no address, so the child's thread id may
419
- # never have reached this frame, while every session
420
- # records the span it was started inside.
421
- shell_sessions.sessions.kill_by_span(
422
- span.id, shell_sessions.KILL_OWNER_FAILED)
423
- raise
424
- return {
425
- "result": response.text,
426
- "subagent_thread_id": str(response.thread_id),
427
- }
428
-
429
-
430
- def _sleep_for_sessions(response, common: dict):
431
- """Stay inside the spawn while the child's sessions report (SS9, SS20).
432
-
433
- Returns the response the child ends on: its first answer when it
434
- started no sessions, or the answer to the last wake it was given.
435
-
436
- THE LIMIT IS WHY THIS TERMINATES. A subagent has no user to type a
437
- message, so the consecutive-wake count it shares with every other
438
- owner can never be reset from outside -- past it the manager stops
439
- handing out batches and holds them instead. SS20 makes that the end of
440
- the run rather than a wait for something that cannot happen: the
441
- remaining sessions are stopped, and the results of stopping them are
442
- what the one final wake carries.
443
- """
444
- from core import shell_sessions
445
-
446
- sessions = shell_sessions.sessions
447
- thread_id = response.thread_id
448
- while True:
449
- batch = sessions.wait_for_wake(thread_id)
450
- if batch:
451
- response = _wake(response, thread_id, batch, common)
452
- continue
453
- if not sessions.suspended(thread_id):
454
- return response
455
- sessions.kill_owned(thread_id, shell_sessions.KILL_WAKE_LIMIT)
456
- held = sessions.take_held(thread_id)
457
- if held:
458
- response = _wake(response, thread_id, held, common)
459
- # Anything that last turn started has nobody left to report to,
460
- # and nothing after this point will ever wake this thread again.
461
- sessions.kill_owned(thread_id, shell_sessions.KILL_WAKE_LIMIT)
462
- return response
463
-
464
-
465
- def _wake(response, thread_id, events, common: dict):
466
- """One wake turn in the child's own thread, under its own run."""
467
- from core.loop import RunAgentLoop
468
- from core.session_wake import build_wake
469
-
470
- text, record = build_wake(events)
471
- return RunAgentLoop.wake_conversation(
472
- thread_id=thread_id, text=text, harness=record, **common)
1
+ """
2
+ agents/subagent_tool.py
3
+
4
+ ROADMAP_v2 §18, D6: the model-initiated half of agent invocation. The
5
+ model spawns a named agent to handle a task; the run is scope-capped by
6
+ the parent's ToolContext (C6), depth-limited (C3), and returns only the
7
+ subagent's final text -- distilled, matching the pipeline's own "don't
8
+ share raw history" principle.
9
+
10
+ The handler declares `parent_context` and `parent_run`, which
11
+ tools/registry.dispatch() injects by signature inspection (§18). The
12
+ Rev. 1 sketch's `depth: int` parameter and `allowed_tools=` kwarg are
13
+ both gone: depth lives on ToolContext.subagent_depth, and §15 replaced
14
+ allowed_tools with context= everywhere.
15
+
16
+ §47 added two more declared names, `memory` and `call_id`, and they are
17
+ what the child's thread records as its PARENT. The spawn already returned
18
+ `subagent_thread_id` to the model, so the edge existed -- as a repr
19
+ inside a JSON blob in one message row, which nothing could query and
20
+ replay skips. Stored on the child's own row, it survives the process and
21
+ lets a `▸ spawn_subagent` line still open its run tomorrow.
22
+
23
+ core.loop is imported INSIDE run(), not at module top: tools/registry.py
24
+ imports this module to register it, and core.loop imports tools.registry
25
+ -- a top-level import here would close that cycle at import time.
26
+ """
27
+
28
+ import config
29
+ from core import agent_activity
30
+ from storage import THREAD_KIND_SUBAGENT
31
+ from tools.context import ToolContext
32
+
33
+ TOOL_SCHEMA = {
34
+ "name": "spawn_subagent",
35
+ "description": "Spawn a named agent to handle a self-contained task "
36
+ "and return its final answer. The subagent runs in its "
37
+ "own thread with its own methodology and a tool set "
38
+ "capped by your current restrictions. Use it when a "
39
+ "task matches a listed agent's specialty; do the work "
40
+ "yourself otherwise.",
41
+ "input_schema": {
42
+ "type": "object",
43
+ "properties": {
44
+ "agent_name": {
45
+ "type": "string",
46
+ "description": "Agent name exactly as listed in the "
47
+ "Available agents catalog.",
48
+ },
49
+ "task": {
50
+ "type": "string",
51
+ "description": "The self-contained task description the "
52
+ "subagent receives as its first message.",
53
+ },
54
+ },
55
+ "required": ["agent_name", "task"],
56
+ },
57
+ }
58
+
59
+
60
+ def has_agents() -> bool:
61
+ """ToolSpec.available_check (TECHNICAL_DEBT 13, batch 110).
62
+
63
+ The schema above tells the model to name an "Agent name exactly as
64
+ listed in the Available agents catalog". With no SPAWNABLE agent
65
+ discovered there is no such catalog, so the tool's only possible
66
+ answer is `Unknown agent` -- a schema the model can see, choose, and
67
+ never get value from, which is the fetch_url damage class §15 exists
68
+ to fix. `load_skill.has_skills` is the same declaration for the same
69
+ reason, and `pin`, `unpin` and `remember` each carry one.
70
+
71
+ Reads the SAME function prompt assembly uses (agent_catalog_text, via
72
+ prompts/system_prompts.with_catalogs) rather than a parallel check, so
73
+ "advertised" and "catalogued" cannot drift apart. That is the whole
74
+ point of the choice: batch 51 shipped two spawnable agents, so the
75
+ live instance of this was gone and only the asymmetry remained.
76
+
77
+ ROSTER-WIDE, NOT PER-RUN, because `available_check` takes no context.
78
+ It answers "is there any spawnable agent at all". A run whose
79
+ `spawn_targets` empties the list is still the business of
80
+ `refusal_reason` and of `agent_catalog_text(targets)`, which read the
81
+ same restriction from the two sides it has.
82
+
83
+ Imported inside the function for the reason the module docstring
84
+ gives about core.loop: tools/registry.py imports this module, and
85
+ prompts/system_prompts.py imports the registry.
86
+ """
87
+ from prompts import system_prompts
88
+
89
+ return bool(system_prompts.agent_catalog_text())
90
+
91
+
92
+ def refusal_reason(params: dict, context=None):
93
+ """Why this spawn would be refused, or None (§32 A7, #70).
94
+
95
+ ONE function, TWO callers: the loop consults it before deciding to
96
+ ask, and run() below calls it before doing anything. That is the
97
+ point rather than a tidiness -- the sign-off shown and the error
98
+ returned have to be about the same refusal, and the way to
99
+ guarantee it is to have one place that decides.
100
+
101
+ THE ORDER MATCHES run()'s ORIGINAL ORDER, depth before params
102
+ before name, because these strings are what the model already
103
+ sees and reordering them would change a live contract for no
104
+ reason.
105
+
106
+ Returns None for anything it cannot settle in advance -- an agent
107
+ that exists and a depth that is fine can still fail once it runs,
108
+ and this function is deliberately not in the business of
109
+ predicting that.
110
+ """
111
+ parent = context or ToolContext()
112
+ if parent.subagent_depth >= config.SUBAGENT_MAX_DEPTH:
113
+ return (f"Maximum subagent nesting depth "
114
+ f"({config.SUBAGENT_MAX_DEPTH}) reached")
115
+ # Depth first, which is the order the docstring above pins; then
116
+ # whether there are arguments to read at all (batch 146). A refusal
117
+ # rather than a raise, because this runs above dispatch()'s
118
+ # containment -- tools/base.py carries the one copy of what that costs.
119
+ if not isinstance(params, dict):
120
+ return "spawn_subagent requires an object of arguments."
121
+ name = params.get("agent_name")
122
+ task = params.get("task")
123
+ if not name or not task:
124
+ return ("spawn_subagent requires both 'agent_name' and "
125
+ "'task'.")
126
+ from agents.manager import manager
127
+
128
+ agent = manager.get(name)
129
+ if agent is None:
130
+ # "the roster", not "the catalog", and the distinction is the one
131
+ # A16 turns on: `manager.get` reads the ROSTER (every agent the
132
+ # loader discovered) while `agent_catalog_text()` is the CATALOG
133
+ # (the spawnable subset). This message claimed the catalog was the
134
+ # membership test for as long as it was not -- so for an agent that
135
+ # was in the roster and off the catalog, the catalog's answer was
136
+ # "absent" and this function's was "spawn it", and the one string a
137
+ # model ever sees about membership described a test that was not
138
+ # being run. Defect shape 9 inside the function that owns the
139
+ # contract. The wording was wrong whichever way A16 had gone.
140
+ return (f"Unknown agent: {name!r} is not one of this harness's "
141
+ f"agents.")
142
+ # A16 (ROADMAP_v3 §62), which REVERSES §32 A3/A4's "advertisement
143
+ # only". Before this, `refusal_reason` never read `spawnable`, so
144
+ # `spawn_subagent` would spawn any agent the loader had discovered, by
145
+ # name -- including one that A3's asymmetry had deliberately left OFF
146
+ # the catalog. A3 argued that a stranger's silence must get the safe
147
+ # answer, and the measured consequence of "reads as false" was that the
148
+ # agent became INVISIBLE rather than unreachable: a project-tier agent
149
+ # omitting the field was absent from the prompt a user might read and
150
+ # callable by any text that named it. For the careless author the
151
+ # default was safe; for the adversarial one it was the quieter option,
152
+ # which is the opposite ranking from the one A3 argues.
153
+ #
154
+ # BEFORE spawn_targets and after the unknown-agent check: an unknown
155
+ # name must still report that it is unknown rather than that it is not
156
+ # permitted, and this is a property of the agent being spawned where
157
+ # spawn_targets is a property of the parent.
158
+ #
159
+ # `is not True` rather than `not`, because `None` means undeclared at
160
+ # the user and project tiers and A3's reading of silence is unchanged --
161
+ # only its consequence is.
162
+ if getattr(agent, "spawnable", None) is not True:
163
+ return (f"{name!r} is not a spawnable agent. It can be used by hand "
164
+ f"with /agent, which is unaffected.")
165
+ # LAST, because the checks above are the live contract this
166
+ # docstring describes and an unknown name must still report that it
167
+ # is unknown rather than that it is not permitted.
168
+ #
169
+ # A REFUSAL RATHER THAN A NARROWING, which is the whole point of the
170
+ # field. C6 caps the child's tools at the parent's, so without this
171
+ # a parent that should not be delegating the work at all gets a
172
+ # child that runs anyway with pieces missing -- `plan` spawning
173
+ # `build` came back unable to `write` or `edit`, and neither side
174
+ # could tell. Refusing says so in a sentence the model can act on,
175
+ # and A7 means it says so BEFORE a human is asked to sign anything.
176
+ if parent.spawn_targets is not None and name not in parent.spawn_targets:
177
+ return (f"{name!r} is not an agent this one may spawn. "
178
+ f"Available here: "
179
+ f"{', '.join(sorted(parent.spawn_targets)) or 'none'}.")
180
+ return None
181
+
182
+
183
+ def approval_notice(params: dict, context=None) -> str:
184
+ """What approving this spawn actually authorises (§18 S1).
185
+
186
+ The params alone say only which agent and which task. What the user
187
+ is really being asked is whether that agent may run a set of tools
188
+ without asking again -- so the prompt has to name them. Computed
189
+ through manager.candidate_approvals(), the SAME helper that builds
190
+ the grant, so the list shown and the list granted cannot drift.
191
+ """
192
+ from agents.manager import manager
193
+
194
+ agent = manager.get(params.get("agent_name", ""))
195
+ if agent is None:
196
+ return ""
197
+ child = manager.child_context(agent, context or ToolContext())
198
+ candidates = manager.candidate_approvals(child)
199
+ if not candidates:
200
+ return f"{agent.name} needs no approval-gated tools."
201
+ listed = "\n".join(f" - {name}" for name in candidates)
202
+ return (f"{agent.name} may use these without asking again, for the "
203
+ f"rest of this turn:\n{listed}")
204
+
205
+
206
+ def request_payload(params: dict, context=None) -> dict:
207
+ """What the sign-off question is ABOUT (§23 AC1b).
208
+
209
+ Carries the agent's name as the memo `subject` and the candidate tool
210
+ list as the options the user picks from. Computed through
211
+ manager.candidate_approvals(), the SAME helper approval_notice uses
212
+ and the same one that used to build the grant wholesale -- so the list
213
+ shown, the list offered and the list granted cannot drift apart.
214
+
215
+ Lives on the TOOL rather than in core/loop.py because which tools a
216
+ child could reach is agents/manager.py's knowledge. The loop asks the
217
+ registry for this the same way it asks for the notice.
218
+ """
219
+ from agents.manager import manager
220
+
221
+ agent = manager.get(params.get("agent_name", ""))
222
+ if agent is None:
223
+ return {}
224
+ child = manager.child_context(agent, context or ToolContext())
225
+ return {"subject": agent.name, "agent": agent.name,
226
+ "candidates": manager.candidate_approvals(child)}
227
+
228
+
229
+ def _child_pair(agent, parent_run) -> tuple:
230
+ """`(model, provider)` a spawned child runs on.
231
+
232
+ THREE TIERS, read top to bottom (ROADMAP_v3 §57, SM2):
233
+
234
+ * The agent's OWN pin, which is its identity: an agent that names a
235
+ model for being a different model must get it. A HALF pin keeps
236
+ today's rule exactly -- the named half, the other from the parent
237
+ run -- and opts the agent out of `/submodel` WHOLE (SM6), because
238
+ a pinned model name against the submodel's provider is a pair
239
+ nobody chose.
240
+ * `/submodel`'s pair, for an agent that pins neither half. It beats
241
+ the parent run's pair at every depth (SM7): it is the model for
242
+ subagents as a class, and a parent's pin is that parent's identity
243
+ rather than its children's. Read at SPAWN time, so a choice made
244
+ between turns reaches the next spawn without a restart.
245
+ * The parent run's pair, then the harness default -- what every
246
+ spawn got before §57, and still what one gets with nothing set.
247
+ """
248
+ from core import pipeline_models
249
+ from core.loop import DEFAULT_PROVIDER
250
+
251
+ if not agent.pins_model:
252
+ chosen = pipeline_models.resolve("subagent")
253
+ if chosen is not None:
254
+ return chosen["model"], chosen["provider_name"]
255
+ model = agent.model or (parent_run.model if parent_run else None) \
256
+ or config.MODEL_NAME
257
+ provider = agent.provider \
258
+ or (parent_run.provider_name if parent_run else None) \
259
+ or DEFAULT_PROVIDER
260
+ return model, provider
261
+
262
+
263
+ def run(params: dict, parent_context=None, parent_run=None,
264
+ response_channel=None, signoff=None, activity=None,
265
+ memory=None, call_id=None, cancel=None) -> dict:
266
+ from agents.manager import manager
267
+ from core.loop import (
268
+ DEFAULT_SYSTEM_PROMPT,
269
+ RunAgentLoop,
270
+ with_persona,
271
+ )
272
+
273
+ parent = parent_context or ToolContext()
274
+ # §32 A7. The SAME function the loop consulted before deciding
275
+ # whether to ask and dispatch() applied before its approval gate,
276
+ # so all three agree about what is being refused. It covers the
277
+ # depth limit, the missing-params case (.get not [], because no
278
+ # provider validates tool inputs against the schema and a bare
279
+ # KeyError escapes _run and takes down the turn) and the
280
+ # unknown-agent case.
281
+ #
282
+ # Kept here even though dispatch now short-circuits first: this is
283
+ # the backstop for a caller that reaches run() directly, which is
284
+ # every test in the suite and anything future that composes agents
285
+ # without going through the registry. Two layers, one predicate.
286
+ refusal = refusal_reason(params, parent)
287
+ if refusal:
288
+ return {"error": refusal}
289
+
290
+ name = params.get("agent_name")
291
+ task = params.get("task")
292
+ agent = manager.get(name)
293
+
294
+ child = manager.child_context(agent, parent)
295
+ # The channel is inherited, and it is NOT redundant with the grant.
296
+ # The grant covers what approval_needed(name, {}) can enumerate; a
297
+ # path-dependent approval_check (file_ops outside the workspace, shell
298
+ # on a non-inert command) only resolves once the call exists, so those
299
+ # still have to reach a human mid-run. Without the channel the child
300
+ # ran headless and lost every approval-gated tool silently.
301
+ #
302
+ # §23 AC1b: the grant is the SUBSET the user ticked, not every
303
+ # candidate. §18 shipped this all-or-nothing (S1) because a boolean
304
+ # channel could not carry a list out and a subset back; approving a
305
+ # spawn therefore authorised the child's entire approval-gated set.
306
+ # `signoff` is injected by dispatch() and is None only when nothing
307
+ # asked -- a headless run, where the child gets no grant anyway.
308
+ granted = set(signoff) if signoff else set()
309
+
310
+ model, provider = _child_pair(agent, parent_run)
311
+ # The parent's level, unvalidated here on purpose: a child on its own
312
+ # pin or on the /submodel pair may be a model that refuses it, and
313
+ # core.client.effort_for drops a level the receiving model does not
314
+ # list at the send, with a warning. One validator at the wire rather
315
+ # than a guess at each site that can change the model.
316
+ effort = parent_run.effort if parent_run else None
317
+
318
+ # Batch 59. THE SPAN AND THE PASS-DOWN ARE ONE CHANGE, and the
319
+ # pass-down is the half that does the work: `activity=activity` on the
320
+ # call below is what lets the child's OWN spawn_subagent open a span
321
+ # too, so a shell sees depth 2 rather than only the spawn it can
322
+ # already infer from tool_call_start. Without it this reports exactly
323
+ # what the TUI knew before the batch.
324
+ #
325
+ # A context manager rather than a pair of calls, because the exit has
326
+ # to happen when the child RAISES -- a provider error inside a
327
+ # subagent must not leave a row on screen describing a run that is
328
+ # over. run_agent_conversation does not contain its own exceptions
329
+ # (core/events.py: "exceptions raised mid-loop propagate naturally"),
330
+ # so this is a reachable path rather than a defensive one.
331
+ #
332
+ # `child.subagent_depth` and not a local count: C3 already maintains
333
+ # that number and a second one would be free to disagree with it.
334
+ from core import shell_sessions
335
+
336
+ # ROADMAP_v3 §49 (SS9). Everything the child's first turn and any wake
337
+ # turn after it share. A wake IS that run continuing -- the same
338
+ # prompt, context, channel, grant and sink -- so the two calls take one
339
+ # dict rather than two argument lists that could drift apart.
340
+ common = dict(
341
+ model=model,
342
+ provider_name=provider,
343
+ max_steps=agent.max_steps or config.MAX_ITERATIONS,
344
+ context=child,
345
+ effort=effort,
346
+ # `child`, not the agent's own context: C6 intersects with
347
+ # the parent, so a parent that excluded spawn_subagent must not
348
+ # have the catalog re-invite its child to spawn one (review
349
+ # f19).
350
+ # #68: the child's own facts, not the parent's. A subagent
351
+ # spawned from a headless run inherits no channel, so its
352
+ # catalogs must be decided by what IT can call -- the same
353
+ # values handed to run_agent_conversation below.
354
+ system_prompt=manager.system_prompt_for(
355
+ agent, with_persona(DEFAULT_SYSTEM_PROMPT, model, provider),
356
+ context=child,
357
+ callable_only=response_channel is None,
358
+ granted=granted),
359
+ response_channel=response_channel,
360
+ granted_tools=granted if (response_channel is not None
361
+ and granted) else None,
362
+ # The recursion. Inherited exactly as response_channel is, and
363
+ # for the same reason: the child is a run in its own right and
364
+ # whatever is watching this stack is watching that one too.
365
+ activity=activity,
366
+ # ROADMAP_v3 §61 (CN7). Inherited exactly as `activity` above is,
367
+ # and for a sharper version of the same reason: the child is a
368
+ # run in its own right, and a stop aimed at the turn that spawned
369
+ # it has to reach it, or the parent waits out a child it has
370
+ # already asked to end.
371
+ cancel=cancel,
372
+ )
373
+ with agent_activity.span(activity, agent.name, child.subagent_depth,
374
+ call_id) as span:
375
+ # ROADMAP_v3 §49 (SS17). The child is a wake CONSUMER: a session it
376
+ # starts is reported inside this call and nowhere else, which is
377
+ # what makes starting one allowed at all in this run.
378
+ with shell_sessions.consuming():
379
+ try:
380
+ response = RunAgentLoop.run_agent_conversation(
381
+ user_goal=task,
382
+ # §27 AC1. A spawned agent's thread is not a
383
+ # conversation anyone will resume, and one goal-mode
384
+ # turn can spawn several.
385
+ thread_kind=THREAD_KIND_SUBAGENT,
386
+ # §47. WHO spawned this thread, stored on the child's
387
+ # own row.
388
+ #
389
+ # `memory` and `call_id` are injected by dispatch() the
390
+ # same way the values in `common` are -- the parent's
391
+ # live ConversationMemory, and the model's id for THIS
392
+ # call. Both are None on a path that reaches run()
393
+ # directly (every test that calls it by hand), and the
394
+ # child is then simply a thread with no recorded
395
+ # parent, which is what it was before that batch.
396
+ #
397
+ # THE CALL ID IS WHAT MAKES THE EDGE SPECIFIC. One turn
398
+ # can spawn `explore` three times, so the agent name
399
+ # identifies the roster entry and not the run; the call
400
+ # id is the only thing that ties one child to one
401
+ # `▸ spawn_subagent` line.
402
+ thread_parent=getattr(memory, "thread_id", None),
403
+ thread_parent_call=call_id,
404
+ thread_agent=agent.name,
405
+ **common,
406
+ )
407
+ # SS9. The child does not answer its parent while its own
408
+ # background sessions are still running: it sleeps HERE, is
409
+ # woken here, and returns once there is nothing left to
410
+ # report. D6 is untouched -- what crosses back is still one
411
+ # distilled answer.
412
+ response = _sleep_for_sessions(response, common)
413
+ except BaseException:
414
+ # A child that RAISED has no thread to report to, and its
415
+ # sessions would outlive the run that started them --
416
+ # holding slots against the process-wide cap for as long
417
+ # as their timeouts. The SPAN is the handle: it is frozen
418
+ # and carries no address, so the child's thread id may
419
+ # never have reached this frame, while every session
420
+ # records the span it was started inside.
421
+ shell_sessions.sessions.kill_by_span(
422
+ span.id, shell_sessions.KILL_OWNER_FAILED)
423
+ raise
424
+ return {
425
+ "result": response.text,
426
+ "subagent_thread_id": str(response.thread_id),
427
+ }
428
+
429
+
430
+ def _sleep_for_sessions(response, common: dict):
431
+ """Stay inside the spawn while the child's sessions report (SS9, SS20).
432
+
433
+ Returns the response the child ends on: its first answer when it
434
+ started no sessions, or the answer to the last wake it was given.
435
+
436
+ THE LIMIT IS WHY THIS TERMINATES. A subagent has no user to type a
437
+ message, so the consecutive-wake count it shares with every other
438
+ owner can never be reset from outside -- past it the manager stops
439
+ handing out batches and holds them instead. SS20 makes that the end of
440
+ the run rather than a wait for something that cannot happen: the
441
+ remaining sessions are stopped, and the results of stopping them are
442
+ what the one final wake carries.
443
+ """
444
+ from core import shell_sessions
445
+
446
+ sessions = shell_sessions.sessions
447
+ thread_id = response.thread_id
448
+ while True:
449
+ batch = sessions.wait_for_wake(thread_id)
450
+ if batch:
451
+ response = _wake(response, thread_id, batch, common)
452
+ continue
453
+ if not sessions.suspended(thread_id):
454
+ return response
455
+ sessions.kill_owned(thread_id, shell_sessions.KILL_WAKE_LIMIT)
456
+ held = sessions.take_held(thread_id)
457
+ if held:
458
+ response = _wake(response, thread_id, held, common)
459
+ # Anything that last turn started has nobody left to report to,
460
+ # and nothing after this point will ever wake this thread again.
461
+ sessions.kill_owned(thread_id, shell_sessions.KILL_WAKE_LIMIT)
462
+ return response
463
+
464
+
465
+ def _wake(response, thread_id, events, common: dict):
466
+ """One wake turn in the child's own thread, under its own run."""
467
+ from core.loop import RunAgentLoop
468
+ from core.session_wake import build_wake
469
+
470
+ text, record = build_wake(events)
471
+ return RunAgentLoop.wake_conversation(
472
+ thread_id=thread_id, text=text, harness=record, **common)