mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-07 06:11:37 +00:00
feat(commands): add /subagents spawn command
Add a `spawn` action to the /subagents command handler that invokes spawnSubagentDirect() to deterministically launch a named subagent. Usage: /subagents spawn <agentId> <task> [--model <model>] [--thinking <level>] Also includes the shared subagent-spawn module extraction (same as the refactor/extract-shared-subagent-spawn branch) since it hasn't merged yet. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
committed by
Peter Steinberger
parent
bb5ce3b02f
commit
5a3a448bc4
46
src/auto-reply/reply/commands-spawn.test-harness.ts
Normal file
46
src/auto-reply/reply/commands-spawn.test-harness.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type { MsgContext } from "../templating.js";
|
||||
import { buildCommandContext } from "./commands-context.js";
|
||||
import { parseInlineDirectives } from "./directive-handling.js";
|
||||
|
||||
export function buildCommandTestParams(
|
||||
commandBody: string,
|
||||
cfg: OpenClawConfig,
|
||||
ctxOverrides?: Partial<MsgContext>,
|
||||
) {
|
||||
const ctx = {
|
||||
Body: commandBody,
|
||||
CommandBody: commandBody,
|
||||
CommandSource: "text",
|
||||
CommandAuthorized: true,
|
||||
Provider: "whatsapp",
|
||||
Surface: "whatsapp",
|
||||
...ctxOverrides,
|
||||
} as MsgContext;
|
||||
|
||||
const command = buildCommandContext({
|
||||
ctx,
|
||||
cfg,
|
||||
isGroup: false,
|
||||
triggerBodyNormalized: commandBody.trim().toLowerCase(),
|
||||
commandAuthorized: true,
|
||||
});
|
||||
|
||||
return {
|
||||
ctx,
|
||||
cfg,
|
||||
command,
|
||||
directives: parseInlineDirectives(commandBody),
|
||||
elevated: { enabled: true, allowed: true, failures: [] },
|
||||
sessionKey: "agent:main:main",
|
||||
workspaceDir: "/tmp",
|
||||
defaultGroupActivation: () => "mention",
|
||||
resolvedVerboseLevel: "off" as const,
|
||||
resolvedReasoningLevel: "off" as const,
|
||||
resolveDefaultThinkingLevel: async () => undefined,
|
||||
provider: "whatsapp",
|
||||
model: "test-model",
|
||||
contextTokens: 0,
|
||||
isGroup: false,
|
||||
};
|
||||
}
|
||||
166
src/auto-reply/reply/commands-subagents-spawn.test.ts
Normal file
166
src/auto-reply/reply/commands-subagents-spawn.test.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SpawnSubagentResult } from "../../agents/subagent-spawn.js";
|
||||
import { resetSubagentRegistryForTests } from "../../agents/subagent-registry.js";
|
||||
|
||||
const hoisted = vi.hoisted(() => {
|
||||
const spawnSubagentDirectMock = vi.fn();
|
||||
const callGatewayMock = vi.fn();
|
||||
return { spawnSubagentDirectMock, callGatewayMock };
|
||||
});
|
||||
|
||||
vi.mock("../../agents/subagent-spawn.js", () => ({
|
||||
spawnSubagentDirect: (...args: unknown[]) => hoisted.spawnSubagentDirectMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../gateway/call.js", () => ({
|
||||
callGateway: (opts: unknown) => hoisted.callGatewayMock(opts),
|
||||
}));
|
||||
|
||||
vi.mock("../../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../../config/config.js")>();
|
||||
return {
|
||||
...actual,
|
||||
loadConfig: () => ({}),
|
||||
};
|
||||
});
|
||||
|
||||
// Prevent transitive import chain from reaching discord/monitor which needs https-proxy-agent.
|
||||
vi.mock("../../discord/monitor/gateway-plugin.js", () => ({
|
||||
createDiscordGatewayPlugin: () => ({}),
|
||||
}));
|
||||
|
||||
// Dynamic import to ensure mocks are installed first.
|
||||
const { handleSubagentsCommand } = await import("./commands-subagents.js");
|
||||
const { buildCommandTestParams } = await import("./commands-spawn.test-harness.js");
|
||||
|
||||
const { spawnSubagentDirectMock } = hoisted;
|
||||
|
||||
function acceptedResult(overrides?: Partial<SpawnSubagentResult>): SpawnSubagentResult {
|
||||
return {
|
||||
status: "accepted",
|
||||
childSessionKey: "agent:beta:subagent:test-uuid",
|
||||
runId: "run-spawn-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function forbiddenResult(error: string): SpawnSubagentResult {
|
||||
return {
|
||||
status: "forbidden",
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
const baseCfg = {
|
||||
session: { mainKey: "main", scope: "per-sender" },
|
||||
};
|
||||
|
||||
describe("/subagents spawn command", () => {
|
||||
beforeEach(() => {
|
||||
resetSubagentRegistryForTests();
|
||||
spawnSubagentDirectMock.mockReset();
|
||||
hoisted.callGatewayMock.mockReset();
|
||||
});
|
||||
|
||||
it("shows usage when agentId is missing", async () => {
|
||||
const params = buildCommandTestParams("/subagents spawn", baseCfg);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Usage:");
|
||||
expect(result?.reply?.text).toContain("/subagents spawn");
|
||||
expect(spawnSubagentDirectMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows usage when task is missing", async () => {
|
||||
const params = buildCommandTestParams("/subagents spawn beta", baseCfg);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Usage:");
|
||||
expect(spawnSubagentDirectMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("spawns subagent and confirms reply text and child session key", async () => {
|
||||
spawnSubagentDirectMock.mockResolvedValue(acceptedResult());
|
||||
const params = buildCommandTestParams("/subagents spawn beta do the thing", baseCfg);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Spawned subagent beta");
|
||||
expect(result?.reply?.text).toContain("agent:beta:subagent:test-uuid");
|
||||
expect(result?.reply?.text).toContain("run-spaw");
|
||||
|
||||
expect(spawnSubagentDirectMock).toHaveBeenCalledOnce();
|
||||
const [spawnParams, spawnCtx] = spawnSubagentDirectMock.mock.calls[0];
|
||||
expect(spawnParams.task).toBe("do the thing");
|
||||
expect(spawnParams.agentId).toBe("beta");
|
||||
expect(spawnParams.cleanup).toBe("keep");
|
||||
expect(spawnCtx.agentSessionKey).toBeDefined();
|
||||
});
|
||||
|
||||
it("spawns with --model flag and passes model to spawnSubagentDirect", async () => {
|
||||
spawnSubagentDirectMock.mockResolvedValue(acceptedResult({ modelApplied: true }));
|
||||
const params = buildCommandTestParams(
|
||||
"/subagents spawn beta do the thing --model openai/gpt-4o",
|
||||
baseCfg,
|
||||
);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Spawned subagent beta");
|
||||
|
||||
const [spawnParams] = spawnSubagentDirectMock.mock.calls[0];
|
||||
expect(spawnParams.model).toBe("openai/gpt-4o");
|
||||
expect(spawnParams.task).toBe("do the thing");
|
||||
});
|
||||
|
||||
it("spawns with --thinking flag and passes thinking to spawnSubagentDirect", async () => {
|
||||
spawnSubagentDirectMock.mockResolvedValue(acceptedResult());
|
||||
const params = buildCommandTestParams(
|
||||
"/subagents spawn beta do the thing --thinking high",
|
||||
baseCfg,
|
||||
);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Spawned subagent beta");
|
||||
|
||||
const [spawnParams] = spawnSubagentDirectMock.mock.calls[0];
|
||||
expect(spawnParams.thinking).toBe("high");
|
||||
expect(spawnParams.task).toBe("do the thing");
|
||||
});
|
||||
|
||||
it("returns forbidden for unauthorized cross-agent spawn", async () => {
|
||||
spawnSubagentDirectMock.mockResolvedValue(
|
||||
forbiddenResult("agentId is not allowed for sessions_spawn (allowed: alpha)"),
|
||||
);
|
||||
const params = buildCommandTestParams("/subagents spawn beta do the thing", baseCfg);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Spawn failed");
|
||||
expect(result?.reply?.text).toContain("not allowed");
|
||||
});
|
||||
|
||||
it("allows cross-agent spawn when in allowlist", async () => {
|
||||
spawnSubagentDirectMock.mockResolvedValue(acceptedResult());
|
||||
const params = buildCommandTestParams("/subagents spawn beta do the thing", baseCfg);
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply?.text).toContain("Spawned subagent beta");
|
||||
});
|
||||
|
||||
it("ignores unauthorized sender (silent, no reply)", async () => {
|
||||
const params = buildCommandTestParams("/subagents spawn beta do the thing", baseCfg, {
|
||||
CommandAuthorized: false,
|
||||
});
|
||||
params.command.isAuthorizedSender = false;
|
||||
const result = await handleSubagentsCommand(params, true);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.reply).toBeUndefined();
|
||||
expect(result?.shouldContinue).toBe(false);
|
||||
expect(spawnSubagentDirectMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns null when text commands disabled", async () => {
|
||||
const params = buildCommandTestParams("/subagents spawn beta do the thing", baseCfg);
|
||||
const result = await handleSubagentsCommand(params, false);
|
||||
expect(result).toBeNull();
|
||||
expect(spawnSubagentDirectMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
markSubagentRunForSteerRestart,
|
||||
replaceSubagentRunAfterSteer,
|
||||
} from "../../agents/subagent-registry.js";
|
||||
import { spawnSubagentDirect } from "../../agents/subagent-spawn.js";
|
||||
import {
|
||||
extractAssistantText,
|
||||
resolveInternalSessionKey,
|
||||
@@ -47,7 +48,7 @@ const COMMAND = "/subagents";
|
||||
const COMMAND_KILL = "/kill";
|
||||
const COMMAND_STEER = "/steer";
|
||||
const COMMAND_TELL = "/tell";
|
||||
const ACTIONS = new Set(["list", "kill", "log", "send", "steer", "info", "help"]);
|
||||
const ACTIONS = new Set(["list", "kill", "log", "send", "steer", "info", "spawn", "help"]);
|
||||
const RECENT_WINDOW_MINUTES = 30;
|
||||
const SUBAGENT_TASK_PREVIEW_MAX = 110;
|
||||
const STEER_ABORT_SETTLE_TIMEOUT_MS = 5_000;
|
||||
@@ -192,6 +193,7 @@ function buildSubagentsHelp() {
|
||||
"- /subagents info <id|#>",
|
||||
"- /subagents send <id|#> <message>",
|
||||
"- /subagents steer <id|#> <message>",
|
||||
"- /subagents spawn <agentId> <task> [--model <model>] [--thinking <level>]",
|
||||
"- /kill <id|#|all>",
|
||||
"- /steer <id|#> <message>",
|
||||
"- /tell <id|#> <message>",
|
||||
@@ -644,5 +646,56 @@ export const handleSubagentsCommand: CommandHandler = async (params, allowTextCo
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "spawn") {
|
||||
const agentId = restTokens[0];
|
||||
// Parse remaining tokens: task text with optional --model and --thinking flags.
|
||||
const taskParts: string[] = [];
|
||||
let model: string | undefined;
|
||||
let thinking: string | undefined;
|
||||
for (let i = 1; i < restTokens.length; i++) {
|
||||
if (restTokens[i] === "--model" && i + 1 < restTokens.length) {
|
||||
i += 1;
|
||||
model = restTokens[i];
|
||||
} else if (restTokens[i] === "--thinking" && i + 1 < restTokens.length) {
|
||||
i += 1;
|
||||
thinking = restTokens[i];
|
||||
} else {
|
||||
taskParts.push(restTokens[i]);
|
||||
}
|
||||
}
|
||||
const task = taskParts.join(" ").trim();
|
||||
if (!agentId || !task) {
|
||||
return {
|
||||
shouldContinue: false,
|
||||
reply: {
|
||||
text: "Usage: /subagents spawn <agentId> <task> [--model <model>] [--thinking <level>]",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const result = await spawnSubagentDirect(
|
||||
{ task, agentId, model, thinking, cleanup: "keep" },
|
||||
{
|
||||
agentSessionKey: requesterKey,
|
||||
agentChannel: params.command.channel,
|
||||
agentAccountId: params.ctx.AccountId,
|
||||
agentTo: params.command.to,
|
||||
agentThreadId: params.ctx.MessageThreadId,
|
||||
},
|
||||
);
|
||||
if (result.status === "accepted") {
|
||||
return {
|
||||
shouldContinue: false,
|
||||
reply: {
|
||||
text: `Spawned subagent ${agentId} (session ${result.childSessionKey}, run ${result.runId?.slice(0, 8)}).${result.warning ? ` Warning: ${result.warning}` : ""}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
shouldContinue: false,
|
||||
reply: { text: `Spawn failed: ${result.error ?? result.status}` },
|
||||
};
|
||||
}
|
||||
|
||||
return { shouldContinue: false, reply: { text: buildSubagentsHelp() } };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user