ur-agent 1.68.18 → 1.69.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.
@@ -1,327 +0,0 @@
1
- # 09 — Multi-Agent Orchestration
2
-
3
- Source of truth: `src/tools/AgentTool/`, `src/services/agents/`, `src/commands/{agents,bg,crew,arena,pattern,task,worktree,route,escalate}`,
4
- `src/coordinator/coordinatorMode.ts`, `src/tools/Team*Tool/`.
5
-
6
- ## Subagents (the `Agent` tool)
7
-
8
- The main agent can spawn subagents. Built-in agent types
9
- (`src/tools/AgentTool/built-in/`):
10
-
11
- | Type | Purpose |
12
- |---|---|
13
- | `general-purpose` | catch-all multi-step worker (all tools) |
14
- | `worker` | stable workflow/crew alias for `general-purpose`; a project-defined `worker` overrides it |
15
- | `verification` | verifies a change actually works (used by `/verify`) |
16
- | `statusline-setup` | configures the status line |
17
- | `ur-code-guide` | answers UR/SDK/API questions |
18
- | `Explore`, `Plan` | built-in read-only search and planning agents; registered in the standard npm bundle so plan-mode instructions never advertise missing worker types |
19
-
20
- Ordinary `Agent` subagents do not require experimental Teams/swarm mode.
21
- Every ordinary worker launch does require successful task setup and an
22
- `in_progress` parent task first; the exact built-in read-only `Explore`/`Plan`
23
- plan-mode path below is the only exception. Coordinator mode exposes Task V2
24
- tools (or `TodoWrite` in a legacy pool) instead of directing workers through an
25
- unsatisfiable gate. Independent tasks may launch in one worker wave only after
26
- their task records exist and the tasks actually launching are marked
27
- `in_progress`.
28
- Approved-plan handoff checks the actual tool pool, agent-type allowlist, live
29
- `Agent(type)` deny rules, and active built-in definitions. It can fan out
30
- independent ready tasks only when a selectable implementation worker remains.
31
- The Teams gate applies only to named teammates, team files/mailboxes, and
32
- `TeamCreate`/`TeamDelete`.
33
-
34
- While the parent is in plan mode, only the exact active built-in `Explore` and
35
- `Plan` definitions may pass the task-list gate as read-only delegations.
36
- Plan prompts apply the same type allowlist and live deny rules as the eventual
37
- `Agent` call, so they do not advertise a planning worker that policy will
38
- reject.
39
- Custom agents reusing those names, generic agents, teammates, background
40
- launches, custom working directories, and worktree launches remain mutating and
41
- task-gated. `TeamCreate` and `TeamDelete` also reject plan mode explicitly;
42
- team lifecycle state starts only after the plan is approved.
43
- Outside plan mode, team creation/deletion, structured shutdown responses, and
44
- emergency `TaskStop` are task-control transitions exempt from the workspace
45
- task gate so team bootstrap and teardown cannot deadlock. Their tool-specific
46
- validation still applies, including refusing deletion while members are active.
47
-
48
- In the standard bundle, `Explore` and `Plan` receive only `Glob`, `Grep`, and
49
- `Read`, use `dontAsk` permission mode, and have a second runtime boundary that
50
- rejects any operation classified as mutating even if an actionable task or
51
- inherited allow rule exists. Ant-native embedded-search builds substitute
52
- read-only Bash `find`/`grep` access for the dedicated search tools; the same
53
- runtime mutation boundary remains in force.
54
-
55
- Custom agents:
56
- - `/agents` — interactive management UI.
57
- - Definition files loaded from agents directories (project + user), validated by
58
- `AgentJsonSchema`: `description` (required), `prompt` (required), `tools`,
59
- `disallowedTools`, `model` (or `inherit`), `effort`, `permissionMode`,
60
- `mcpServers`, `hooks`, `maxTurns`, `skills`, `initialPrompt`, `memory`,
61
- `background`, and worktree `isolation`.
62
- - CLI: `ur --agents '{"reviewer":{"description":"…","prompt":"…"}}'` and
63
- `ur --agent reviewer` to run a whole session as that agent.
64
- - `/agent-templates install <name>` installs reusable templates;
65
- `/role-mode install architect|code|debug|ask` installs the four classic role modes as
66
- scoped agents.
67
-
68
- Read-only `Explore`/`Plan` agents omit the UR.md hierarchy only
69
- when the default-on `tengu_slim_subagent_agentmd` gate remains enabled and the
70
- caller did not explicitly provide user context (token saving; see
71
- `loadAgentsDir.ts`).
72
-
73
- Inspection: `/agent-inspect` reconstructs a per-subagent timeline (spawns, prompts,
74
- results, verdicts, tools, tokens) from the session or a transcript file.
75
-
76
- ## Fan-out limits (`src/tools/AgentTool/fanOutLimits.ts`)
77
-
78
- These limits apply specifically to nested, in-process launches through the
79
- `Agent` tool. Both are checked in `runAgent` before that child starts, so a
80
- refusal is free.
81
-
82
- | Limit | Default | Hard ceiling | Setting |
83
- |---|---|---|---|
84
- | Nesting depth | 3 | 10 | `agents.maxDepth` |
85
- | Concurrent agents | 20 | 100 | `agents.maxConcurrent` |
86
-
87
- ```json
88
- { "agents": { "maxConcurrent": 40, "maxDepth": 4 } }
89
- ```
90
-
91
- Out-of-range, negative and non-numeric values clamp rather than disabling the
92
- governor — a settings file cannot switch it off. Exceeding a limit throws with
93
- a message naming both the limit and the setting that raises it. Slot ownership
94
- enters a single `try/finally` immediately after registration. Failures during
95
- context loading, hooks, skill or MCP setup, cache callbacks, query execution,
96
- cancellation, and normal completion all release it exactly once; partial setup
97
- resources are cleaned conditionally.
98
-
99
- Depth is derived from the live registry rather than passed down: a child's
100
- depth is its parent's plus one, and an agent whose parent is unknown counts as
101
- a root.
102
-
103
- `/crew`, `/arena`, `/bg fanout`, and `/exec` launch subprocess/worktree
104
- orchestrators and do **not** register in this `Agent`-tool governor. They have
105
- their own concurrency limits (`crew` clamps fixed and dynamic pools to 1–32;
106
- `bg fanout` and `exec` also clamp their public counts) and their own model/token
107
- cost. Detached background agents are separate processes with separate
108
- in-process registries.
109
-
110
- ## Running several workers at once
111
-
112
- Four ways to parallelise, differing mainly in whether workers share your
113
- checkout:
114
-
115
- | Command | Shape | Isolation flag |
116
- |---|---|---|
117
- | `ur exec "a" "b" --concurrency 3` | different prompts in parallel | `--worktree` |
118
- | `ur crew run <name> --workers 4` | one goal split across a task board | `--worktrees` |
119
- | `ur arena "<task>" --agents 3` | same task, N attempts, judge picks | isolated by default |
120
- | `ur bg fanout "<task>" --agents 4` | detached, survives the session | `--worktree` |
121
-
122
- Pass the isolation flag whenever workers might touch the same files. Without
123
- it every worker edits the same checkout concurrently and they overwrite each
124
- other. Agents are much heavier than test workers — each is a full model session
125
- with its own token spend — so 4–6 is usually the practical ceiling on a laptop
126
- regardless of the configured limit.
127
-
128
- Isolation does not imply integration. `/crew --worktrees` creates a fresh
129
- worktree for every task attempt and leaves a passing attempt at its recorded
130
- path for lead/human review; it does not merge, cherry-pick, or apply those
131
- changes to the starting checkout. A dependent crew task receives its
132
- prerequisite's text result, but its fresh worktree does not inherit the
133
- prerequisite worktree's unmerged file changes. Design dependent code edits
134
- accordingly. `/exec --worktree` instead gives all steps of one top-level prompt
135
- the same plan worktree (doc 10).
136
-
137
- ## Shared task-list correctness
138
-
139
- Interactive sessions use the canonical Task V2 tools. Print/headless sessions
140
- use legacy `TodoWrite` by default, or Task V2 when
141
- `UR_CODE_ENABLE_TASKS=1`. Both feed the same mutation gate:
142
-
143
- - Approved non-trivial plans are translated into a complete task graph before
144
- workspace changes: one task record per cohesive outcome with its own
145
- observable completion check. Separate deliverables are not hidden in one
146
- umbrella item, while files, tool calls, and tiny mechanical steps are not
147
- artificial task boundaries.
148
- - Independent Task V2 records are created together (up to the eight-call
149
- prompt batch limit), then real dependency edges are added once task IDs are
150
- known. Default headless sessions instead write the complete outcome list
151
- through `TodoWrite`; approval handoff detects this capability rather than
152
- naming unavailable Task V2 tools. When an actual built-in implementation
153
- worker is active, ready tasks without conflicting shared mutations launch in
154
- waves of up to eight with bounded scope, acceptance checks, and dependency
155
- inputs. Dependent or conflicting writes stay sequential, and the lead
156
- verifies worker evidence before completion. An exposed `Agent` tool with no
157
- selectable implementation worker is not advertised as delegation support.
158
- - Task IDs are ordered numerically (`1, 2, 10`), with non-numeric external IDs
159
- sorted stably after numeric IDs.
160
- - Dependencies block transition or claim until prerequisites are complete.
161
- - Actionable `pending` or `in_progress` entries open the gate; completed and
162
- internal entries do not.
163
- - The last actionable `in_progress` task cannot be terminalized immediately
164
- after a recorded file mutation with no later successful observable check.
165
- `TaskUpdate` soft-defers that completion and keeps the same task actionable;
166
- it does not infer or auto-create a replacement task. A later successful
167
- inspection/runtime/test/delegated check allows the explicit completion retry.
168
- - Reads remain unrestricted. Ordinary mutations have a default allowance of
169
- three preceding tool calls, counted by tool call rather than message.
170
- Delegation and child mutations always require an actionable parent task.
171
- The sole delegation exception is a foreground built-in `Explore` or `Plan`
172
- call during live plan mode; those agents omit workspace-editing and nested
173
- delegation tools and remain subject to their child permission checks.
174
- - An unreadable task store fails closed. Task create/update/list/get tools stay
175
- exempt so the agent can repair the plan.
176
- - Creating or updating the exact current-session plan-mode Markdown file is
177
- also exempt: that file is the planning artifact, not an ordinary workspace
178
- change. A bounded Bash bootstrap may only create/check that file's exact
179
- parent (`mkdir -p`, optionally guarded by the known `ls` pattern); this
180
- compatibility path remains subject to Bash permission and sandbox checks.
181
- The exemption and live actionable-task state are re-evaluated at the final
182
- execution boundary after permission-hook input rewrites. Sibling paths,
183
- general plans-directory commands, added shell operations, and the filename
184
- alone outside live plan mode are not exempt.
185
- - Configure the behavior at
186
- `tasks.requireBeforeChanges.{enabled,freeReads}`.
187
- - Full, partial, and session-memory compaction restore the live task board as
188
- an authoritative bounded snapshot, including exact Task V2 IDs, statuses,
189
- owners, and dependency edges. In-process workers do not run a second private
190
- compaction algorithm: they use the same `runAgent` query-loop policy,
191
- feature gates, session-memory-first behavior, threshold, circuit breaker,
192
- and compact-boundary handling as the main agent.
193
-
194
- The prompt contract, plan-file structure, plan-agent output, approval handoff,
195
- task-tool result, and gate recovery text all reinforce the same decomposition
196
- and worker rules. Runtime dependencies and mutation gating enforce ordering and
197
- plan presence; they cannot prove that an arbitrary natural-language task is
198
- semantically complete, so the gate deliberately does not require a fake
199
- minimum task count. Workflows and crews add stricter verdict rules where a
200
- machine-checkable execution boundary exists.
201
-
202
- ## Task routing
203
-
204
- ```
205
- /route "why does login 500 intermittently?" # → recommends subagent + pattern
206
- /model-route "port to Rust" --strategy strong # → recommends model (doc 05)
207
- /escalate run "hard problem" --oracle gpt-5.5 # fast model + oracle escalation (doc 05)
208
- ```
209
- `src/services/agents/intentRouter.ts` does the task classification;
210
- `decomposer.ts` splits goals into tasks; `delegation.ts` hands tasks to workers.
211
-
212
- ## Background agents (`/bg`, `ur bg`)
213
-
214
- Detached local agents managed by `src/services/agents/backgroundRunner.ts`:
215
- ```
216
- /bg run "upgrade eslint to v9" --worktree # isolated local worktree
217
- /bg run "upgrade eslint to v9" --worktree --pr # explicit opt-in PR creation
218
- /bg fanout "fix all TODO(sec) comments" --agents 4
219
- /bg list · /bg status <id> · /bg logs <id> · /bg attach <id> · /bg kill <id>
220
- ```
221
- The standard CLI exposes the same operations through `ur bg ...`. The separate
222
- process-session fast path (`ur --bg -p`, then top-level `ur ps|logs|attach|kill`)
223
- requires the `BG_SESSIONS` build feature and is not present in the normal npm
224
- bundle.
225
-
226
- ## Crews (`/crew`) — shared task board
227
-
228
- A lead agent decomposes a goal into a task board; worker subagents claim and execute tasks
229
- (`src/services/agents/crew.ts`):
230
- ```
231
- /crew create cleanup --goal "remove dead code and fix lints" --decompose
232
- /crew plan cleanup --goal "remove dead code and fix lints" --decompose
233
- /crew add cleanup --task "delete unused exports in src/utils"
234
- /crew run cleanup --workers 3 --worktrees
235
- /crew run cleanup --dynamic --max-workers 8 # scale workers to the board (own 1–32 cap)
236
- /crew show cleanup · /crew reset cleanup --max-attempts 2 · /crew delete cleanup
237
- ```
238
-
239
- A task succeeds only when the worker process is non-error and returns exactly
240
- one standalone `VERDICT: PASS` line; inline, missing, or multiple verdicts,
241
- `PARTIAL`, and `FAIL` are failures. Automatic
242
- retries are bounded (hard cap five), cancellation-aware, and allowed only for
243
- dry runs or fresh worktree attempts. Shared-checkout failures are not replayed
244
- because their mutations are ambiguous. `--resume` and `reset` reopen only safe
245
- isolated attempts that still have budget; ambiguous claimed tasks are marked
246
- failed. Dynamic mode exits rather than spinning when claimed tasks prevent
247
- further progress. Fixed `--workers` and dynamic `--max-workers` are clamped to
248
- 1–32 independently of the in-process `Agent`-tool governor. A board that is
249
- not completely done returns nonzero.
250
-
251
- ## Arena (`/arena`) — best-of-N with a judge
252
-
253
- N agents attempt the same task in isolated worktrees, a deterministic judge compares the
254
- diffs, and a passing winner can be applied (`src/services/agents/arena.ts`). Worktree
255
- creation failure fails that candidate; it never falls back to concurrent writes in cwd.
256
- Only non-error `PASS` candidates with a non-empty, non-blocking diff can win:
257
- ```
258
- /arena "make the image pipeline 2x faster" --agents 3 --max-turns 30
259
- /arena "…" --apply # apply the winning diff
260
- /arena "…" --keep # keep losing worktrees for inspection
261
- ```
262
-
263
- ## Worktree-per-task sessions
264
-
265
- ```
266
- ur -w feature-x # session in a fresh git worktree (+ --tmux for panes)
267
- /task start rate-limiter --worktree --base main
268
- /task run <id> · /task status <id> · /task list
269
- /task pr <id> --create --draft --base main
270
- /worktree list · /worktree status · /worktree clean
271
- ```
272
- `EnterWorktree` / `ExitWorktree` tools let the model move itself into isolation mid-turn
273
- (worktree mode). Worktree settings: `worktree.symlinkDirectories`, `worktree.sparsePaths`.
274
- `task start --worktree` creates only local isolated state; it never pushes or
275
- opens a PR. Publishing begins only with the explicit `task pr --create`
276
- command.
277
-
278
- Bundled worktree skills (`/debug-v2`, `/refactor`, `/security-review`,
279
- `/dockerize`, `/paper-implementation`, `/latex-paper`, `/benchmark`, `/batch`)
280
- carry instructions to leave changes local, run focused checks while working,
281
- ask before the final full verification suite, and avoid commit/push/PR actions
282
- unless the user separately requests publishing. These are model instructions,
283
- not a separate OS enforcement boundary. `agentSkillRunner.createPr` defaults
284
- to false.
285
-
286
- ## Teams / swarm mode (feature-gated)
287
-
288
- - The standard external build can opt into in-process teams with
289
- `UR_CODE_EXPERIMENTAL_AGENT_TEAMS=1`, subject to the
290
- `tengu_amber_flint` runtime kill switch. This enables `TeamCreate`,
291
- `TeamDelete`, `SendMessage`, `InProcessTeammateTask`, and the
292
- `TeammateIdle` hook. `--agent-teams` is registered only in ant builds, so it
293
- is not a supported external CLI flag.
294
- - Team creation and deletion are unavailable while plan mode is active. Use the
295
- standard read-only `Explore`/`Plan` subagents for parallel planning, then
296
- create an implementation team after approval.
297
- - Coordinator mode (`UR_CODE_COORDINATOR_MODE=1`) is additionally behind the
298
- compile-time `COORDINATOR_MODE` feature. The standard npm bundle does not
299
- include it; setting the environment variable there has no effect.
300
- - `/peers` and `ListPeers` are behind the compile-time `UDS_INBOX` feature and
301
- are likewise absent from the standard npm bundle.
302
- - Team-memory synchronization is separately behind the compile-time `TEAMMEM`
303
- feature; enabling teams does not make that source-only memory service appear.
304
-
305
- ## Goals — long-horizon persistence (`/goal`)
306
-
307
- ```
308
- /goal add v2-launch --objective "ship v2" --workflow release
309
- /goal list · /goal show v2-launch · /goal note v2-launch "auth blocked on infra"
310
- /goal resume v2-launch # run the linked workflow now from its saved checkpoint
311
- /goal pause|done|abandon|delete v2-launch
312
- ```
313
- `resume` executes the linked workflow through child sessions from the current
314
- command; it does not open a new main interactive session. A stored `--pattern`
315
- is descriptive metadata today and is not executed by `goal resume`, which
316
- requires a linked workflow.
317
-
318
- ## Verification layer (`src/services/verifier/`)
319
-
320
- The main query loop has a verifier with done detection, loop detection, project
321
- quality gates (`projectGates.ts`, installed by
322
- `/test-first install --install-gates`), and optional subagent nudges.
323
- `verifier.askBeforeGates` controls prompting. Workflow verification gates,
324
- crew verdicts, arena judging, and exec evidence checks are separate
325
- orchestrator-specific mechanisms; they should not be conflated with this query
326
- verifier. Proof helpers in `verificationProofs.ts` are consumed by the
327
- spec/kernel verification paths and related evidence reporting.