mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-07 19:31:24 +00:00
feat: ACP thread-bound agents (#23580)
* docs: add ACP thread-bound agents plan doc * docs: expand ACP implementation specification * feat(acp): route ACP sessions through core dispatch and lifecycle cleanup * feat(acp): add /acp commands and Discord spawn gate * ACP: add acpx runtime plugin backend * fix(subagents): defer transient lifecycle errors before announce * Agents: harden ACP sessions_spawn and tighten spawn guidance * Agents: require explicit ACP target for runtime spawns * docs: expand ACP control-plane implementation plan * ACP: harden metadata seeding and spawn guidance * ACP: centralize runtime control-plane manager and fail-closed dispatch * ACP: harden runtime manager and unify spawn helpers * Commands: route ACP sessions through ACP runtime in agent command * ACP: require persisted metadata for runtime spawns * Sessions: preserve ACP metadata when updating entries * Plugins: harden ACP backend registry across loaders * ACPX: make availability probe compatible with adapters * E2E: add manual Discord ACP plain-language smoke script * ACPX: preserve streamed spacing across Discord delivery * Docs: add ACP Discord streaming strategy * ACP: harden Discord stream buffering for thread replies * ACP: reuse shared block reply pipeline for projector * ACP: unify streaming config and adopt coalesceIdleMs * Docs: add temporary ACP production hardening plan * Docs: trim temporary ACP hardening plan goals * Docs: gate ACP thread controls by backend capabilities * ACP: add capability-gated runtime controls and /acp operator commands * Docs: remove temporary ACP hardening plan * ACP: fix spawn target validation and close cache cleanup * ACP: harden runtime dispatch and recovery paths * ACP: split ACP command/runtime internals and centralize policy * ACP: harden runtime lifecycle, validation, and observability * ACP: surface runtime and backend session IDs in thread bindings * docs: add temp plan for binding-service migration * ACP: migrate thread binding flows to SessionBindingService * ACP: address review feedback and preserve prompt wording * ACPX plugin: pin runtime dependency and prefer bundled CLI * Discord: complete binding-service migration cleanup and restore ACP plan * Docs: add standalone ACP agents guide * ACP: route harness intents to thread-bound ACP sessions * ACP: fix spawn thread routing and queue-owner stall * ACP: harden startup reconciliation and command bypass handling * ACP: fix dispatch bypass type narrowing * ACP: align runtime metadata to agentSessionId * ACP: normalize session identifier handling and labels * ACP: mark thread banner session ids provisional until first reply * ACP: stabilize session identity mapping and startup reconciliation * ACP: add resolved session-id notices and cwd in thread intros * Discord: prefix thread meta notices consistently * Discord: unify ACP/thread meta notices with gear prefix * Discord: split thread persona naming from meta formatting * Extensions: bump acpx plugin dependency to 0.1.9 * Agents: gate ACP prompt guidance behind acp.enabled * Docs: remove temp experiment plan docs * Docs: scope streaming plan to holy grail refactor * Docs: refactor ACP agents guide for human-first flow * Docs/Skill: add ACP feature-flag guidance and direct acpx telephone-game flow * Docs/Skill: add OpenCode and Pi to ACP harness lists * Docs/Skill: align ACP harness list with current acpx registry * Dev/Test: move ACP plain-language smoke script and mark as keep * Docs/Skill: reorder ACP harness lists with Pi first * ACP: split control-plane manager into core/types/utils modules * Docs: refresh ACP thread-bound agents plan * ACP: extract dispatch lane and split manager domains * ACP: centralize binding context and remove reverse deps * Infra: unify system message formatting * ACP: centralize error boundaries and session id rendering * ACP: enforce init concurrency cap and strict meta clear * Tests: fix ACP dispatch binding mock typing * Tests: fix Discord thread-binding mock drift and ACP request id * ACP: gate slash bypass and persist cleared overrides * ACPX: await pre-abort cancel before runTurn return * Extension: pin acpx runtime dependency to 0.1.11 * Docs: add pinned acpx install strategy for ACP extension * Extensions/acpx: enforce strict local pinned startup * Extensions/acpx: tighten acp-router install guidance * ACPX: retry runtime test temp-dir cleanup * Extensions/acpx: require proactive ACPX repair for thread spawns * Extensions/acpx: require restart offer after acpx reinstall * extensions/acpx: remove workspace protocol devDependency * extensions/acpx: bump pinned acpx to 0.1.13 * extensions/acpx: sync lockfile after dependency bump * ACPX: make runtime spawn Windows-safe * fix: align doctor-config-flow repair tests with default-account migration (#23580) (thanks @osolmaz)
This commit is contained in:
42
src/agents/acp-binding-architecture.guardrail.test.ts
Normal file
42
src/agents/acp-binding-architecture.guardrail.test.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const ROOT_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
type GuardedSource = {
|
||||
path: string;
|
||||
forbiddenPatterns: RegExp[];
|
||||
};
|
||||
|
||||
const GUARDED_SOURCES: GuardedSource[] = [
|
||||
{
|
||||
path: "agents/acp-spawn.ts",
|
||||
forbiddenPatterns: [/\bgetThreadBindingManager\b/, /\bparseDiscordTarget\b/],
|
||||
},
|
||||
{
|
||||
path: "auto-reply/reply/commands-acp/lifecycle.ts",
|
||||
forbiddenPatterns: [/\bgetThreadBindingManager\b/, /\bunbindThreadBindingsBySessionKey\b/],
|
||||
},
|
||||
{
|
||||
path: "auto-reply/reply/commands-acp/targets.ts",
|
||||
forbiddenPatterns: [/\bgetThreadBindingManager\b/],
|
||||
},
|
||||
{
|
||||
path: "auto-reply/reply/commands-subagents/action-focus.ts",
|
||||
forbiddenPatterns: [/\bgetThreadBindingManager\b/],
|
||||
},
|
||||
];
|
||||
|
||||
describe("ACP/session binding architecture guardrails", () => {
|
||||
it("keeps ACP/focus flows off Discord thread-binding manager APIs", () => {
|
||||
for (const source of GUARDED_SOURCES) {
|
||||
const absolutePath = resolve(ROOT_DIR, source.path);
|
||||
const text = readFileSync(absolutePath, "utf8");
|
||||
for (const pattern of source.forbiddenPatterns) {
|
||||
expect(text).not.toMatch(pattern);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
373
src/agents/acp-spawn.test.ts
Normal file
373
src/agents/acp-spawn.test.ts
Normal file
@@ -0,0 +1,373 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import type { SessionBindingRecord } from "../infra/outbound/session-binding-service.js";
|
||||
|
||||
const hoisted = vi.hoisted(() => {
|
||||
const callGatewayMock = vi.fn();
|
||||
const sessionBindingCapabilitiesMock = vi.fn();
|
||||
const sessionBindingBindMock = vi.fn();
|
||||
const sessionBindingUnbindMock = vi.fn();
|
||||
const sessionBindingResolveByConversationMock = vi.fn();
|
||||
const sessionBindingListBySessionMock = vi.fn();
|
||||
const closeSessionMock = vi.fn();
|
||||
const initializeSessionMock = vi.fn();
|
||||
const state = {
|
||||
cfg: {
|
||||
acp: {
|
||||
enabled: true,
|
||||
backend: "acpx",
|
||||
allowedAgents: ["codex"],
|
||||
},
|
||||
session: {
|
||||
mainKey: "main",
|
||||
scope: "per-sender",
|
||||
},
|
||||
channels: {
|
||||
discord: {
|
||||
threadBindings: {
|
||||
enabled: true,
|
||||
spawnAcpSessions: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
} as OpenClawConfig,
|
||||
};
|
||||
return {
|
||||
callGatewayMock,
|
||||
sessionBindingCapabilitiesMock,
|
||||
sessionBindingBindMock,
|
||||
sessionBindingUnbindMock,
|
||||
sessionBindingResolveByConversationMock,
|
||||
sessionBindingListBySessionMock,
|
||||
closeSessionMock,
|
||||
initializeSessionMock,
|
||||
state,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../config/config.js")>();
|
||||
return {
|
||||
...actual,
|
||||
loadConfig: () => hoisted.state.cfg,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../gateway/call.js", () => ({
|
||||
callGateway: (opts: unknown) => hoisted.callGatewayMock(opts),
|
||||
}));
|
||||
|
||||
vi.mock("../acp/control-plane/manager.js", () => {
|
||||
return {
|
||||
getAcpSessionManager: () => ({
|
||||
initializeSession: (params: unknown) => hoisted.initializeSessionMock(params),
|
||||
closeSession: (params: unknown) => hoisted.closeSessionMock(params),
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../infra/outbound/session-binding-service.js", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("../infra/outbound/session-binding-service.js")>();
|
||||
return {
|
||||
...actual,
|
||||
getSessionBindingService: () => ({
|
||||
bind: (input: unknown) => hoisted.sessionBindingBindMock(input),
|
||||
getCapabilities: (params: unknown) => hoisted.sessionBindingCapabilitiesMock(params),
|
||||
listBySession: (targetSessionKey: string) =>
|
||||
hoisted.sessionBindingListBySessionMock(targetSessionKey),
|
||||
resolveByConversation: (ref: unknown) => hoisted.sessionBindingResolveByConversationMock(ref),
|
||||
touch: vi.fn(),
|
||||
unbind: (input: unknown) => hoisted.sessionBindingUnbindMock(input),
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const { spawnAcpDirect } = await import("./acp-spawn.js");
|
||||
|
||||
function createSessionBinding(overrides?: Partial<SessionBindingRecord>): SessionBindingRecord {
|
||||
return {
|
||||
bindingId: "default:child-thread",
|
||||
targetSessionKey: "agent:codex:acp:s1",
|
||||
targetKind: "session",
|
||||
conversation: {
|
||||
channel: "discord",
|
||||
accountId: "default",
|
||||
conversationId: "child-thread",
|
||||
parentConversationId: "parent-channel",
|
||||
},
|
||||
status: "active",
|
||||
boundAt: Date.now(),
|
||||
metadata: {
|
||||
agentId: "codex",
|
||||
boundBy: "system",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("spawnAcpDirect", () => {
|
||||
beforeEach(() => {
|
||||
hoisted.state.cfg = {
|
||||
acp: {
|
||||
enabled: true,
|
||||
backend: "acpx",
|
||||
allowedAgents: ["codex"],
|
||||
},
|
||||
session: {
|
||||
mainKey: "main",
|
||||
scope: "per-sender",
|
||||
},
|
||||
channels: {
|
||||
discord: {
|
||||
threadBindings: {
|
||||
enabled: true,
|
||||
spawnAcpSessions: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies OpenClawConfig;
|
||||
|
||||
hoisted.callGatewayMock.mockReset().mockImplementation(async (argsUnknown: unknown) => {
|
||||
const args = argsUnknown as { method?: string };
|
||||
if (args.method === "sessions.patch") {
|
||||
return { ok: true };
|
||||
}
|
||||
if (args.method === "agent") {
|
||||
return { runId: "run-1" };
|
||||
}
|
||||
if (args.method === "sessions.delete") {
|
||||
return { ok: true };
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
hoisted.closeSessionMock.mockReset().mockResolvedValue({
|
||||
runtimeClosed: true,
|
||||
metaCleared: false,
|
||||
});
|
||||
hoisted.initializeSessionMock.mockReset().mockImplementation(async (argsUnknown: unknown) => {
|
||||
const args = argsUnknown as {
|
||||
sessionKey: string;
|
||||
agent: string;
|
||||
mode: "persistent" | "oneshot";
|
||||
cwd?: string;
|
||||
};
|
||||
const runtimeSessionName = `${args.sessionKey}:runtime`;
|
||||
const cwd = typeof args.cwd === "string" ? args.cwd : undefined;
|
||||
return {
|
||||
runtime: {
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
handle: {
|
||||
sessionKey: args.sessionKey,
|
||||
backend: "acpx",
|
||||
runtimeSessionName,
|
||||
...(cwd ? { cwd } : {}),
|
||||
agentSessionId: "codex-inner-1",
|
||||
backendSessionId: "acpx-1",
|
||||
},
|
||||
meta: {
|
||||
backend: "acpx",
|
||||
agent: args.agent,
|
||||
runtimeSessionName,
|
||||
...(cwd ? { runtimeOptions: { cwd }, cwd } : {}),
|
||||
identity: {
|
||||
state: "pending",
|
||||
source: "ensure",
|
||||
acpxSessionId: "acpx-1",
|
||||
agentSessionId: "codex-inner-1",
|
||||
lastUpdatedAt: Date.now(),
|
||||
},
|
||||
mode: args.mode,
|
||||
state: "idle",
|
||||
lastActivityAt: Date.now(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
hoisted.sessionBindingCapabilitiesMock.mockReset().mockReturnValue({
|
||||
adapterAvailable: true,
|
||||
bindSupported: true,
|
||||
unbindSupported: true,
|
||||
placements: ["current", "child"],
|
||||
});
|
||||
hoisted.sessionBindingBindMock
|
||||
.mockReset()
|
||||
.mockImplementation(
|
||||
async (input: {
|
||||
targetSessionKey: string;
|
||||
conversation: { accountId: string };
|
||||
metadata?: Record<string, unknown>;
|
||||
}) =>
|
||||
createSessionBinding({
|
||||
targetSessionKey: input.targetSessionKey,
|
||||
conversation: {
|
||||
channel: "discord",
|
||||
accountId: input.conversation.accountId,
|
||||
conversationId: "child-thread",
|
||||
parentConversationId: "parent-channel",
|
||||
},
|
||||
metadata: {
|
||||
boundBy:
|
||||
typeof input.metadata?.boundBy === "string" ? input.metadata.boundBy : "system",
|
||||
agentId: "codex",
|
||||
webhookId: "wh-1",
|
||||
},
|
||||
}),
|
||||
);
|
||||
hoisted.sessionBindingResolveByConversationMock.mockReset().mockReturnValue(null);
|
||||
hoisted.sessionBindingListBySessionMock.mockReset().mockReturnValue([]);
|
||||
hoisted.sessionBindingUnbindMock.mockReset().mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("spawns ACP session, binds a new thread, and dispatches initial task", async () => {
|
||||
const result = await spawnAcpDirect(
|
||||
{
|
||||
task: "Investigate flaky tests",
|
||||
agentId: "codex",
|
||||
mode: "session",
|
||||
thread: true,
|
||||
},
|
||||
{
|
||||
agentSessionKey: "agent:main:main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "default",
|
||||
agentTo: "channel:parent-channel",
|
||||
agentThreadId: "requester-thread",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).toBe("accepted");
|
||||
expect(result.childSessionKey).toMatch(/^agent:codex:acp:/);
|
||||
expect(result.runId).toBe("run-1");
|
||||
expect(result.mode).toBe("session");
|
||||
expect(hoisted.sessionBindingBindMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
targetKind: "session",
|
||||
placement: "child",
|
||||
}),
|
||||
);
|
||||
expect(hoisted.sessionBindingBindMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: expect.objectContaining({
|
||||
introText: expect.not.stringContaining(
|
||||
"session ids: pending (available after the first reply)",
|
||||
),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const agentCall = hoisted.callGatewayMock.mock.calls
|
||||
.map((call: unknown[]) => call[0] as { method?: string; params?: Record<string, unknown> })
|
||||
.find((request) => request.method === "agent");
|
||||
expect(agentCall?.params?.sessionKey).toMatch(/^agent:codex:acp:/);
|
||||
expect(agentCall?.params?.to).toBe("channel:child-thread");
|
||||
expect(agentCall?.params?.threadId).toBe("child-thread");
|
||||
expect(agentCall?.params?.deliver).toBe(true);
|
||||
expect(hoisted.initializeSessionMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sessionKey: expect.stringMatching(/^agent:codex:acp:/),
|
||||
agent: "codex",
|
||||
mode: "persistent",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("includes cwd in ACP thread intro banner when provided at spawn time", async () => {
|
||||
const result = await spawnAcpDirect(
|
||||
{
|
||||
task: "Check workspace",
|
||||
agentId: "codex",
|
||||
cwd: "/home/bob/clawd",
|
||||
mode: "session",
|
||||
thread: true,
|
||||
},
|
||||
{
|
||||
agentSessionKey: "agent:main:main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "default",
|
||||
agentTo: "channel:parent-channel",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).toBe("accepted");
|
||||
expect(hoisted.sessionBindingBindMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
metadata: expect.objectContaining({
|
||||
introText: expect.stringContaining("cwd: /home/bob/clawd"),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects disallowed ACP agents", async () => {
|
||||
hoisted.state.cfg = {
|
||||
...hoisted.state.cfg,
|
||||
acp: {
|
||||
enabled: true,
|
||||
backend: "acpx",
|
||||
allowedAgents: ["claudecode"],
|
||||
},
|
||||
};
|
||||
|
||||
const result = await spawnAcpDirect(
|
||||
{
|
||||
task: "hello",
|
||||
agentId: "codex",
|
||||
},
|
||||
{
|
||||
agentSessionKey: "agent:main:main",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "forbidden",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires an explicit ACP agent when no config default exists", async () => {
|
||||
const result = await spawnAcpDirect(
|
||||
{
|
||||
task: "hello",
|
||||
},
|
||||
{
|
||||
agentSessionKey: "agent:main:main",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.error).toContain("set `acp.defaultAgent`");
|
||||
});
|
||||
|
||||
it("fails fast when Discord ACP thread spawn is disabled", async () => {
|
||||
hoisted.state.cfg = {
|
||||
...hoisted.state.cfg,
|
||||
channels: {
|
||||
discord: {
|
||||
threadBindings: {
|
||||
enabled: true,
|
||||
spawnAcpSessions: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = await spawnAcpDirect(
|
||||
{
|
||||
task: "hello",
|
||||
agentId: "codex",
|
||||
thread: true,
|
||||
mode: "session",
|
||||
},
|
||||
{
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "default",
|
||||
agentTo: "channel:parent-channel",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.error).toContain("spawnAcpSessions=true");
|
||||
});
|
||||
});
|
||||
424
src/agents/acp-spawn.ts
Normal file
424
src/agents/acp-spawn.ts
Normal file
@@ -0,0 +1,424 @@
|
||||
import crypto from "node:crypto";
|
||||
import { getAcpSessionManager } from "../acp/control-plane/manager.js";
|
||||
import {
|
||||
cleanupFailedAcpSpawn,
|
||||
type AcpSpawnRuntimeCloseHandle,
|
||||
} from "../acp/control-plane/spawn.js";
|
||||
import { isAcpEnabledByPolicy, resolveAcpAgentPolicyError } from "../acp/policy.js";
|
||||
import {
|
||||
resolveAcpSessionCwd,
|
||||
resolveAcpThreadSessionDetailLines,
|
||||
} from "../acp/runtime/session-identifiers.js";
|
||||
import type { AcpRuntimeSessionMode } from "../acp/runtime/types.js";
|
||||
import {
|
||||
resolveThreadBindingIntroText,
|
||||
resolveThreadBindingThreadName,
|
||||
} from "../channels/thread-bindings-messages.js";
|
||||
import {
|
||||
formatThreadBindingDisabledError,
|
||||
formatThreadBindingSpawnDisabledError,
|
||||
resolveThreadBindingSessionTtlMsForChannel,
|
||||
resolveThreadBindingSpawnPolicy,
|
||||
} from "../channels/thread-bindings-policy.js";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import { callGateway } from "../gateway/call.js";
|
||||
import { resolveConversationIdFromTargets } from "../infra/outbound/conversation-id.js";
|
||||
import {
|
||||
getSessionBindingService,
|
||||
isSessionBindingError,
|
||||
type SessionBindingRecord,
|
||||
} from "../infra/outbound/session-binding-service.js";
|
||||
import { normalizeAgentId } from "../routing/session-key.js";
|
||||
import { normalizeDeliveryContext } from "../utils/delivery-context.js";
|
||||
|
||||
export const ACP_SPAWN_MODES = ["run", "session"] as const;
|
||||
export type SpawnAcpMode = (typeof ACP_SPAWN_MODES)[number];
|
||||
|
||||
export type SpawnAcpParams = {
|
||||
task: string;
|
||||
label?: string;
|
||||
agentId?: string;
|
||||
cwd?: string;
|
||||
mode?: SpawnAcpMode;
|
||||
thread?: boolean;
|
||||
};
|
||||
|
||||
export type SpawnAcpContext = {
|
||||
agentSessionKey?: string;
|
||||
agentChannel?: string;
|
||||
agentAccountId?: string;
|
||||
agentTo?: string;
|
||||
agentThreadId?: string | number;
|
||||
};
|
||||
|
||||
export type SpawnAcpResult = {
|
||||
status: "accepted" | "forbidden" | "error";
|
||||
childSessionKey?: string;
|
||||
runId?: string;
|
||||
mode?: SpawnAcpMode;
|
||||
note?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export const ACP_SPAWN_ACCEPTED_NOTE =
|
||||
"initial ACP task queued in isolated session; follow-ups continue in the bound thread.";
|
||||
export const ACP_SPAWN_SESSION_ACCEPTED_NOTE =
|
||||
"thread-bound ACP session stays active after this task; continue in-thread for follow-ups.";
|
||||
|
||||
type PreparedAcpThreadBinding = {
|
||||
channel: string;
|
||||
accountId: string;
|
||||
conversationId: string;
|
||||
};
|
||||
|
||||
function resolveSpawnMode(params: {
|
||||
requestedMode?: SpawnAcpMode;
|
||||
threadRequested: boolean;
|
||||
}): SpawnAcpMode {
|
||||
if (params.requestedMode === "run" || params.requestedMode === "session") {
|
||||
return params.requestedMode;
|
||||
}
|
||||
// Thread-bound spawns should default to persistent sessions.
|
||||
return params.threadRequested ? "session" : "run";
|
||||
}
|
||||
|
||||
function resolveAcpSessionMode(mode: SpawnAcpMode): AcpRuntimeSessionMode {
|
||||
return mode === "session" ? "persistent" : "oneshot";
|
||||
}
|
||||
|
||||
function resolveTargetAcpAgentId(params: {
|
||||
requestedAgentId?: string;
|
||||
cfg: OpenClawConfig;
|
||||
}): { ok: true; agentId: string } | { ok: false; error: string } {
|
||||
const requested = normalizeOptionalAgentId(params.requestedAgentId);
|
||||
if (requested) {
|
||||
return { ok: true, agentId: requested };
|
||||
}
|
||||
|
||||
const configuredDefault = normalizeOptionalAgentId(params.cfg.acp?.defaultAgent);
|
||||
if (configuredDefault) {
|
||||
return { ok: true, agentId: configuredDefault };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
"ACP target agent is not configured. Pass `agentId` in `sessions_spawn` or set `acp.defaultAgent` in config.",
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeOptionalAgentId(value: string | undefined | null): string | undefined {
|
||||
const trimmed = (value ?? "").trim();
|
||||
if (!trimmed) {
|
||||
return undefined;
|
||||
}
|
||||
return normalizeAgentId(trimmed);
|
||||
}
|
||||
|
||||
function summarizeError(err: unknown): string {
|
||||
if (err instanceof Error) {
|
||||
return err.message;
|
||||
}
|
||||
if (typeof err === "string") {
|
||||
return err;
|
||||
}
|
||||
return "error";
|
||||
}
|
||||
|
||||
function resolveConversationIdForThreadBinding(params: {
|
||||
to?: string;
|
||||
threadId?: string | number;
|
||||
}): string | undefined {
|
||||
return resolveConversationIdFromTargets({
|
||||
threadId: params.threadId,
|
||||
targets: [params.to],
|
||||
});
|
||||
}
|
||||
|
||||
function prepareAcpThreadBinding(params: {
|
||||
cfg: OpenClawConfig;
|
||||
channel?: string;
|
||||
accountId?: string;
|
||||
to?: string;
|
||||
threadId?: string | number;
|
||||
}): { ok: true; binding: PreparedAcpThreadBinding } | { ok: false; error: string } {
|
||||
const channel = params.channel?.trim().toLowerCase();
|
||||
if (!channel) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "thread=true for ACP sessions requires a channel context.",
|
||||
};
|
||||
}
|
||||
|
||||
const accountId = params.accountId?.trim() || "default";
|
||||
const policy = resolveThreadBindingSpawnPolicy({
|
||||
cfg: params.cfg,
|
||||
channel,
|
||||
accountId,
|
||||
kind: "acp",
|
||||
});
|
||||
if (!policy.enabled) {
|
||||
return {
|
||||
ok: false,
|
||||
error: formatThreadBindingDisabledError({
|
||||
channel: policy.channel,
|
||||
accountId: policy.accountId,
|
||||
kind: "acp",
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (!policy.spawnEnabled) {
|
||||
return {
|
||||
ok: false,
|
||||
error: formatThreadBindingSpawnDisabledError({
|
||||
channel: policy.channel,
|
||||
accountId: policy.accountId,
|
||||
kind: "acp",
|
||||
}),
|
||||
};
|
||||
}
|
||||
const bindingService = getSessionBindingService();
|
||||
const capabilities = bindingService.getCapabilities({
|
||||
channel: policy.channel,
|
||||
accountId: policy.accountId,
|
||||
});
|
||||
if (!capabilities.adapterAvailable) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Thread bindings are unavailable for ${policy.channel}.`,
|
||||
};
|
||||
}
|
||||
if (!capabilities.bindSupported || !capabilities.placements.includes("child")) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Thread bindings do not support ACP thread spawn for ${policy.channel}.`,
|
||||
};
|
||||
}
|
||||
const conversationId = resolveConversationIdForThreadBinding({
|
||||
to: params.to,
|
||||
threadId: params.threadId,
|
||||
});
|
||||
if (!conversationId) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Could not resolve a ${policy.channel} conversation for ACP thread spawn.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
binding: {
|
||||
channel: policy.channel,
|
||||
accountId: policy.accountId,
|
||||
conversationId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function spawnAcpDirect(
|
||||
params: SpawnAcpParams,
|
||||
ctx: SpawnAcpContext,
|
||||
): Promise<SpawnAcpResult> {
|
||||
const cfg = loadConfig();
|
||||
if (!isAcpEnabledByPolicy(cfg)) {
|
||||
return {
|
||||
status: "forbidden",
|
||||
error: "ACP is disabled by policy (`acp.enabled=false`).",
|
||||
};
|
||||
}
|
||||
|
||||
const requestThreadBinding = params.thread === true;
|
||||
const spawnMode = resolveSpawnMode({
|
||||
requestedMode: params.mode,
|
||||
threadRequested: requestThreadBinding,
|
||||
});
|
||||
if (spawnMode === "session" && !requestThreadBinding) {
|
||||
return {
|
||||
status: "error",
|
||||
error: 'mode="session" requires thread=true so the ACP session can stay bound to a thread.',
|
||||
};
|
||||
}
|
||||
|
||||
const targetAgentResult = resolveTargetAcpAgentId({
|
||||
requestedAgentId: params.agentId,
|
||||
cfg,
|
||||
});
|
||||
if (!targetAgentResult.ok) {
|
||||
return {
|
||||
status: "error",
|
||||
error: targetAgentResult.error,
|
||||
};
|
||||
}
|
||||
const targetAgentId = targetAgentResult.agentId;
|
||||
const agentPolicyError = resolveAcpAgentPolicyError(cfg, targetAgentId);
|
||||
if (agentPolicyError) {
|
||||
return {
|
||||
status: "forbidden",
|
||||
error: agentPolicyError.message,
|
||||
};
|
||||
}
|
||||
|
||||
const sessionKey = `agent:${targetAgentId}:acp:${crypto.randomUUID()}`;
|
||||
const runtimeMode = resolveAcpSessionMode(spawnMode);
|
||||
|
||||
let preparedBinding: PreparedAcpThreadBinding | null = null;
|
||||
if (requestThreadBinding) {
|
||||
const prepared = prepareAcpThreadBinding({
|
||||
cfg,
|
||||
channel: ctx.agentChannel,
|
||||
accountId: ctx.agentAccountId,
|
||||
to: ctx.agentTo,
|
||||
threadId: ctx.agentThreadId,
|
||||
});
|
||||
if (!prepared.ok) {
|
||||
return {
|
||||
status: "error",
|
||||
error: prepared.error,
|
||||
};
|
||||
}
|
||||
preparedBinding = prepared.binding;
|
||||
}
|
||||
|
||||
const acpManager = getAcpSessionManager();
|
||||
const bindingService = getSessionBindingService();
|
||||
let binding: SessionBindingRecord | null = null;
|
||||
let sessionCreated = false;
|
||||
let initializedRuntime: AcpSpawnRuntimeCloseHandle | undefined;
|
||||
try {
|
||||
await callGateway({
|
||||
method: "sessions.patch",
|
||||
params: {
|
||||
key: sessionKey,
|
||||
...(params.label ? { label: params.label } : {}),
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
sessionCreated = true;
|
||||
const initialized = await acpManager.initializeSession({
|
||||
cfg,
|
||||
sessionKey,
|
||||
agent: targetAgentId,
|
||||
mode: runtimeMode,
|
||||
cwd: params.cwd,
|
||||
backendId: cfg.acp?.backend,
|
||||
});
|
||||
initializedRuntime = {
|
||||
runtime: initialized.runtime,
|
||||
handle: initialized.handle,
|
||||
};
|
||||
|
||||
if (preparedBinding) {
|
||||
binding = await bindingService.bind({
|
||||
targetSessionKey: sessionKey,
|
||||
targetKind: "session",
|
||||
conversation: {
|
||||
channel: preparedBinding.channel,
|
||||
accountId: preparedBinding.accountId,
|
||||
conversationId: preparedBinding.conversationId,
|
||||
},
|
||||
placement: "child",
|
||||
metadata: {
|
||||
threadName: resolveThreadBindingThreadName({
|
||||
agentId: targetAgentId,
|
||||
label: params.label || targetAgentId,
|
||||
}),
|
||||
agentId: targetAgentId,
|
||||
label: params.label || undefined,
|
||||
boundBy: "system",
|
||||
introText: resolveThreadBindingIntroText({
|
||||
agentId: targetAgentId,
|
||||
label: params.label || undefined,
|
||||
sessionTtlMs: resolveThreadBindingSessionTtlMsForChannel({
|
||||
cfg,
|
||||
channel: preparedBinding.channel,
|
||||
accountId: preparedBinding.accountId,
|
||||
}),
|
||||
sessionCwd: resolveAcpSessionCwd(initialized.meta),
|
||||
sessionDetails: resolveAcpThreadSessionDetailLines({
|
||||
sessionKey,
|
||||
meta: initialized.meta,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
});
|
||||
if (!binding?.conversation.conversationId) {
|
||||
throw new Error(
|
||||
`Failed to create and bind a ${preparedBinding.channel} thread for this ACP session.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
await cleanupFailedAcpSpawn({
|
||||
cfg,
|
||||
sessionKey,
|
||||
shouldDeleteSession: sessionCreated,
|
||||
deleteTranscript: true,
|
||||
runtimeCloseHandle: initializedRuntime,
|
||||
});
|
||||
return {
|
||||
status: "error",
|
||||
error: isSessionBindingError(err) ? err.message : summarizeError(err),
|
||||
};
|
||||
}
|
||||
|
||||
const requesterOrigin = normalizeDeliveryContext({
|
||||
channel: ctx.agentChannel,
|
||||
accountId: ctx.agentAccountId,
|
||||
to: ctx.agentTo,
|
||||
threadId: ctx.agentThreadId,
|
||||
});
|
||||
// For thread-bound ACP spawns, force bootstrap delivery to the new child thread.
|
||||
const boundThreadIdRaw = binding?.conversation.conversationId;
|
||||
const boundThreadId = boundThreadIdRaw ? String(boundThreadIdRaw).trim() || undefined : undefined;
|
||||
const fallbackThreadIdRaw = requesterOrigin?.threadId;
|
||||
const fallbackThreadId =
|
||||
fallbackThreadIdRaw != null ? String(fallbackThreadIdRaw).trim() || undefined : undefined;
|
||||
const deliveryThreadId = boundThreadId ?? fallbackThreadId;
|
||||
const inferredDeliveryTo = boundThreadId
|
||||
? `channel:${boundThreadId}`
|
||||
: requesterOrigin?.to?.trim() || (deliveryThreadId ? `channel:${deliveryThreadId}` : undefined);
|
||||
const hasDeliveryTarget = Boolean(requesterOrigin?.channel && inferredDeliveryTo);
|
||||
const childIdem = crypto.randomUUID();
|
||||
let childRunId: string = childIdem;
|
||||
try {
|
||||
const response = await callGateway<{ runId?: string }>({
|
||||
method: "agent",
|
||||
params: {
|
||||
message: params.task,
|
||||
sessionKey,
|
||||
channel: hasDeliveryTarget ? requesterOrigin?.channel : undefined,
|
||||
to: hasDeliveryTarget ? inferredDeliveryTo : undefined,
|
||||
accountId: hasDeliveryTarget ? (requesterOrigin?.accountId ?? undefined) : undefined,
|
||||
threadId: hasDeliveryTarget ? deliveryThreadId : undefined,
|
||||
idempotencyKey: childIdem,
|
||||
deliver: hasDeliveryTarget,
|
||||
label: params.label || undefined,
|
||||
},
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (typeof response?.runId === "string" && response.runId.trim()) {
|
||||
childRunId = response.runId.trim();
|
||||
}
|
||||
} catch (err) {
|
||||
await cleanupFailedAcpSpawn({
|
||||
cfg,
|
||||
sessionKey,
|
||||
shouldDeleteSession: true,
|
||||
deleteTranscript: true,
|
||||
});
|
||||
return {
|
||||
status: "error",
|
||||
error: summarizeError(err),
|
||||
childSessionKey: sessionKey,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "accepted",
|
||||
childSessionKey: sessionKey,
|
||||
runId: childRunId,
|
||||
mode: spawnMode,
|
||||
note: spawnMode === "session" ? ACP_SPAWN_SESSION_ACCEPTED_NOTE : ACP_SPAWN_ACCEPTED_NOTE,
|
||||
};
|
||||
}
|
||||
@@ -93,6 +93,7 @@ export function buildSystemPrompt(params: {
|
||||
reasoningTagHint: false,
|
||||
heartbeatPrompt: params.heartbeatPrompt,
|
||||
docsPath: params.docsPath,
|
||||
acpEnabled: params.config?.acp?.enabled !== false,
|
||||
runtimeInfo,
|
||||
toolNames: params.tools.map((tool) => tool.name),
|
||||
modelAliasLines: buildModelAliasLines(params.config),
|
||||
|
||||
@@ -91,6 +91,8 @@ describe("sessions tools", () => {
|
||||
expect(schemaProp("sessions_spawn", "runTimeoutSeconds").type).toBe("number");
|
||||
expect(schemaProp("sessions_spawn", "thread").type).toBe("boolean");
|
||||
expect(schemaProp("sessions_spawn", "mode").type).toBe("string");
|
||||
expect(schemaProp("sessions_spawn", "runtime").type).toBe("string");
|
||||
expect(schemaProp("sessions_spawn", "cwd").type).toBe("string");
|
||||
expect(schemaProp("subagents", "recentMinutes").type).toBe("number");
|
||||
});
|
||||
|
||||
|
||||
@@ -499,6 +499,7 @@ export async function compactEmbeddedPiSessionDirect(
|
||||
docsPath: docsPath ?? undefined,
|
||||
ttsHint,
|
||||
promptMode,
|
||||
acpEnabled: params.config?.acp?.enabled !== false,
|
||||
runtimeInfo,
|
||||
reactionGuidance,
|
||||
messageToolHints,
|
||||
|
||||
@@ -545,6 +545,7 @@ export async function runEmbeddedAttempt(
|
||||
workspaceNotes,
|
||||
reactionGuidance,
|
||||
promptMode,
|
||||
acpEnabled: params.config?.acp?.enabled !== false,
|
||||
runtimeInfo,
|
||||
messageToolHints,
|
||||
sandboxInfo,
|
||||
|
||||
@@ -28,6 +28,8 @@ export function buildEmbeddedSystemPrompt(params: {
|
||||
workspaceNotes?: string[];
|
||||
/** Controls which hardcoded sections to include. Defaults to "full". */
|
||||
promptMode?: PromptMode;
|
||||
/** Whether ACP-specific routing guidance should be included. Defaults to true. */
|
||||
acpEnabled?: boolean;
|
||||
runtimeInfo: {
|
||||
agentId?: string;
|
||||
host: string;
|
||||
@@ -67,6 +69,7 @@ export function buildEmbeddedSystemPrompt(params: {
|
||||
workspaceNotes: params.workspaceNotes,
|
||||
reactionGuidance: params.reactionGuidance,
|
||||
promptMode: params.promptMode,
|
||||
acpEnabled: params.acpEnabled,
|
||||
runtimeInfo: params.runtimeInfo,
|
||||
messageToolHints: params.messageToolHints,
|
||||
sandboxInfo: params.sandboxInfo,
|
||||
|
||||
103
src/agents/skills/plugin-skills.test.ts
Normal file
103
src/agents/skills/plugin-skills.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "../../config/config.js";
|
||||
import type { PluginManifestRegistry } from "../../plugins/manifest-registry.js";
|
||||
import { createTrackedTempDirs } from "../../test-utils/tracked-temp-dirs.js";
|
||||
|
||||
const hoisted = vi.hoisted(() => ({
|
||||
loadPluginManifestRegistry: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../plugins/manifest-registry.js", () => ({
|
||||
loadPluginManifestRegistry: (...args: unknown[]) => hoisted.loadPluginManifestRegistry(...args),
|
||||
}));
|
||||
|
||||
const { resolvePluginSkillDirs } = await import("./plugin-skills.js");
|
||||
|
||||
const tempDirs = createTrackedTempDirs();
|
||||
|
||||
function buildRegistry(params: { acpxRoot: string; helperRoot: string }): PluginManifestRegistry {
|
||||
return {
|
||||
diagnostics: [],
|
||||
plugins: [
|
||||
{
|
||||
id: "acpx",
|
||||
name: "ACPX Runtime",
|
||||
channels: [],
|
||||
providers: [],
|
||||
skills: ["./skills"],
|
||||
origin: "workspace",
|
||||
rootDir: params.acpxRoot,
|
||||
source: params.acpxRoot,
|
||||
manifestPath: path.join(params.acpxRoot, "openclaw.plugin.json"),
|
||||
},
|
||||
{
|
||||
id: "helper",
|
||||
name: "Helper",
|
||||
channels: [],
|
||||
providers: [],
|
||||
skills: ["./skills"],
|
||||
origin: "workspace",
|
||||
rootDir: params.helperRoot,
|
||||
source: params.helperRoot,
|
||||
manifestPath: path.join(params.helperRoot, "openclaw.plugin.json"),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
hoisted.loadPluginManifestRegistry.mockReset();
|
||||
await tempDirs.cleanup();
|
||||
});
|
||||
|
||||
describe("resolvePluginSkillDirs", () => {
|
||||
it("keeps acpx plugin skills when ACP is enabled", async () => {
|
||||
const workspaceDir = await tempDirs.make("openclaw-");
|
||||
const acpxRoot = await tempDirs.make("openclaw-acpx-plugin-");
|
||||
const helperRoot = await tempDirs.make("openclaw-helper-plugin-");
|
||||
await fs.mkdir(path.join(acpxRoot, "skills"), { recursive: true });
|
||||
await fs.mkdir(path.join(helperRoot, "skills"), { recursive: true });
|
||||
|
||||
hoisted.loadPluginManifestRegistry.mockReturnValue(
|
||||
buildRegistry({
|
||||
acpxRoot,
|
||||
helperRoot,
|
||||
}),
|
||||
);
|
||||
|
||||
const dirs = resolvePluginSkillDirs({
|
||||
workspaceDir,
|
||||
config: {
|
||||
acp: { enabled: true },
|
||||
} as OpenClawConfig,
|
||||
});
|
||||
|
||||
expect(dirs).toEqual([path.resolve(acpxRoot, "skills"), path.resolve(helperRoot, "skills")]);
|
||||
});
|
||||
|
||||
it("skips acpx plugin skills when ACP is disabled", async () => {
|
||||
const workspaceDir = await tempDirs.make("openclaw-");
|
||||
const acpxRoot = await tempDirs.make("openclaw-acpx-plugin-");
|
||||
const helperRoot = await tempDirs.make("openclaw-helper-plugin-");
|
||||
await fs.mkdir(path.join(acpxRoot, "skills"), { recursive: true });
|
||||
await fs.mkdir(path.join(helperRoot, "skills"), { recursive: true });
|
||||
|
||||
hoisted.loadPluginManifestRegistry.mockReturnValue(
|
||||
buildRegistry({
|
||||
acpxRoot,
|
||||
helperRoot,
|
||||
}),
|
||||
);
|
||||
|
||||
const dirs = resolvePluginSkillDirs({
|
||||
workspaceDir,
|
||||
config: {
|
||||
acp: { enabled: false },
|
||||
} as OpenClawConfig,
|
||||
});
|
||||
|
||||
expect(dirs).toEqual([path.resolve(helperRoot, "skills")]);
|
||||
});
|
||||
});
|
||||
@@ -27,6 +27,7 @@ export function resolvePluginSkillDirs(params: {
|
||||
return [];
|
||||
}
|
||||
const normalizedPlugins = normalizePluginsConfig(params.config?.plugins);
|
||||
const acpEnabled = params.config?.acp?.enabled !== false;
|
||||
const memorySlot = normalizedPlugins.slots.memory;
|
||||
let selectedMemoryPluginId: string | null = null;
|
||||
const seen = new Set<string>();
|
||||
@@ -45,6 +46,10 @@ export function resolvePluginSkillDirs(params: {
|
||||
if (!enableState.enabled) {
|
||||
continue;
|
||||
}
|
||||
// ACP router skills should not be attached when ACP is explicitly disabled.
|
||||
if (!acpEnabled && record.id === "acpx") {
|
||||
continue;
|
||||
}
|
||||
const memoryDecision = resolveMemorySlotDecision({
|
||||
id: record.id,
|
||||
kind: record.kind,
|
||||
|
||||
@@ -924,6 +924,8 @@ export function buildSubagentSystemPrompt(params: {
|
||||
childSessionKey: string;
|
||||
label?: string;
|
||||
task?: string;
|
||||
/** Whether ACP-specific routing guidance should be included. Defaults to true. */
|
||||
acpEnabled?: boolean;
|
||||
/** Depth of the child being spawned (1 = sub-agent, 2 = sub-sub-agent). */
|
||||
childDepth?: number;
|
||||
/** Config value: max allowed spawn depth. */
|
||||
@@ -938,6 +940,7 @@ export function buildSubagentSystemPrompt(params: {
|
||||
typeof params.maxSpawnDepth === "number"
|
||||
? params.maxSpawnDepth
|
||||
: DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH;
|
||||
const acpEnabled = params.acpEnabled !== false;
|
||||
const canSpawn = childDepth < maxSpawnDepth;
|
||||
const parentLabel = childDepth >= 2 ? "parent orchestrator" : "main agent";
|
||||
|
||||
@@ -983,6 +986,17 @@ export function buildSubagentSystemPrompt(params: {
|
||||
"Default workflow: spawn work, continue orchestrating, and wait for auto-announced completions.",
|
||||
"Do NOT repeatedly poll `subagents list` in a loop unless you are actively debugging or intervening.",
|
||||
"Coordinate their work and synthesize results before reporting back.",
|
||||
...(acpEnabled
|
||||
? [
|
||||
'For ACP harness sessions (codex/claudecode/gemini), use `sessions_spawn` with `runtime: "acp"` (set `agentId` unless `acp.defaultAgent` is configured).',
|
||||
'`agents_list` and `subagents` apply to OpenClaw sub-agents (`runtime: "subagent"`); ACP harness ids are controlled by `acp.allowedAgents`.',
|
||||
"Do not ask users to run slash commands or CLI when `sessions_spawn` can do it directly.",
|
||||
"Do not use `exec` (`openclaw ...`, `acpx ...`) to spawn ACP sessions.",
|
||||
'Use `subagents` only for OpenClaw subagents (`runtime: "subagent"`).',
|
||||
"Subagent results auto-announce back to you; ACP sessions continue in their bound thread.",
|
||||
"Avoid polling loops; spawn, orchestrate, and synthesize results.",
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
);
|
||||
} else if (childDepth >= 2) {
|
||||
|
||||
157
src/agents/subagent-registry.lifecycle-retry-grace.test.ts
Normal file
157
src/agents/subagent-registry.lifecycle-retry-grace.test.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
let lifecycleHandler:
|
||||
| ((evt: {
|
||||
stream?: string;
|
||||
runId: string;
|
||||
data?: {
|
||||
phase?: string;
|
||||
startedAt?: number;
|
||||
endedAt?: number;
|
||||
aborted?: boolean;
|
||||
error?: string;
|
||||
};
|
||||
}) => void)
|
||||
| undefined;
|
||||
|
||||
vi.mock("../gateway/call.js", () => ({
|
||||
callGateway: vi.fn(async (request: unknown) => {
|
||||
const method = (request as { method?: string }).method;
|
||||
if (method === "agent.wait") {
|
||||
// Keep wait unresolved from the RPC path so lifecycle fallback logic is exercised.
|
||||
return { status: "pending" };
|
||||
}
|
||||
return {};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../infra/agent-events.js", () => ({
|
||||
onAgentEvent: vi.fn((handler: typeof lifecycleHandler) => {
|
||||
lifecycleHandler = handler;
|
||||
return noop;
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", () => ({
|
||||
loadConfig: vi.fn(() => ({
|
||||
agents: { defaults: { subagents: { archiveAfterMinutes: 0 } } },
|
||||
})),
|
||||
}));
|
||||
|
||||
const announceSpy = vi.fn(async () => true);
|
||||
vi.mock("./subagent-announce.js", () => ({
|
||||
runSubagentAnnounceFlow: announceSpy,
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/hook-runner-global.js", () => ({
|
||||
getGlobalHookRunner: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
vi.mock("./subagent-registry.store.js", () => ({
|
||||
loadSubagentRegistryFromDisk: vi.fn(() => new Map()),
|
||||
saveSubagentRegistryToDisk: vi.fn(() => {}),
|
||||
}));
|
||||
|
||||
describe("subagent registry lifecycle error grace", () => {
|
||||
let mod: typeof import("./subagent-registry.js");
|
||||
|
||||
beforeAll(async () => {
|
||||
mod = await import("./subagent-registry.js");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
announceSpy.mockClear();
|
||||
lifecycleHandler = undefined;
|
||||
mod.resetSubagentRegistryForTests({ persist: false });
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const flushAsync = async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
|
||||
it("ignores transient lifecycle errors when run retries and then ends successfully", async () => {
|
||||
mod.registerSubagentRun({
|
||||
runId: "run-transient-error",
|
||||
childSessionKey: "agent:main:subagent:transient-error",
|
||||
requesterSessionKey: "agent:main:main",
|
||||
requesterDisplayKey: "main",
|
||||
task: "transient error test",
|
||||
cleanup: "keep",
|
||||
expectsCompletionMessage: true,
|
||||
});
|
||||
|
||||
lifecycleHandler?.({
|
||||
stream: "lifecycle",
|
||||
runId: "run-transient-error",
|
||||
data: { phase: "error", error: "rate limit", endedAt: 1_000 },
|
||||
});
|
||||
await flushAsync();
|
||||
expect(announceSpy).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(14_999);
|
||||
expect(announceSpy).not.toHaveBeenCalled();
|
||||
|
||||
lifecycleHandler?.({
|
||||
stream: "lifecycle",
|
||||
runId: "run-transient-error",
|
||||
data: { phase: "start", startedAt: 1_050 },
|
||||
});
|
||||
await flushAsync();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(announceSpy).not.toHaveBeenCalled();
|
||||
|
||||
lifecycleHandler?.({
|
||||
stream: "lifecycle",
|
||||
runId: "run-transient-error",
|
||||
data: { phase: "end", endedAt: 1_250 },
|
||||
});
|
||||
await flushAsync();
|
||||
|
||||
expect(announceSpy).toHaveBeenCalledTimes(1);
|
||||
const announceCalls = announceSpy.mock.calls as unknown as Array<Array<unknown>>;
|
||||
const first = (announceCalls[0]?.[0] ?? {}) as {
|
||||
outcome?: { status?: string; error?: string };
|
||||
};
|
||||
expect(first.outcome?.status).toBe("ok");
|
||||
});
|
||||
|
||||
it("announces error when lifecycle error remains terminal after grace window", async () => {
|
||||
mod.registerSubagentRun({
|
||||
runId: "run-terminal-error",
|
||||
childSessionKey: "agent:main:subagent:terminal-error",
|
||||
requesterSessionKey: "agent:main:main",
|
||||
requesterDisplayKey: "main",
|
||||
task: "terminal error test",
|
||||
cleanup: "keep",
|
||||
expectsCompletionMessage: true,
|
||||
});
|
||||
|
||||
lifecycleHandler?.({
|
||||
stream: "lifecycle",
|
||||
runId: "run-terminal-error",
|
||||
data: { phase: "error", error: "fatal failure", endedAt: 2_000 },
|
||||
});
|
||||
await flushAsync();
|
||||
expect(announceSpy).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
await flushAsync();
|
||||
|
||||
expect(announceSpy).toHaveBeenCalledTimes(1);
|
||||
const announceCalls = announceSpy.mock.calls as unknown as Array<Array<unknown>>;
|
||||
const first = (announceCalls[0]?.[0] ?? {}) as {
|
||||
outcome?: { status?: string; error?: string };
|
||||
};
|
||||
expect(first.outcome?.status).toBe("error");
|
||||
expect(first.outcome?.error).toBe("fatal failure");
|
||||
});
|
||||
});
|
||||
@@ -66,6 +66,12 @@ const MAX_ANNOUNCE_RETRY_COUNT = 3;
|
||||
*/
|
||||
const ANNOUNCE_EXPIRY_MS = 5 * 60_000; // 5 minutes
|
||||
type SubagentRunOrphanReason = "missing-session-entry" | "missing-session-id";
|
||||
/**
|
||||
* Embedded runs can emit transient lifecycle `error` events while provider/model
|
||||
* retry is still in progress. Defer terminal error cleanup briefly so a
|
||||
* subsequent lifecycle `start` / `end` can cancel premature failure announces.
|
||||
*/
|
||||
const LIFECYCLE_ERROR_RETRY_GRACE_MS = 15_000;
|
||||
|
||||
function resolveAnnounceRetryDelayMs(retryCount: number) {
|
||||
const boundedRetryCount = Math.max(0, Math.min(retryCount, 10));
|
||||
@@ -204,6 +210,66 @@ function reconcileOrphanedRestoredRuns() {
|
||||
|
||||
const resumedRuns = new Set<string>();
|
||||
const endedHookInFlightRunIds = new Set<string>();
|
||||
const pendingLifecycleErrorByRunId = new Map<
|
||||
string,
|
||||
{
|
||||
timer: NodeJS.Timeout;
|
||||
endedAt: number;
|
||||
error?: string;
|
||||
}
|
||||
>();
|
||||
|
||||
function clearPendingLifecycleError(runId: string) {
|
||||
const pending = pendingLifecycleErrorByRunId.get(runId);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(pending.timer);
|
||||
pendingLifecycleErrorByRunId.delete(runId);
|
||||
}
|
||||
|
||||
function clearAllPendingLifecycleErrors() {
|
||||
for (const pending of pendingLifecycleErrorByRunId.values()) {
|
||||
clearTimeout(pending.timer);
|
||||
}
|
||||
pendingLifecycleErrorByRunId.clear();
|
||||
}
|
||||
|
||||
function schedulePendingLifecycleError(params: { runId: string; endedAt: number; error?: string }) {
|
||||
clearPendingLifecycleError(params.runId);
|
||||
const timer = setTimeout(() => {
|
||||
const pending = pendingLifecycleErrorByRunId.get(params.runId);
|
||||
if (!pending || pending.timer !== timer) {
|
||||
return;
|
||||
}
|
||||
pendingLifecycleErrorByRunId.delete(params.runId);
|
||||
const entry = subagentRuns.get(params.runId);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
if (entry.endedReason === SUBAGENT_ENDED_REASON_COMPLETE || entry.outcome?.status === "ok") {
|
||||
return;
|
||||
}
|
||||
void completeSubagentRun({
|
||||
runId: params.runId,
|
||||
endedAt: pending.endedAt,
|
||||
outcome: {
|
||||
status: "error",
|
||||
error: pending.error,
|
||||
},
|
||||
reason: SUBAGENT_ENDED_REASON_ERROR,
|
||||
sendFarewell: true,
|
||||
accountId: entry.requesterOrigin?.accountId,
|
||||
triggerCleanup: true,
|
||||
});
|
||||
}, LIFECYCLE_ERROR_RETRY_GRACE_MS);
|
||||
timer.unref?.();
|
||||
pendingLifecycleErrorByRunId.set(params.runId, {
|
||||
timer,
|
||||
endedAt: params.endedAt,
|
||||
error: params.error,
|
||||
});
|
||||
}
|
||||
|
||||
function suppressAnnounceForSteerRestart(entry?: SubagentRunRecord) {
|
||||
return entry?.suppressAnnounceReason === "steer-restart";
|
||||
@@ -256,6 +322,7 @@ async function completeSubagentRun(params: {
|
||||
accountId?: string;
|
||||
triggerCleanup: boolean;
|
||||
}) {
|
||||
clearPendingLifecycleError(params.runId);
|
||||
const entry = subagentRuns.get(params.runId);
|
||||
if (!entry) {
|
||||
return;
|
||||
@@ -491,6 +558,7 @@ async function sweepSubagentRuns() {
|
||||
if (!entry.archiveAtMs || entry.archiveAtMs > now) {
|
||||
continue;
|
||||
}
|
||||
clearPendingLifecycleError(runId);
|
||||
subagentRuns.delete(runId);
|
||||
mutated = true;
|
||||
try {
|
||||
@@ -531,6 +599,7 @@ function ensureListener() {
|
||||
}
|
||||
const phase = evt.data?.phase;
|
||||
if (phase === "start") {
|
||||
clearPendingLifecycleError(evt.runId);
|
||||
const startedAt = typeof evt.data?.startedAt === "number" ? evt.data.startedAt : undefined;
|
||||
if (startedAt) {
|
||||
entry.startedAt = startedAt;
|
||||
@@ -543,17 +612,23 @@ function ensureListener() {
|
||||
}
|
||||
const endedAt = typeof evt.data?.endedAt === "number" ? evt.data.endedAt : Date.now();
|
||||
const error = typeof evt.data?.error === "string" ? evt.data.error : undefined;
|
||||
const outcome: SubagentRunOutcome =
|
||||
phase === "error"
|
||||
? { status: "error", error }
|
||||
: evt.data?.aborted
|
||||
? { status: "timeout" }
|
||||
: { status: "ok" };
|
||||
if (phase === "error") {
|
||||
schedulePendingLifecycleError({
|
||||
runId: evt.runId,
|
||||
endedAt,
|
||||
error,
|
||||
});
|
||||
return;
|
||||
}
|
||||
clearPendingLifecycleError(evt.runId);
|
||||
const outcome: SubagentRunOutcome = evt.data?.aborted
|
||||
? { status: "timeout" }
|
||||
: { status: "ok" };
|
||||
await completeSubagentRun({
|
||||
runId: evt.runId,
|
||||
endedAt,
|
||||
outcome,
|
||||
reason: phase === "error" ? SUBAGENT_ENDED_REASON_ERROR : SUBAGENT_ENDED_REASON_COMPLETE,
|
||||
reason: SUBAGENT_ENDED_REASON_COMPLETE,
|
||||
sendFarewell: true,
|
||||
accountId: entry.requesterOrigin?.accountId,
|
||||
triggerCleanup: true,
|
||||
@@ -661,6 +736,7 @@ function completeCleanupBookkeeping(params: {
|
||||
completedAt: number;
|
||||
}) {
|
||||
if (params.cleanup === "delete") {
|
||||
clearPendingLifecycleError(params.runId);
|
||||
subagentRuns.delete(params.runId);
|
||||
persistSubagentRuns();
|
||||
retryDeferredCompletedAnnounces(params.runId);
|
||||
@@ -774,6 +850,7 @@ export function replaceSubagentRunAfterSteer(params: {
|
||||
}
|
||||
|
||||
if (previousRunId !== nextRunId) {
|
||||
clearPendingLifecycleError(previousRunId);
|
||||
subagentRuns.delete(previousRunId);
|
||||
resumedRuns.delete(previousRunId);
|
||||
}
|
||||
@@ -935,6 +1012,7 @@ export function resetSubagentRegistryForTests(opts?: { persist?: boolean }) {
|
||||
subagentRuns.clear();
|
||||
resumedRuns.clear();
|
||||
endedHookInFlightRunIds.clear();
|
||||
clearAllPendingLifecycleErrors();
|
||||
resetAnnounceQueuesForTests();
|
||||
stopSweeper();
|
||||
restoreAttempted = false;
|
||||
@@ -953,6 +1031,7 @@ export function addSubagentRunForTests(entry: SubagentRunRecord) {
|
||||
}
|
||||
|
||||
export function releaseSubagentRun(runId: string) {
|
||||
clearPendingLifecycleError(runId);
|
||||
const didDelete = subagentRuns.delete(runId);
|
||||
if (didDelete) {
|
||||
persistSubagentRuns();
|
||||
@@ -1020,6 +1099,7 @@ export function markSubagentRunTerminated(params: {
|
||||
let updated = 0;
|
||||
const entriesByChildSessionKey = new Map<string, SubagentRunRecord>();
|
||||
for (const runId of runIds) {
|
||||
clearPendingLifecycleError(runId);
|
||||
const entry = subagentRuns.get(runId);
|
||||
if (!entry) {
|
||||
continue;
|
||||
|
||||
@@ -385,6 +385,7 @@ export async function spawnSubagentDirect(
|
||||
childSessionKey,
|
||||
label: label || undefined,
|
||||
task,
|
||||
acpEnabled: cfg.acp?.enabled !== false,
|
||||
childDepth,
|
||||
maxSpawnDepth,
|
||||
});
|
||||
|
||||
@@ -221,6 +221,9 @@ describe("buildAgentSystemPrompt", () => {
|
||||
);
|
||||
expect(prompt).toContain("Completion is push-based: it will auto-announce when done.");
|
||||
expect(prompt).toContain("Do not poll `subagents list` / `sessions_list` in a loop");
|
||||
expect(prompt).toContain(
|
||||
"When a first-class tool exists for an action, use the tool directly instead of asking the user to run equivalent CLI or slash commands.",
|
||||
);
|
||||
});
|
||||
|
||||
it("lists available tools when provided", () => {
|
||||
@@ -235,6 +238,52 @@ describe("buildAgentSystemPrompt", () => {
|
||||
expect(prompt).toContain("sessions_send");
|
||||
});
|
||||
|
||||
it("documents ACP sessions_spawn agent targeting requirements", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/openclaw",
|
||||
toolNames: ["sessions_spawn"],
|
||||
});
|
||||
|
||||
expect(prompt).toContain("sessions_spawn");
|
||||
expect(prompt).toContain(
|
||||
'runtime="acp" requires `agentId` unless `acp.defaultAgent` is configured',
|
||||
);
|
||||
expect(prompt).toContain("not agents_list");
|
||||
});
|
||||
|
||||
it("guides harness requests to ACP thread-bound spawns", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/openclaw",
|
||||
toolNames: ["sessions_spawn", "subagents", "agents_list", "exec"],
|
||||
});
|
||||
|
||||
expect(prompt).toContain(
|
||||
'For requests like "do this in codex/claude code/gemini", treat it as ACP harness intent',
|
||||
);
|
||||
expect(prompt).toContain(
|
||||
'On Discord, default ACP harness requests to thread-bound persistent sessions (`thread: true`, `mode: "session"`)',
|
||||
);
|
||||
expect(prompt).toContain(
|
||||
"do not route ACP harness requests through `subagents`/`agents_list` or local PTY exec flows",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits ACP harness guidance when ACP is disabled", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/openclaw",
|
||||
toolNames: ["sessions_spawn", "subagents", "agents_list", "exec"],
|
||||
acpEnabled: false,
|
||||
});
|
||||
|
||||
expect(prompt).not.toContain(
|
||||
'For requests like "do this in codex/claude code/gemini", treat it as ACP harness intent',
|
||||
);
|
||||
expect(prompt).not.toContain('runtime="acp" requires `agentId`');
|
||||
expect(prompt).not.toContain("not ACP harness ids");
|
||||
expect(prompt).toContain("- sessions_spawn: Spawn an isolated sub-agent session");
|
||||
expect(prompt).toContain("- agents_list: List OpenClaw agent ids allowed for sessions_spawn");
|
||||
});
|
||||
|
||||
it("preserves tool casing in the prompt", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/openclaw",
|
||||
@@ -599,11 +648,18 @@ describe("buildSubagentSystemPrompt", () => {
|
||||
});
|
||||
|
||||
expect(prompt).toContain("## Sub-Agent Spawning");
|
||||
expect(prompt).toContain("You CAN spawn your own sub-agents");
|
||||
expect(prompt).toContain(
|
||||
"You CAN spawn your own sub-agents for parallel or complex work using `sessions_spawn`.",
|
||||
);
|
||||
expect(prompt).toContain("sessions_spawn");
|
||||
expect(prompt).toContain("`subagents` tool");
|
||||
expect(prompt).toContain("announce their results back to you automatically");
|
||||
expect(prompt).toContain("Do NOT repeatedly poll `subagents list`");
|
||||
expect(prompt).toContain('runtime: "acp"');
|
||||
expect(prompt).toContain("For ACP harness sessions (codex/claudecode/gemini)");
|
||||
expect(prompt).toContain("set `agentId` unless `acp.defaultAgent` is configured");
|
||||
expect(prompt).toContain("Do not ask users to run slash commands or CLI");
|
||||
expect(prompt).toContain("Do not use `exec` (`openclaw ...`, `acpx ...`)");
|
||||
expect(prompt).toContain("Use `subagents` only for OpenClaw subagents");
|
||||
expect(prompt).toContain("Subagent results auto-announce back to you");
|
||||
expect(prompt).toContain("Avoid polling loops");
|
||||
expect(prompt).toContain("spawned by the main agent");
|
||||
expect(prompt).toContain("reported to the main agent");
|
||||
expect(prompt).toContain("[compacted: tool output removed to free context]");
|
||||
@@ -612,6 +668,21 @@ describe("buildSubagentSystemPrompt", () => {
|
||||
expect(prompt).toContain("instead of full-file `cat`");
|
||||
});
|
||||
|
||||
it("omits ACP spawning guidance when ACP is disabled", () => {
|
||||
const prompt = buildSubagentSystemPrompt({
|
||||
childSessionKey: "agent:main:subagent:abc",
|
||||
task: "research task",
|
||||
childDepth: 1,
|
||||
maxSpawnDepth: 2,
|
||||
acpEnabled: false,
|
||||
});
|
||||
|
||||
expect(prompt).not.toContain('runtime: "acp"');
|
||||
expect(prompt).not.toContain("For ACP harness sessions (codex/claudecode/gemini)");
|
||||
expect(prompt).not.toContain("set `agentId` unless `acp.defaultAgent` is configured");
|
||||
expect(prompt).toContain("You CAN spawn your own sub-agents");
|
||||
});
|
||||
|
||||
it("renders depth-2 leaf guidance with parent orchestrator labels", () => {
|
||||
const prompt = buildSubagentSystemPrompt({
|
||||
childSessionKey: "agent:main:subagent:abc:subagent:def",
|
||||
|
||||
@@ -209,6 +209,8 @@ export function buildAgentSystemPrompt(params: {
|
||||
ttsHint?: string;
|
||||
/** Controls which hardcoded sections to include. Defaults to "full". */
|
||||
promptMode?: PromptMode;
|
||||
/** Whether ACP-specific routing guidance should be included. Defaults to true. */
|
||||
acpEnabled?: boolean;
|
||||
runtimeInfo?: {
|
||||
agentId?: string;
|
||||
host?: string;
|
||||
@@ -231,6 +233,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
};
|
||||
memoryCitationsMode?: MemoryCitationsMode;
|
||||
}) {
|
||||
const acpEnabled = params.acpEnabled !== false;
|
||||
const coreToolSummaries: Record<string, string> = {
|
||||
read: "Read file contents",
|
||||
write: "Create or overwrite files",
|
||||
@@ -250,11 +253,15 @@ export function buildAgentSystemPrompt(params: {
|
||||
cron: "Manage cron jobs and wake events (use for reminders; when scheduling a reminder, write the systemEvent text as something that will read like a reminder when it fires, and mention that it is a reminder depending on the time gap between setting and firing; include recent context in reminder text if appropriate)",
|
||||
message: "Send messages and channel actions",
|
||||
gateway: "Restart, apply config, or run updates on the running OpenClaw process",
|
||||
agents_list: "List agent ids allowed for sessions_spawn",
|
||||
agents_list: acpEnabled
|
||||
? 'List OpenClaw agent ids allowed for sessions_spawn when runtime="subagent" (not ACP harness ids)'
|
||||
: "List OpenClaw agent ids allowed for sessions_spawn",
|
||||
sessions_list: "List other sessions (incl. sub-agents) with filters/last",
|
||||
sessions_history: "Fetch history for another session/sub-agent",
|
||||
sessions_send: "Send a message to another session/sub-agent",
|
||||
sessions_spawn: "Spawn a sub-agent session",
|
||||
sessions_spawn: acpEnabled
|
||||
? 'Spawn an isolated sub-agent or ACP coding session (runtime="acp" requires `agentId` unless `acp.defaultAgent` is configured; ACP harness ids follow acp.allowedAgents, not agents_list)'
|
||||
: "Spawn an isolated sub-agent session",
|
||||
subagents: "List, steer, or kill sub-agent runs for this requester session",
|
||||
session_status:
|
||||
"Show a /status-equivalent status card (usage + time + Reasoning/Verbose/Elevated); use for model-use questions (📊 session_status); optional per-session model override",
|
||||
@@ -303,6 +310,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
|
||||
const normalizedTools = canonicalToolNames.map((tool) => tool.toLowerCase());
|
||||
const availableTools = new Set(normalizedTools);
|
||||
const hasSessionsSpawn = availableTools.has("sessions_spawn");
|
||||
const externalToolSummaries = new Map<string, string>();
|
||||
for (const [key, value] of Object.entries(params.toolSummaries ?? {})) {
|
||||
const normalized = key.trim().toLowerCase();
|
||||
@@ -436,6 +444,13 @@ export function buildAgentSystemPrompt(params: {
|
||||
"TOOLS.md does not control tool availability; it is user guidance for how to use external tools.",
|
||||
`For long waits, avoid rapid poll loops: use ${execToolName} with enough yieldMs or ${processToolName}(action=poll, timeout=<ms>).`,
|
||||
"If a task is more complex or takes longer, spawn a sub-agent. Completion is push-based: it will auto-announce when done.",
|
||||
...(hasSessionsSpawn && acpEnabled
|
||||
? [
|
||||
'For requests like "do this in codex/claude code/gemini", treat it as ACP harness intent and call `sessions_spawn` with `runtime: "acp"`.',
|
||||
'On Discord, default ACP harness requests to thread-bound persistent sessions (`thread: true`, `mode: "session"`) unless the user asks otherwise.',
|
||||
"Set `agentId` explicitly unless `acp.defaultAgent` is configured, and do not route ACP harness requests through `subagents`/`agents_list` or local PTY exec flows.",
|
||||
]
|
||||
: []),
|
||||
"Do not poll `subagents list` / `sessions_list` in a loop; only check status on-demand (for intervention, debugging, or when explicitly asked).",
|
||||
"",
|
||||
"## Tool Call Style",
|
||||
@@ -443,6 +458,7 @@ export function buildAgentSystemPrompt(params: {
|
||||
"Narrate only when it helps: multi-step work, complex/challenging problems, sensitive actions (e.g., deletions), or when the user explicitly asks.",
|
||||
"Keep narration brief and value-dense; avoid repeating obvious steps.",
|
||||
"Use plain human language for narration unless in a technical context.",
|
||||
"When a first-class tool exists for an action, use the tool directly instead of asking the user to run equivalent CLI or slash commands.",
|
||||
"",
|
||||
...safetySection,
|
||||
"## OpenClaw CLI Quick Reference",
|
||||
|
||||
@@ -26,7 +26,8 @@ export function createAgentsListTool(opts?: {
|
||||
return {
|
||||
label: "Agents",
|
||||
name: "agents_list",
|
||||
description: "List agent ids you can target with sessions_spawn (based on allowlists).",
|
||||
description:
|
||||
'List OpenClaw agent ids you can target with `sessions_spawn` when `runtime="subagent"` (based on subagent allowlists).',
|
||||
parameters: AgentsListToolSchema,
|
||||
execute: async () => {
|
||||
const cfg = loadConfig();
|
||||
|
||||
118
src/agents/tools/sessions-spawn-tool.test.ts
Normal file
118
src/agents/tools/sessions-spawn-tool.test.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const hoisted = vi.hoisted(() => {
|
||||
const spawnSubagentDirectMock = vi.fn();
|
||||
const spawnAcpDirectMock = vi.fn();
|
||||
return {
|
||||
spawnSubagentDirectMock,
|
||||
spawnAcpDirectMock,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../subagent-spawn.js", () => ({
|
||||
SUBAGENT_SPAWN_MODES: ["run", "session"],
|
||||
spawnSubagentDirect: (...args: unknown[]) => hoisted.spawnSubagentDirectMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../acp-spawn.js", () => ({
|
||||
ACP_SPAWN_MODES: ["run", "session"],
|
||||
spawnAcpDirect: (...args: unknown[]) => hoisted.spawnAcpDirectMock(...args),
|
||||
}));
|
||||
|
||||
const { createSessionsSpawnTool } = await import("./sessions-spawn-tool.js");
|
||||
|
||||
describe("sessions_spawn tool", () => {
|
||||
beforeEach(() => {
|
||||
hoisted.spawnSubagentDirectMock.mockReset().mockResolvedValue({
|
||||
status: "accepted",
|
||||
childSessionKey: "agent:main:subagent:1",
|
||||
runId: "run-subagent",
|
||||
});
|
||||
hoisted.spawnAcpDirectMock.mockReset().mockResolvedValue({
|
||||
status: "accepted",
|
||||
childSessionKey: "agent:codex:acp:1",
|
||||
runId: "run-acp",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses subagent runtime by default", async () => {
|
||||
const tool = createSessionsSpawnTool({
|
||||
agentSessionKey: "agent:main:main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "default",
|
||||
agentTo: "channel:123",
|
||||
agentThreadId: "456",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call-1", {
|
||||
task: "build feature",
|
||||
agentId: "main",
|
||||
model: "anthropic/claude-sonnet-4-6",
|
||||
thinking: "medium",
|
||||
runTimeoutSeconds: 5,
|
||||
thread: true,
|
||||
mode: "session",
|
||||
cleanup: "keep",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({
|
||||
status: "accepted",
|
||||
childSessionKey: "agent:main:subagent:1",
|
||||
runId: "run-subagent",
|
||||
});
|
||||
expect(hoisted.spawnSubagentDirectMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
task: "build feature",
|
||||
agentId: "main",
|
||||
model: "anthropic/claude-sonnet-4-6",
|
||||
thinking: "medium",
|
||||
runTimeoutSeconds: 5,
|
||||
thread: true,
|
||||
mode: "session",
|
||||
cleanup: "keep",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
agentSessionKey: "agent:main:main",
|
||||
}),
|
||||
);
|
||||
expect(hoisted.spawnAcpDirectMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("routes to ACP runtime when runtime=acp", async () => {
|
||||
const tool = createSessionsSpawnTool({
|
||||
agentSessionKey: "agent:main:main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "default",
|
||||
agentTo: "channel:123",
|
||||
agentThreadId: "456",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call-2", {
|
||||
runtime: "acp",
|
||||
task: "investigate the failing CI run",
|
||||
agentId: "codex",
|
||||
cwd: "/workspace",
|
||||
thread: true,
|
||||
mode: "session",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({
|
||||
status: "accepted",
|
||||
childSessionKey: "agent:codex:acp:1",
|
||||
runId: "run-acp",
|
||||
});
|
||||
expect(hoisted.spawnAcpDirectMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
task: "investigate the failing CI run",
|
||||
agentId: "codex",
|
||||
cwd: "/workspace",
|
||||
thread: true,
|
||||
mode: "session",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
agentSessionKey: "agent:main:main",
|
||||
}),
|
||||
);
|
||||
expect(hoisted.spawnSubagentDirectMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,21 @@
|
||||
import { Type } from "@sinclair/typebox";
|
||||
import type { GatewayMessageChannel } from "../../utils/message-channel.js";
|
||||
import { ACP_SPAWN_MODES, spawnAcpDirect } from "../acp-spawn.js";
|
||||
import { optionalStringEnum } from "../schema/typebox.js";
|
||||
import { SUBAGENT_SPAWN_MODES, spawnSubagentDirect } from "../subagent-spawn.js";
|
||||
import type { AnyAgentTool } from "./common.js";
|
||||
import { jsonResult, readStringParam } from "./common.js";
|
||||
|
||||
const SESSIONS_SPAWN_RUNTIMES = ["subagent", "acp"] as const;
|
||||
|
||||
const SessionsSpawnToolSchema = Type.Object({
|
||||
task: Type.String(),
|
||||
label: Type.Optional(Type.String()),
|
||||
runtime: optionalStringEnum(SESSIONS_SPAWN_RUNTIMES),
|
||||
agentId: Type.Optional(Type.String()),
|
||||
model: Type.Optional(Type.String()),
|
||||
thinking: Type.Optional(Type.String()),
|
||||
cwd: Type.Optional(Type.String()),
|
||||
runTimeoutSeconds: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
// Back-compat: older callers used timeoutSeconds for this tool.
|
||||
timeoutSeconds: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
@@ -36,15 +41,17 @@ export function createSessionsSpawnTool(opts?: {
|
||||
label: "Sessions",
|
||||
name: "sessions_spawn",
|
||||
description:
|
||||
'Spawn a sub-agent in an isolated session (mode="run" one-shot or mode="session" persistent) and route results back to the requester chat/thread.',
|
||||
'Spawn an isolated session (runtime="subagent" or runtime="acp"). mode="run" is one-shot and mode="session" is persistent/thread-bound.',
|
||||
parameters: SessionsSpawnToolSchema,
|
||||
execute: async (_toolCallId, args) => {
|
||||
const params = args as Record<string, unknown>;
|
||||
const task = readStringParam(params, "task", { required: true });
|
||||
const label = typeof params.label === "string" ? params.label.trim() : "";
|
||||
const runtime = params.runtime === "acp" ? "acp" : "subagent";
|
||||
const requestedAgentId = readStringParam(params, "agentId");
|
||||
const modelOverride = readStringParam(params, "model");
|
||||
const thinkingOverrideRaw = readStringParam(params, "thinking");
|
||||
const cwd = readStringParam(params, "cwd");
|
||||
const mode = params.mode === "run" || params.mode === "session" ? params.mode : undefined;
|
||||
const cleanup =
|
||||
params.cleanup === "keep" || params.cleanup === "delete" ? params.cleanup : "keep";
|
||||
@@ -61,31 +68,50 @@ export function createSessionsSpawnTool(opts?: {
|
||||
: undefined;
|
||||
const thread = params.thread === true;
|
||||
|
||||
const result = await spawnSubagentDirect(
|
||||
{
|
||||
task,
|
||||
label: label || undefined,
|
||||
agentId: requestedAgentId,
|
||||
model: modelOverride,
|
||||
thinking: thinkingOverrideRaw,
|
||||
runTimeoutSeconds,
|
||||
thread,
|
||||
mode,
|
||||
cleanup,
|
||||
expectsCompletionMessage: true,
|
||||
},
|
||||
{
|
||||
agentSessionKey: opts?.agentSessionKey,
|
||||
agentChannel: opts?.agentChannel,
|
||||
agentAccountId: opts?.agentAccountId,
|
||||
agentTo: opts?.agentTo,
|
||||
agentThreadId: opts?.agentThreadId,
|
||||
agentGroupId: opts?.agentGroupId,
|
||||
agentGroupChannel: opts?.agentGroupChannel,
|
||||
agentGroupSpace: opts?.agentGroupSpace,
|
||||
requesterAgentIdOverride: opts?.requesterAgentIdOverride,
|
||||
},
|
||||
);
|
||||
const result =
|
||||
runtime === "acp"
|
||||
? await spawnAcpDirect(
|
||||
{
|
||||
task,
|
||||
label: label || undefined,
|
||||
agentId: requestedAgentId,
|
||||
cwd,
|
||||
mode: mode && ACP_SPAWN_MODES.includes(mode) ? mode : undefined,
|
||||
thread,
|
||||
},
|
||||
{
|
||||
agentSessionKey: opts?.agentSessionKey,
|
||||
agentChannel: opts?.agentChannel,
|
||||
agentAccountId: opts?.agentAccountId,
|
||||
agentTo: opts?.agentTo,
|
||||
agentThreadId: opts?.agentThreadId,
|
||||
},
|
||||
)
|
||||
: await spawnSubagentDirect(
|
||||
{
|
||||
task,
|
||||
label: label || undefined,
|
||||
agentId: requestedAgentId,
|
||||
model: modelOverride,
|
||||
thinking: thinkingOverrideRaw,
|
||||
runTimeoutSeconds,
|
||||
thread,
|
||||
mode,
|
||||
cleanup,
|
||||
expectsCompletionMessage: true,
|
||||
},
|
||||
{
|
||||
agentSessionKey: opts?.agentSessionKey,
|
||||
agentChannel: opts?.agentChannel,
|
||||
agentAccountId: opts?.agentAccountId,
|
||||
agentTo: opts?.agentTo,
|
||||
agentThreadId: opts?.agentThreadId,
|
||||
agentGroupId: opts?.agentGroupId,
|
||||
agentGroupChannel: opts?.agentGroupChannel,
|
||||
agentGroupSpace: opts?.agentGroupSpace,
|
||||
requesterAgentIdOverride: opts?.requesterAgentIdOverride,
|
||||
},
|
||||
);
|
||||
|
||||
return jsonResult(result);
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user