@unieai/rabi-tool-subagent-control 0.2.1-rc.3 → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @unieai/rabi-tool-subagent-control
2
2
 
3
- Globally named send_message, interrupt_agent, and list_agents tools over ctx.subagents continuations
3
+ Shared messaging, interruption, and child discovery tools for subagents
4
4
 
5
5
  Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
6
  not meant to be used on its own.
package/lib/index.js CHANGED
@@ -1,11 +1,199 @@
1
- import { brandString } from "@unieai/rabi-brand";
1
+ import z from "@unieai/schemastery";
2
2
  import { defineTool } from "@unieai/rabi-tools";
3
- import { markAdjacentAgentSendMessageTool } from "@unieai/rabi-subagent/internal";
3
+ import { ROOT_AGENT_NAME } from "@unieai/rabi-subagent";
4
+ import { HarnessError } from "@unieai/rabi-llm";
5
+ //#region lib/types/list-agents.js
6
+ /** Discover the caller's entire subagent tree; the control plugin owns registration. */
7
+ /** Report turn activity without exposing whether the child is loaded. */
8
+ function statusOf(agents, id) {
9
+ return agents.get(id)?.status === "running" ? "running" : "inactive";
10
+ }
11
+ /** Project one service row into the model-facing entry, or omit a one-shot or external child. */
12
+ function project(agents, entry) {
13
+ const name = entry.path ?? entry.id;
14
+ if (entry.kind === "diagnostic") return {
15
+ name,
16
+ status: entry.reason
17
+ };
18
+ if (entry.mode !== "continuable") return void 0;
19
+ return {
20
+ name,
21
+ status: statusOf(agents, entry.id),
22
+ description: entry.label
23
+ };
24
+ }
25
+ /**
26
+ * Register the `list_agents` tool.
27
+ * @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
28
+ * @returns the registered definition for scoped availability checks.
29
+ */
30
+ function registerListAgents(ctx) {
31
+ const definition = defineTool({
32
+ name: "list_agents",
33
+ description: "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.",
34
+ parameters: {},
35
+ isConcurrencySafe: () => true,
36
+ output: {
37
+ schema: {
38
+ type: "array",
39
+ items: {
40
+ type: "object",
41
+ additionalProperties: false,
42
+ properties: {
43
+ name: {
44
+ type: "string",
45
+ required: true
46
+ },
47
+ status: {
48
+ type: "string",
49
+ required: true,
50
+ enum: [
51
+ "running",
52
+ "inactive",
53
+ "corrupt",
54
+ "unsupported",
55
+ "unavailable"
56
+ ]
57
+ },
58
+ description: { type: "string" }
59
+ }
60
+ }
61
+ },
62
+ render: (_args, entries) => [{
63
+ type: "text",
64
+ text: entries.map((entry) => `${entry.name} [${entry.status}]${entry.description === void 0 ? "" : ` — ${entry.description}`}`).join("\n")
65
+ }]
66
+ },
67
+ async execute(_args, exec) {
68
+ const parent = exec.agent;
69
+ if (!parent) throw new Error("list_agents requires a calling agent (exec.agent was undefined)");
70
+ const root = ctx.subagents.rootOf(parent);
71
+ const entries = await ctx.subagents.listDescendants(root.id, exec.signal);
72
+ return [{
73
+ name: ROOT_AGENT_NAME,
74
+ status: statusOf(ctx.agents, root.id),
75
+ description: "root agent"
76
+ }, ...entries.map((entry) => project(ctx.agents, entry)).filter((entry) => entry !== void 0)];
77
+ }
78
+ });
79
+ ctx.tools.register(definition);
80
+ return definition;
81
+ }
82
+ //#endregion
83
+ //#region lib/types/wait-agent.js
84
+ /** Input waiting owned by the subagent control plugin. */
85
+ /** Wait failures retain a stable machine-readable reason through tool execution. */
86
+ var AgentWaitError = class extends HarnessError {
87
+ constructor(message, code) {
88
+ super(message, code);
89
+ this.name = "AgentWaitError";
90
+ }
91
+ };
92
+ /**
93
+ * Wait without consuming input; every settlement removes its live resources.
94
+ * Within one model tool call, such as a `run_code` program, pending input that
95
+ * an earlier wait already reported does not end this wait: that input reaches
96
+ * the model only after the call finishes, so a waiting loop cannot spin on it.
97
+ */
98
+ function waitForInput(ctx, agent, timeoutMs, signal, lifetime, reported, rootCallId) {
99
+ lifetime.throwIfAborted();
100
+ if (ctx.agents.get(agent.id) !== agent) throw new AgentWaitError("wait_agent requires the exact live calling agent", "WAIT_UNAVAILABLE");
101
+ const previous = reported.get(agent);
102
+ const seen = previous?.rootCallId === rootCallId ? previous.ids : void 0;
103
+ return new Promise((resolve, reject) => {
104
+ const finish = (settle) => {
105
+ clearTimeout(timer);
106
+ offInbox();
107
+ offDisposed();
108
+ signal.removeEventListener("abort", onAbort);
109
+ lifetime.removeEventListener("abort", onUnload);
110
+ settle();
111
+ };
112
+ const onInput = () => {
113
+ const pending = agent.inbox.nextStep;
114
+ if (pending.some((message) => seen?.has(message.id) !== true)) {
115
+ reported.set(agent, {
116
+ rootCallId,
117
+ ids: new Set(pending.map((message) => message.id))
118
+ });
119
+ finish(() => {
120
+ resolve({ timedOut: false });
121
+ });
122
+ }
123
+ };
124
+ const onAbort = () => {
125
+ finish(() => {
126
+ reject(signal.reason);
127
+ });
128
+ };
129
+ const onUnload = () => {
130
+ finish(() => {
131
+ reject(lifetime.reason);
132
+ });
133
+ };
134
+ const offInbox = ctx.on("agent/inbox/inserted", ({ agent: recipient }) => {
135
+ if (recipient === agent) onInput();
136
+ });
137
+ const offDisposed = ctx.on("agent/disposed", ({ agent: disposed }) => {
138
+ if (disposed === agent) finish(() => {
139
+ reject(new AgentWaitError("wait_agent ended because the calling agent was disposed", "WAIT_UNAVAILABLE"));
140
+ });
141
+ });
142
+ signal.addEventListener("abort", onAbort, { once: true });
143
+ lifetime.addEventListener("abort", onUnload, { once: true });
144
+ const timer = setTimeout(() => {
145
+ finish(() => {
146
+ resolve({ timedOut: true });
147
+ });
148
+ }, timeoutMs);
149
+ if (signal.aborted) onAbort();
150
+ else onInput();
151
+ });
152
+ }
153
+ /**
154
+ * Register one inbox wait tool and cancel its waits when the plugin unloads.
155
+ * @param ctx - plugin context owning the tool, event listeners, and wait lifetime.
156
+ */
157
+ function registerWaitAgent(ctx) {
158
+ const lifetime = new AbortController();
159
+ const reported = /* @__PURE__ */ new WeakMap();
160
+ ctx.effect(() => () => {
161
+ lifetime.abort(new AgentWaitError("wait_agent ended because its plugin was unloaded", "WAIT_UNAVAILABLE"));
162
+ }, "subagent-control.waits()");
163
+ ctx.tools.register(defineTool({
164
+ name: "wait_agent",
165
+ description: "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.",
166
+ parameters: { timeout_ms: {
167
+ type: "integer",
168
+ description: "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000."
169
+ } },
170
+ output: {
171
+ schema: {
172
+ type: "object",
173
+ additionalProperties: false,
174
+ properties: { timedOut: {
175
+ type: "boolean",
176
+ required: true
177
+ } }
178
+ },
179
+ render: (_args, value) => [{
180
+ type: "text",
181
+ text: JSON.stringify(value)
182
+ }]
183
+ },
184
+ async execute(args, exec) {
185
+ const timeoutMs = args.timeout_ms ?? 3e4;
186
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1e4 || timeoutMs > 36e5) throw new AgentWaitError("timeout_ms must be an integer from 10000 through 3600000", "WAIT_INVALID_TIMEOUT");
187
+ if (exec.agent === void 0) throw new AgentWaitError("wait_agent requires a calling agent", "WAIT_UNAVAILABLE");
188
+ return await waitForInput(ctx, exec.agent, timeoutMs, exec.signal, lifetime.signal, reported, exec.rootCallId);
189
+ }
190
+ }));
191
+ }
192
+ //#endregion
4
193
  //#region lib/types/index.js
5
194
  /**
6
- * The globally named `send_message` and `interrupt_agent` tools: thin
7
- * model-facing adapters over `ctx.subagents.sendMessage()` and
8
- * `ctx.subagents.interrupt()`. They perform no lifecycle routing of their own —
195
+ * Shared messaging, inbox waiting, interruption, and child discovery tools.
196
+ * They perform no lifecycle routing of their own —
9
197
  * residency, cold resume, and interrupt authorization belong to the subagent
10
198
  * service — and they live apart from the provider-bound
11
199
  * `@unieai/rabi-tool-subagent` instances so multiple delegation tools share
@@ -13,20 +201,31 @@ import { markAdjacentAgentSendMessageTool } from "@unieai/rabi-subagent/internal
13
201
  * @module @unieai/rabi-tool-subagent-control
14
202
  */
15
203
  const name = "tool-subagent-control";
16
- const inject = ["tools", "subagents"];
204
+ const inject = [
205
+ "tools",
206
+ "subagents",
207
+ "agents",
208
+ "systemPrompt"
209
+ ];
210
+ /** Loader schema for optional subagent control tools. */
211
+ const Config = z.object({ interrupt: z.boolean().default(true) });
17
212
  /**
18
- * Register the `send_message` and `interrupt_agent` tools.
19
- * @param ctx - context carrying the tool registry and subagent service.
213
+ * Register the shared subagent control and discovery tools.
214
+ * @param ctx - context carrying tools, subagents, live Agents, and prompt assembly.
215
+ * @param config - optional tool registration settings.
20
216
  */
21
- function apply(ctx) {
22
- ctx.tools.register(markAdjacentAgentSendMessageTool(defineTool({
217
+ function apply(ctx, config = {}) {
218
+ const interrupt = config.interrupt !== false;
219
+ const listAgents = registerListAgents(ctx);
220
+ registerWaitAgent(ctx);
221
+ const sendMessage = defineTool({
23
222
  name: "send_message",
24
- description: "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation, not the agent's answer.",
223
+ description: "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.",
25
224
  parameters: {
26
- agent_id: {
225
+ agent: {
27
226
  type: "string",
28
227
  required: true,
29
- description: "The agent id of your direct continuable child, or your direct parent when you are a resident continuable child."
228
+ description: "The name of another agent in your subagent tree, as shown by list_agents."
30
229
  },
31
230
  message: {
32
231
  type: "string",
@@ -45,7 +244,7 @@ function apply(ctx) {
45
244
  },
46
245
  render: (args, _value) => [{
47
246
  type: "text",
48
- text: `message delivered to agent ${args.agent_id}`
247
+ text: `message delivered to agent ${args.agent}`
49
248
  }]
50
249
  },
51
250
  async execute(args, exec) {
@@ -55,16 +254,40 @@ function apply(ctx) {
55
254
  type: "text",
56
255
  text: args.message
57
256
  }];
58
- return { messageId: await ctx.subagents.sendMessage(sender, brandString(args.agent_id), message, { signal: exec.signal }) };
257
+ const targetId = await ctx.subagents.resolveName(sender, args.agent, exec.signal);
258
+ return { messageId: await ctx.subagents.sendMessage(sender, targetId, message, { signal: exec.signal }) };
59
259
  }
60
- })));
260
+ });
261
+ ctx.tools.register(sendMessage);
262
+ ctx.systemPrompt.context({
263
+ name: "subagent:identity",
264
+ order: ctx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),
265
+ required: true,
266
+ interpolate: false,
267
+ text: ({ agent, scope, toolSet }) => {
268
+ if (agent === void 0) return "";
269
+ try {
270
+ const names = ctx.subagents.namesOf(agent);
271
+ let identity = names.parent === void 0 ? `You are the root agent. Your name is ${JSON.stringify(names.self)}.` : `You are a subagent delegated by agent ${JSON.stringify(names.parent)}.\nYour name is ${JSON.stringify(names.self)}.\nThe root agent of your collaboration tree is ${JSON.stringify(ROOT_AGENT_NAME)}.`;
272
+ const guidance = [];
273
+ if (ctx.tools.get(sendMessage.name, scope, toolSet) === sendMessage) guidance.push("To message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).");
274
+ if (ctx.tools.get(listAgents.name, scope, toolSet) === listAgents) guidance.push("Use list_agents({}) to find your collaborator agents and their names.");
275
+ if (guidance.length > 0) identity += "\n\n" + guidance.join("\n");
276
+ return identity;
277
+ } catch (error) {
278
+ if (!(typeof error === "object" && error !== null && "name" in error && error.name === "SubagentError" && "code" in error && error.code === "UNAUTHORIZED")) throw error;
279
+ return `Your agent id is ${JSON.stringify(agent.id)}. Your subagent tree root is unavailable. Continue independent work; subagent discovery and messaging require an active root.`;
280
+ }
281
+ }
282
+ });
283
+ if (!interrupt) return;
61
284
  ctx.tools.register(defineTool({
62
285
  name: "interrupt_agent",
63
- description: "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local direct child's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.",
64
- parameters: { agent_id: {
286
+ description: "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.",
287
+ parameters: { agent: {
65
288
  type: "string",
66
289
  required: true,
67
- description: "The id of an agent created under you: your direct child or a deeper descendant."
290
+ description: "The name of an agent created under you: your direct child or a deeper descendant."
68
291
  } },
69
292
  output: {
70
293
  schema: {
@@ -77,19 +300,20 @@ function apply(ctx) {
77
300
  },
78
301
  render: (args, _value) => [{
79
302
  type: "text",
80
- text: `interrupt requested for agent ${args.agent_id}`
303
+ text: `interrupt requested for agent ${args.agent}`
81
304
  }]
82
305
  },
83
- execute(args, exec) {
306
+ async execute(args, exec) {
84
307
  const caller = exec.agent;
85
308
  if (!caller) throw new Error("interrupt_agent requires a calling agent (exec.agent was undefined)");
86
- ctx.subagents.interrupt(brandString(args.agent_id), {
309
+ const targetId = await ctx.subagents.resolveName(caller, args.agent, exec.signal);
310
+ ctx.subagents.interrupt(targetId, {
87
311
  kind: "ancestor",
88
312
  agent: caller
89
313
  });
90
- return Promise.resolve({ accepted: true });
314
+ return { accepted: true };
91
315
  }
92
316
  }));
93
317
  }
94
318
  //#endregion
95
- export { apply, inject, name };
319
+ export { Config, apply, inject, name };
@@ -1,7 +1,6 @@
1
1
  /**
2
- * The globally named `send_message` and `interrupt_agent` tools: thin
3
- * model-facing adapters over `ctx.subagents.sendMessage()` and
4
- * `ctx.subagents.interrupt()`. They perform no lifecycle routing of their own —
2
+ * Shared messaging, inbox waiting, interruption, and child discovery tools.
3
+ * They perform no lifecycle routing of their own —
5
4
  * residency, cold resume, and interrupt authorization belong to the subagent
6
5
  * service — and they live apart from the provider-bound
7
6
  * `@unieai/rabi-tool-subagent` instances so multiple delegation tools share
@@ -9,11 +8,20 @@
9
8
  * @module @unieai/rabi-tool-subagent-control
10
9
  */
11
10
  import type { Context } from '@unieai/cordis';
11
+ import z from '@unieai/schemastery';
12
12
  export declare const name = "tool-subagent-control";
13
13
  export declare const inject: string[];
14
+ /** Optional subagent control tools. */
15
+ export interface Config {
16
+ /** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */
17
+ interrupt?: boolean;
18
+ }
19
+ /** Loader schema for optional subagent control tools. */
20
+ export declare const Config: z<Config>;
14
21
  /**
15
- * Register the `send_message` and `interrupt_agent` tools.
16
- * @param ctx - context carrying the tool registry and subagent service.
22
+ * Register the shared subagent control and discovery tools.
23
+ * @param ctx - context carrying tools, subagents, live Agents, and prompt assembly.
24
+ * @param config - optional tool registration settings.
17
25
  */
18
- export declare function apply(ctx: Context): void;
26
+ export declare function apply(ctx: Context, config?: Config): void;
19
27
  //# sourceMappingURL=index.d.ts.map
@@ -1,17 +1,10 @@
1
- /**
2
- * The globally named `list_agents` tool: a thin model-facing adapter over
3
- * the continuable projection of `ctx.subagents.listChildren()` and, for the
4
- * `descendants` scope, `ctx.subagents.listDescendants()`. It stays separately
5
- * loadable from the root `send_message` plugin so a deployment can register
6
- * continuation delivery without exposing discovery.
7
- * @module @unieai/rabi-tool-subagent-control/list-agents
8
- */
1
+ /** Discover the caller's entire subagent tree; the control plugin owns registration. */
9
2
  import type { Context } from '@unieai/cordis';
10
- export declare const name = "tool-subagent-list-agents";
11
- export declare const inject: string[];
3
+ import type { ToolDefinition } from '@unieai/rabi-tools';
12
4
  /**
13
5
  * Register the `list_agents` tool.
14
6
  * @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
7
+ * @returns the registered definition for scoped availability checks.
15
8
  */
16
- export declare function apply(ctx: Context): void;
9
+ export declare function registerListAgents(ctx: Context): ToolDefinition;
17
10
  //# sourceMappingURL=list-agents.d.ts.map
@@ -0,0 +1,8 @@
1
+ /** Input waiting owned by the subagent control plugin. */
2
+ import type { Context } from '@unieai/cordis';
3
+ /**
4
+ * Register one inbox wait tool and cancel its waits when the plugin unloads.
5
+ * @param ctx - plugin context owning the tool, event listeners, and wait lifetime.
6
+ */
7
+ export declare function registerWaitAgent(ctx: Context): void;
8
+ //# sourceMappingURL=wait-agent.d.ts.map
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Kontrolltools für Subagenten",
4
+ "description": "Lassen Sie die KI Nachrichten an Subagenten senden oder deren Betrieb unterbrechen."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Herramientas de control de subagentes",
4
+ "description": "Deje que la IA envíe mensajes a los subagentes o interrumpa su operación."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Outils de contrôle des sous-agents",
4
+ "description": "Laissez l'IA envoyer des messages aux sous-agents ou interrompre leur fonctionnement."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "サブエージェント制御ツール",
4
+ "description": "AI がサブエージェントにメッセージを送信し、その実行を中断できます。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Ferramentas de controle de subagentes",
4
+ "description": "Deixe a IA enviar mensagens aos subagentes ou interromper sua operação."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Инструменты управления субагентами",
4
+ "description": "Позвольте ИИ отправлять сообщения субагентам или прерывать их работу."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-tool-subagent-control",
3
- "description": "Globally named send_message, interrupt_agent, and list_agents tools over ctx.subagents continuations",
4
- "version": "0.2.1-rc.3",
3
+ "description": "Shared messaging, interruption, and child discovery tools for subagents",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -13,33 +13,31 @@
13
13
  "types": "./lib/types/index.d.ts",
14
14
  "default": "./lib/index.js"
15
15
  },
16
- "./list-agents": {
17
- "types": "./lib/types/list-agents.d.ts",
18
- "default": "./lib/types/list-agents.js"
19
- },
20
16
  "./src/*": "./src/*",
21
17
  "./package.json": "./package.json",
22
- "./locale/*.json": "./locale/*.json",
23
- "./list-agents/locale/*.json": "./locale/list-agents/*.json"
18
+ "./locale/*.json": "./locale/*.json"
24
19
  },
25
20
  "files": [
26
21
  "locale/*.json",
27
- "locale/list-agents/*.json",
28
22
  "lib/index.js",
29
- "lib/types/**/*.js",
30
23
  "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
31
27
  "README.md"
32
28
  ],
33
29
  "license": "MIT",
34
30
  "peerDependencies": {
35
- "@unieai/cordis": "4.0.5",
36
- "@unieai/rabi-llm": "0.2.1-rc.3",
37
- "@unieai/rabi-session": "0.2.1-rc.3",
38
- "@unieai/rabi-subagent": "0.2.1-rc.3",
39
- "@unieai/rabi-tools": "0.2.1-rc.3"
31
+ "@unieai/cordis": "4.1.0",
32
+ "@unieai/rabi-llm": "0.2.2-rc.5",
33
+ "@unieai/rabi-session": "0.2.2-rc.5",
34
+ "@unieai/rabi-subagent": "0.2.2-rc.5",
35
+ "@unieai/rabi-tools": "0.2.2-rc.5",
36
+ "@unieai/rabi-agent": "0.2.2-rc.5",
37
+ "@unieai/rabi-system-prompt": "0.2.2-rc.5"
40
38
  },
41
39
  "dependencies": {
42
- "@unieai/rabi-brand": "0.2.1-rc.3",
43
- "@unieai/rabi-util-values": "0.2.1-rc.3"
40
+ "@unieai/schemastery": "3.19.0",
41
+ "@unieai/rabi-util-values": "0.2.2-rc.5"
44
42
  }
45
43
  }
package/src/index.ts ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Shared messaging, inbox waiting, interruption, and child discovery tools.
3
+ * They perform no lifecycle routing of their own —
4
+ * residency, cold resume, and interrupt authorization belong to the subagent
5
+ * service — and they live apart from the provider-bound
6
+ * `@unieai/rabi-tool-subagent` instances so multiple delegation tools share
7
+ * one control API.
8
+ * @module @unieai/rabi-tool-subagent-control
9
+ */
10
+
11
+ import type { Context } from '@unieai/cordis'
12
+ import z from '@unieai/schemastery'
13
+ import { defineTool } from '@unieai/rabi-tools'
14
+ import type { ContentBlock } from '@unieai/rabi-llm'
15
+ import { ROOT_AGENT_NAME } from '@unieai/rabi-subagent'
16
+ import type {} from '@unieai/rabi-system-prompt'
17
+ import { registerListAgents } from './list-agents.ts'
18
+ import { registerWaitAgent } from './wait-agent.ts'
19
+
20
+ export const name = 'tool-subagent-control'
21
+ export const inject = ['tools', 'subagents', 'agents', 'systemPrompt']
22
+
23
+ /** Optional subagent control tools. */
24
+ export interface Config {
25
+ /** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */
26
+ interrupt?: boolean
27
+ }
28
+
29
+ /** Loader schema for optional subagent control tools. */
30
+ export const Config: z<Config> = z.object({
31
+ interrupt: z.boolean().default(true),
32
+ })
33
+
34
+ /**
35
+ * Register the shared subagent control and discovery tools.
36
+ * @param ctx - context carrying tools, subagents, live Agents, and prompt assembly.
37
+ * @param config - optional tool registration settings.
38
+ */
39
+ export function apply(ctx: Context, config: Config = {}): void {
40
+ const interrupt = config.interrupt !== false
41
+ const listAgents = registerListAgents(ctx)
42
+ registerWaitAgent(ctx)
43
+ const sendMessage = defineTool({
44
+ name: 'send_message',
45
+ description:
46
+ 'Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. '
47
+ + 'Returns delivery confirmation.',
48
+ parameters: {
49
+ agent: {
50
+ type: 'string',
51
+ required: true,
52
+ description: 'The name of another agent in your subagent tree, as shown by list_agents.',
53
+ },
54
+ message: {
55
+ type: 'string',
56
+ required: true,
57
+ description: 'The message to deliver to the agent.',
58
+ },
59
+ },
60
+ output: {
61
+ schema: {
62
+ type: 'object',
63
+ additionalProperties: false,
64
+ properties: {
65
+ messageId: { type: 'string', required: true },
66
+ },
67
+ },
68
+ render: (args, _value) => [{
69
+ type: 'text',
70
+ text: `message delivered to agent ${args.agent}`,
71
+ }],
72
+ },
73
+ async execute(args, exec) {
74
+ const sender = exec.agent
75
+ if (!sender) {
76
+ throw new Error('send_message requires a calling agent (exec.agent was undefined)')
77
+ }
78
+ const message: ContentBlock[] = [{ type: 'text', text: args.message }]
79
+ const targetId = await ctx.subagents.resolveName(sender, args.agent, exec.signal)
80
+ const messageId = await ctx.subagents.sendMessage(sender, targetId, message, { signal: exec.signal })
81
+ return { messageId }
82
+ },
83
+ })
84
+ ctx.tools.register(sendMessage)
85
+ ctx.systemPrompt.context({
86
+ name: 'subagent:identity',
87
+ order: ctx.systemPrompt.getContextOrder('SUBAGENT_DELEGATION'),
88
+ required: true,
89
+ interpolate: false,
90
+ text: ({ agent, scope, toolSet }) => {
91
+ if (agent === undefined) return ''
92
+ try {
93
+ const names = ctx.subagents.namesOf(agent)
94
+ let identity = names.parent === undefined
95
+ ? `You are the root agent. Your name is ${JSON.stringify(names.self)}.`
96
+ : `You are a subagent delegated by agent ${JSON.stringify(names.parent)}.\n`
97
+ + `Your name is ${JSON.stringify(names.self)}.\n`
98
+ + `The root agent of your collaboration tree is ${JSON.stringify(ROOT_AGENT_NAME)}.`
99
+ const guidance: string[] = []
100
+ if (ctx.tools.get(sendMessage.name, scope, toolSet) === sendMessage) {
101
+ guidance.push('To message other agents, use send_message({ agent: "<agent-name>", message: "..." }).')
102
+ }
103
+ if (ctx.tools.get(listAgents.name, scope, toolSet) === listAgents) {
104
+ guidance.push('Use list_agents({}) to find your collaborator agents and their names.')
105
+ }
106
+ if (guidance.length > 0) identity += '\n\n' + guidance.join('\n')
107
+ return identity
108
+ } catch (error: unknown) {
109
+ const rootUnavailable = typeof error === 'object' && error !== null
110
+ && 'name' in error && error.name === 'SubagentError'
111
+ && 'code' in error && error.code === 'UNAUTHORIZED'
112
+ if (!rootUnavailable) throw error
113
+ return `Your agent id is ${JSON.stringify(agent.id)}. Your subagent tree root is unavailable. `
114
+ + 'Continue independent work; subagent discovery and messaging require an active root.'
115
+ }
116
+ },
117
+ })
118
+ if (!interrupt) return
119
+ ctx.tools.register(defineTool({
120
+ name: 'interrupt_agent',
121
+ description:
122
+ 'Ask a subagent to stop its current work. This call returns without waiting for it to stop. '
123
+ + 'You can continue a local subagent\'s conversation later with send_message. '
124
+ + 'External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.',
125
+ parameters: {
126
+ agent: {
127
+ type: 'string',
128
+ required: true,
129
+ description: 'The name of an agent created under you: your direct child or a deeper descendant.',
130
+ },
131
+ },
132
+ output: {
133
+ schema: {
134
+ type: 'object',
135
+ additionalProperties: false,
136
+ properties: {
137
+ accepted: { type: 'boolean', required: true },
138
+ },
139
+ },
140
+ render: (args, _value) => [{
141
+ type: 'text',
142
+ text: `interrupt requested for agent ${args.agent}`,
143
+ }],
144
+ },
145
+ async execute(args, exec) {
146
+ const caller = exec.agent
147
+ if (!caller) {
148
+ // Ancestor authority requires an exact live calling agent.
149
+ throw new Error('interrupt_agent requires a calling agent (exec.agent was undefined)')
150
+ }
151
+ const targetId = await ctx.subagents.resolveName(caller, args.agent, exec.signal)
152
+ // The service authorizes the exact live caller against the target's
153
+ // recorded lineage; the tool adds no authority of its own.
154
+ ctx.subagents.interrupt(targetId, { kind: 'ancestor', agent: caller })
155
+ return { accepted: true }
156
+ },
157
+ }))
158
+ }
@@ -0,0 +1,97 @@
1
+ /** Discover the caller's entire subagent tree; the control plugin owns registration. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import { defineTool } from '@unieai/rabi-tools'
5
+ import type { ToolDefinition } from '@unieai/rabi-tools'
6
+ import type { Agent } from '@unieai/rabi-agent'
7
+ import type { SessionId } from '@unieai/rabi-session'
8
+ import { ROOT_AGENT_NAME } from '@unieai/rabi-subagent'
9
+ import type { SubagentDescendantListEntry } from '@unieai/rabi-subagent'
10
+
11
+
12
+ type ListAgentsStatus = 'running' | 'inactive' | 'corrupt' | 'unsupported' | 'unavailable'
13
+
14
+ /** One model-facing tree member; unreadable branches report their failure as status. */
15
+ interface ListAgentsEntry {
16
+ readonly name: string
17
+ readonly status: ListAgentsStatus
18
+ readonly description?: string
19
+ }
20
+
21
+ /** Report turn activity without exposing whether the child is loaded. */
22
+ function statusOf(agents: { get(id: SessionId): Agent | undefined }, id: SessionId): 'running' | 'inactive' {
23
+ return agents.get(id)?.status === 'running' ? 'running' : 'inactive'
24
+ }
25
+
26
+ /** Project one service row into the model-facing entry, or omit a one-shot or external child. */
27
+ function project(
28
+ agents: { get(id: SessionId): Agent | undefined },
29
+ entry: SubagentDescendantListEntry,
30
+ ): ListAgentsEntry | undefined {
31
+ const name = entry.path ?? entry.id
32
+ if (entry.kind === 'diagnostic') return { name, status: entry.reason }
33
+ // One-shot children cannot be continued by send_message, so the model
34
+ // never selects them; discovery still traversed them for descendants.
35
+ if (entry.mode !== 'continuable') return undefined
36
+ return { name, status: statusOf(agents, entry.id), description: entry.label }
37
+ }
38
+
39
+ /**
40
+ * Register the `list_agents` tool.
41
+ * @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
42
+ * @returns the registered definition for scoped availability checks.
43
+ */
44
+ export function registerListAgents(ctx: Context): ToolDefinition {
45
+ const definition = defineTool({
46
+ name: 'list_agents',
47
+ description:
48
+ 'List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. '
49
+ + 'Rows carry names, descriptions, and status. A descendant\'s name is its path from the root, such as reviewer/checker. '
50
+ + 'You can message any other agent in the subagent tree. '
51
+ + 'running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. '
52
+ + 'corrupt, unsupported, or unavailable means this row\'s own descendants could not be read; the row itself is '
53
+ + 'still a member you can message. '
54
+ + 'While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. '
55
+ + 'Use send_message to continue the conversation.',
56
+ parameters: {},
57
+ // Catalog observations are read-only and release their Session handles.
58
+ isConcurrencySafe: () => true,
59
+ output: {
60
+ schema: {
61
+ type: 'array',
62
+ items: {
63
+ type: 'object',
64
+ additionalProperties: false,
65
+ properties: {
66
+ name: { type: 'string', required: true },
67
+ status: { type: 'string', required: true, enum: ['running', 'inactive', 'corrupt', 'unsupported', 'unavailable'] },
68
+ description: { type: 'string' },
69
+ },
70
+ },
71
+ },
72
+ render: (_args, entries) => [{
73
+ type: 'text',
74
+ text: entries.map(entry =>
75
+ `${entry.name} [${entry.status}]${entry.description === undefined ? '' : ` — ${entry.description}`}`,
76
+ ).join('\n'),
77
+ }],
78
+ },
79
+ async execute(_args, exec) {
80
+ const parent = exec.agent
81
+ if (!parent) {
82
+ // Non-agent callers have no session whose children could be listed.
83
+ throw new Error('list_agents requires a calling agent (exec.agent was undefined)')
84
+ }
85
+ const root = ctx.subagents.rootOf(parent)
86
+ const entries = await ctx.subagents.listDescendants(root.id, exec.signal)
87
+ return [
88
+ { name: ROOT_AGENT_NAME, status: statusOf(ctx.agents, root.id), description: 'root agent' },
89
+ ...entries
90
+ .map(entry => project(ctx.agents, entry))
91
+ .filter(entry => entry !== undefined),
92
+ ]
93
+ },
94
+ })
95
+ ctx.tools.register(definition)
96
+ return definition
97
+ }
@@ -0,0 +1,118 @@
1
+ /** Input waiting owned by the subagent control plugin. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import type { Agent } from '@unieai/rabi-agent'
5
+ import type { MessageId, ToolCallId } from '@unieai/rabi-llm'
6
+ import { HarnessError } from '@unieai/rabi-llm'
7
+ import { defineTool } from '@unieai/rabi-tools'
8
+
9
+ /** Wait failures retain a stable machine-readable reason through tool execution. */
10
+ class AgentWaitError extends HarnessError {
11
+ constructor(message: string, code: 'WAIT_INVALID_TIMEOUT' | 'WAIT_UNAVAILABLE') {
12
+ super(message, code)
13
+ this.name = 'AgentWaitError'
14
+ }
15
+ }
16
+
17
+ /** Pending input ids that the latest successful wait of one model tool call reported. */
18
+ type ReportedInput = WeakMap<Agent, { readonly rootCallId: ToolCallId; readonly ids: ReadonlySet<MessageId> }>
19
+
20
+ /**
21
+ * Wait without consuming input; every settlement removes its live resources.
22
+ * Within one model tool call, such as a `run_code` program, pending input that
23
+ * an earlier wait already reported does not end this wait: that input reaches
24
+ * the model only after the call finishes, so a waiting loop cannot spin on it.
25
+ */
26
+ function waitForInput(
27
+ ctx: Context,
28
+ agent: Agent,
29
+ timeoutMs: number,
30
+ signal: AbortSignal,
31
+ lifetime: AbortSignal,
32
+ reported: ReportedInput,
33
+ rootCallId: ToolCallId,
34
+ ): Promise<{ timedOut: boolean }> {
35
+ lifetime.throwIfAborted()
36
+ if (ctx.agents.get(agent.id) !== agent) {
37
+ throw new AgentWaitError('wait_agent requires the exact live calling agent', 'WAIT_UNAVAILABLE')
38
+ }
39
+ const previous = reported.get(agent)
40
+ const seen = previous?.rootCallId === rootCallId ? previous.ids : undefined
41
+ return new Promise((resolve, reject) => {
42
+ const finish = (settle: () => void): void => {
43
+ clearTimeout(timer)
44
+ offInbox()
45
+ offDisposed()
46
+ signal.removeEventListener('abort', onAbort)
47
+ lifetime.removeEventListener('abort', onUnload)
48
+ settle()
49
+ }
50
+ const onInput = (): void => {
51
+ const pending = agent.inbox.nextStep
52
+ if (pending.some(message => seen?.has(message.id) !== true)) {
53
+ reported.set(agent, { rootCallId, ids: new Set(pending.map(message => message.id)) })
54
+ finish(() => { resolve({ timedOut: false }) })
55
+ }
56
+ }
57
+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- Cancellation preserves the caller's exact AbortSignal reason.
58
+ const onAbort = (): void => { finish(() => { reject(signal.reason) }) }
59
+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- This plugin aborts its lifetime only with AgentWaitError.
60
+ const onUnload = (): void => { finish(() => { reject(lifetime.reason) }) }
61
+ const offInbox = ctx.on('agent/inbox/inserted', ({ agent: recipient }) => {
62
+ if (recipient === agent) onInput()
63
+ })
64
+ const offDisposed = ctx.on('agent/disposed', ({ agent: disposed }) => {
65
+ if (disposed === agent) {
66
+ finish(() => {
67
+ reject(new AgentWaitError('wait_agent ended because the calling agent was disposed', 'WAIT_UNAVAILABLE'))
68
+ })
69
+ }
70
+ })
71
+ signal.addEventListener('abort', onAbort, { once: true })
72
+ lifetime.addEventListener('abort', onUnload, { once: true })
73
+ const timer = setTimeout(() => { finish(() => { resolve({ timedOut: true }) }) }, timeoutMs)
74
+ // Subscribe before reading pending input so an arrival cannot fall between them.
75
+ if (signal.aborted) onAbort()
76
+ else onInput()
77
+ })
78
+ }
79
+
80
+ /**
81
+ * Register one inbox wait tool and cancel its waits when the plugin unloads.
82
+ * @param ctx - plugin context owning the tool, event listeners, and wait lifetime.
83
+ */
84
+ export function registerWaitAgent(ctx: Context): void {
85
+ const lifetime = new AbortController()
86
+ const reported: ReportedInput = new WeakMap()
87
+ ctx.effect(() => () => {
88
+ lifetime.abort(new AgentWaitError('wait_agent ended because its plugin was unloaded', 'WAIT_UNAVAILABLE'))
89
+ }, 'subagent-control.waits()')
90
+ ctx.tools.register(defineTool({
91
+ name: 'wait_agent',
92
+ description: 'Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.',
93
+ parameters: {
94
+ timeout_ms: {
95
+ type: 'integer',
96
+ description: 'Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000.',
97
+ },
98
+ },
99
+ output: {
100
+ schema: {
101
+ type: 'object',
102
+ additionalProperties: false,
103
+ properties: { timedOut: { type: 'boolean', required: true } },
104
+ },
105
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
106
+ },
107
+ async execute(args, exec) {
108
+ const timeoutMs = args.timeout_ms ?? 30_000
109
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 10_000 || timeoutMs > 3_600_000) {
110
+ throw new AgentWaitError('timeout_ms must be an integer from 10000 through 3600000', 'WAIT_INVALID_TIMEOUT')
111
+ }
112
+ if (exec.agent === undefined) {
113
+ throw new AgentWaitError('wait_agent requires a calling agent', 'WAIT_UNAVAILABLE')
114
+ }
115
+ return await waitForInput(ctx, exec.agent, timeoutMs, exec.signal, lifetime.signal, reported, exec.rootCallId)
116
+ },
117
+ }))
118
+ }
@@ -1,97 +0,0 @@
1
- /**
2
- * The globally named `send_message` and `interrupt_agent` tools: thin
3
- * model-facing adapters over `ctx.subagents.sendMessage()` and
4
- * `ctx.subagents.interrupt()`. They perform no lifecycle routing of their own —
5
- * residency, cold resume, and interrupt authorization belong to the subagent
6
- * service — and they live apart from the provider-bound
7
- * `@unieai/rabi-tool-subagent` instances so multiple delegation tools share
8
- * one control API.
9
- * @module @unieai/rabi-tool-subagent-control
10
- */
11
- import { brandString } from '@unieai/rabi-brand';
12
- import { defineTool } from '@unieai/rabi-tools';
13
- import { markAdjacentAgentSendMessageTool } from '@unieai/rabi-subagent/internal';
14
- export const name = 'tool-subagent-control';
15
- export const inject = ['tools', 'subagents'];
16
- /**
17
- * Register the `send_message` and `interrupt_agent` tools.
18
- * @param ctx - context carrying the tool registry and subagent service.
19
- */
20
- export function apply(ctx) {
21
- ctx.tools.register(markAdjacentAgentSendMessageTool(defineTool({
22
- name: 'send_message',
23
- description: 'Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. '
24
- + 'Returns delivery confirmation, not the agent\'s answer.',
25
- parameters: {
26
- agent_id: {
27
- type: 'string',
28
- required: true,
29
- description: 'The agent id of your direct continuable child, or your direct parent when you are a resident continuable child.',
30
- },
31
- message: {
32
- type: 'string',
33
- required: true,
34
- description: 'The message to deliver to the agent.',
35
- },
36
- },
37
- output: {
38
- schema: {
39
- type: 'object',
40
- additionalProperties: false,
41
- properties: {
42
- messageId: { type: 'string', required: true },
43
- },
44
- },
45
- render: (args, _value) => [{
46
- type: 'text',
47
- text: `message delivered to agent ${args.agent_id}`,
48
- }],
49
- },
50
- async execute(args, exec) {
51
- const sender = exec.agent;
52
- if (!sender) {
53
- throw new Error('send_message requires a calling agent (exec.agent was undefined)');
54
- }
55
- const message = [{ type: 'text', text: args.message }];
56
- const messageId = await ctx.subagents.sendMessage(sender, brandString(args.agent_id), message, { signal: exec.signal });
57
- return { messageId };
58
- },
59
- })));
60
- ctx.tools.register(defineTool({
61
- name: 'interrupt_agent',
62
- description: 'Ask a subagent to stop its current work. This call returns without waiting for it to stop. '
63
- + 'You can continue a local direct child\'s conversation later with send_message. '
64
- + 'External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.',
65
- parameters: {
66
- agent_id: {
67
- type: 'string',
68
- required: true,
69
- description: 'The id of an agent created under you: your direct child or a deeper descendant.',
70
- },
71
- },
72
- output: {
73
- schema: {
74
- type: 'object',
75
- additionalProperties: false,
76
- properties: {
77
- accepted: { type: 'boolean', required: true },
78
- },
79
- },
80
- render: (args, _value) => [{
81
- type: 'text',
82
- text: `interrupt requested for agent ${args.agent_id}`,
83
- }],
84
- },
85
- execute(args, exec) {
86
- const caller = exec.agent;
87
- if (!caller) {
88
- // Ancestor authority requires an exact live calling agent.
89
- throw new Error('interrupt_agent requires a calling agent (exec.agent was undefined)');
90
- }
91
- // The service authorizes the exact live caller against the target's
92
- // recorded lineage; the tool adds no authority of its own.
93
- ctx.subagents.interrupt(brandString(args.agent_id), { kind: 'ancestor', agent: caller });
94
- return Promise.resolve({ accepted: true });
95
- },
96
- }));
97
- }
@@ -1,135 +0,0 @@
1
- /**
2
- * The globally named `list_agents` tool: a thin model-facing adapter over
3
- * the continuable projection of `ctx.subagents.listChildren()` and, for the
4
- * `descendants` scope, `ctx.subagents.listDescendants()`. It stays separately
5
- * loadable from the root `send_message` plugin so a deployment can register
6
- * continuation delivery without exposing discovery.
7
- * @module @unieai/rabi-tool-subagent-control/list-agents
8
- */
9
- import { defineTool } from '@unieai/rabi-tools';
10
- import { assertNever } from '@unieai/rabi-util-values';
11
- export const name = 'tool-subagent-list-agents';
12
- export const inject = ['tools', 'subagents', 'agents'];
13
- /** Resolve the optional model request into an internal required-scope spec. */
14
- function resolveListAgentsRequest(request) {
15
- return { scope: request.scope ?? 'children' };
16
- }
17
- /** Report turn activity without exposing whether the child is loaded. */
18
- function statusOf(agents, id) {
19
- return agents.get(id)?.status === 'running' ? 'running' : 'inactive';
20
- }
21
- /** Project one service row into the model-facing entry, or omit a one-shot child. */
22
- function project(agents, entry, position) {
23
- const at = position === undefined ? {} : { parent: position.parentId, depth: position.depth };
24
- if ('kind' in entry && entry.kind === 'diagnostic') {
25
- return { kind: 'diagnostic', id: entry.id, reason: entry.reason, ...at };
26
- }
27
- // One-shot children cannot be continued by send_message, so the model
28
- // never selects them; discovery still traversed them for descendants.
29
- if (entry.mode !== 'continuable')
30
- return undefined;
31
- return {
32
- kind: 'child',
33
- id: entry.id,
34
- label: entry.label,
35
- status: statusOf(agents, entry.id),
36
- ...at,
37
- };
38
- }
39
- /**
40
- * Register the `list_agents` tool.
41
- * @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
42
- */
43
- export function apply(ctx) {
44
- ctx.tools.register(defineTool({
45
- name: 'list_agents',
46
- description: 'List subagents you started, with their ids, labels, and status. '
47
- + 'running means it is working; inactive means it is not currently working. '
48
- + 'You will be notified when a subagent finishes; there is no need to keep checking its status. '
49
- + 'Use send_message to continue the conversation.',
50
- parameters: {
51
- scope: {
52
- type: 'string',
53
- enum: ['children', 'descendants'],
54
- description: 'children (default) lists direct children, which accept send_message in any status. '
55
- + 'descendants lists the whole tree below you with each entry\'s parent session id and depth; entries deeper than 1 accept only interrupt_agent.',
56
- },
57
- },
58
- output: {
59
- schema: {
60
- type: 'array',
61
- items: {
62
- oneOf: [
63
- {
64
- type: 'object',
65
- additionalProperties: false,
66
- properties: {
67
- kind: { type: 'string', required: true, enum: ['child'] },
68
- id: { type: 'string', required: true },
69
- label: { type: 'string', required: true },
70
- status: { type: 'string', required: true, enum: ['running', 'inactive'] },
71
- parent: { type: 'string' },
72
- depth: { type: 'number' },
73
- },
74
- },
75
- {
76
- type: 'object',
77
- additionalProperties: false,
78
- properties: {
79
- kind: { type: 'string', required: true, enum: ['diagnostic'] },
80
- id: { type: 'string', required: true },
81
- reason: { type: 'string', required: true, enum: ['corrupt', 'unsupported', 'unavailable'] },
82
- parent: { type: 'string' },
83
- depth: { type: 'number' },
84
- },
85
- },
86
- ],
87
- },
88
- },
89
- render: (args, entries) => {
90
- const request = resolveListAgentsRequest(args);
91
- return [{
92
- type: 'text',
93
- text: entries.length === 0
94
- ? '(no subagents)'
95
- : entries.map((entry) => {
96
- // A descendants row always carries its position; children rows
97
- // never render it. String() spans the schema-optional shape
98
- // without a dead fallback branch.
99
- const at = request.scope === 'descendants'
100
- ? ` parent=${String(entry.parent)} depth=${String(entry.depth)}`
101
- : '';
102
- return entry.kind === 'child'
103
- ? `${entry.id} [${entry.status}]${at} — ${entry.label}`
104
- : `${entry.id} [diagnostic: ${entry.reason}]${at}`;
105
- }).join('\n'),
106
- }];
107
- },
108
- },
109
- async execute(args, exec) {
110
- const parent = exec.agent;
111
- if (!parent) {
112
- // Non-agent callers have no session whose children could be listed.
113
- throw new Error('list_agents requires a calling agent (exec.agent was undefined)');
114
- }
115
- const request = resolveListAgentsRequest(args);
116
- switch (request.scope) {
117
- case 'children': {
118
- const entries = await ctx.subagents.listChildren(parent.id, exec.signal);
119
- return entries
120
- .map(entry => project(ctx.agents, entry))
121
- .filter(entry => entry !== undefined);
122
- }
123
- case 'descendants': {
124
- const entries = await ctx.subagents.listDescendants(parent.id, exec.signal);
125
- return entries
126
- .map(entry => project(ctx.agents, entry, entry))
127
- .filter(entry => entry !== undefined);
128
- }
129
- /* v8 ignore next 2 -- the resolver normalizes the schema-validated closed scope before dispatch. */
130
- default:
131
- return assertNever(request.scope, 'list_agents scope');
132
- }
133
- },
134
- }));
135
- }
@@ -1,5 +0,0 @@
1
- {
2
- "meta": {
3
- "title": "tool-subagent-control/list-agents"
4
- }
5
- }
@@ -1,5 +0,0 @@
1
- {
2
- "meta": {
3
- "title": "子智能体列表工具"
4
- }
5
- }