diff --git a/CHANGELOG.md b/CHANGELOG.md index 4da00877..20a1e9b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ All notable changes to DreamCoder will be documented in this file. ### Fixed - Asking the agent to change a setting no longer fails: the `update-config` skill builds its settings reference again (#293). Thanks @KingEmma7. +- The agent can continue a subagent it started when agent teams are off. Teammate names still need agent teams (#298). Thanks @jay23606. - **Saving a memory no longer asks for approval every time.** Writes to the project's memory folder are allowed like the instructions say, also in bypass mode (#270). - **Stopping a reply keeps the session's context.** Stop ends the agent process only when the reply has not stopped a few seconds after you press Stop, and a restarted agent keeps uploaded images and files, instruction files from subfolders and files restored after compaction, without adding a "Continue from where you left off." message (#270). - The agent knows the available skills again after compaction, gets only newly added skills when the skill folders change, and does not get the whole list again after a restart (#270). diff --git a/docs/features/harness/prompt/tools.md b/docs/features/harness/prompt/tools.md index cb13db8b..223fd5c2 100644 --- a/docs/features/harness/prompt/tools.md +++ b/docs/features/harness/prompt/tools.md @@ -63,7 +63,7 @@ ### T-TOOL-01 Agent 的描述和每次结果都让模型用 SendMessage 续接子 agent,但 SendMessage 在本场景只接受 `session:`,这类调用必然被拒 -- 状态:维护者已定(2026-11-18):放宽 SendMessage 的参数检查,接受已登记的子 agent 名字和格式合法的 agentId;teammate 名字和 `*` 仍要求打开 agent teams。 +- 状态:已修复(#298):SendMessage 在 agent teams 关闭时接受格式合法的子 agent id 和已登记的后台 agent 名字;结构化消息、teammate 名字和 `*` 仍要求打开 agent teams。 - 类型:问题 - 严重程度:高 - 体量:Agent 描述里一句约 190 字符(每个请求);Agent 结果尾注约 70 字符加 agentId(每次非 Explore/Plan 的同步完成和每次后台启动都出现);被拒后多一轮。 diff --git a/src/tools/AgentTool/prompt.ts b/src/tools/AgentTool/prompt.ts index 814dd873..c99c546c 100644 --- a/src/tools/AgentTool/prompt.ts +++ b/src/tools/AgentTool/prompt.ts @@ -264,7 +264,7 @@ Usage notes: - **Foreground vs background**: Use foreground (default) when you need the agent's results before you can proceed — e.g., research agents whose findings inform your next steps. Use background when you have genuinely independent work to do in parallel.` : '' } -- To continue a previously spawned agent, use ${SEND_MESSAGE_TOOL_NAME} with the agent's ID or name as the \`to\` field. The agent resumes with its full context preserved. ${forkEnabled ? 'Each fresh Agent invocation with a subagent_type starts without context — provide a complete task description.' : 'Each Agent invocation starts fresh — provide a complete task description.'} +- To continue a previously spawned agent, use ${SEND_MESSAGE_TOOL_NAME} with the agent's ID as the \`to\` field (or the name of a background agent you started with one). The agent resumes with its full context preserved. ${forkEnabled ? 'Each fresh Agent invocation with a subagent_type starts without context — provide a complete task description.' : 'Each Agent invocation starts fresh — provide a complete task description.'} - The agent's outputs should generally be trusted - Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.)${forkEnabled ? '' : ", since it is not aware of the user's intent"} - If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. diff --git a/src/tools/SendMessageTool/SendMessageTool.session.test.ts b/src/tools/SendMessageTool/SendMessageTool.session.test.ts index 73c86e9e..1a079af8 100644 --- a/src/tools/SendMessageTool/SendMessageTool.session.test.ts +++ b/src/tools/SendMessageTool/SendMessageTool.session.test.ts @@ -15,7 +15,10 @@ afterEach(() => { teams.restore() }) -const validate = (input: Record) => SendMessageTool.validateInput!(input as never, {} as never) +const validate = (input: Record) => + SendMessageTool.validateInput!(input as never, { + getAppState: () => ({ agentNameRegistry: new Map(), tasks: {} }), + } as never) const run = (input: Record) => SendMessageTool.call(input as never, {} as never, undefined as never, undefined as never) @@ -112,7 +115,7 @@ describe('SendMessage to a session', () => { expect(SendMessageTool.isEnabled()).toBe(true) }) - test('accepts only session addresses without agent teams', async () => { + test('rejects unregistered recipients without agent teams', async () => { teams.disable() env.enable() const result = await validate({ to: 'researcher', summary: 's', message: 'hello' }) diff --git a/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts b/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts new file mode 100644 index 00000000..6c54e714 --- /dev/null +++ b/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts @@ -0,0 +1,137 @@ +import { afterEach, describe, expect, spyOn, test } from 'bun:test' +import * as resumeAgent from '../AgentTool/resumeAgent.js' +import { useEnvFlag } from '../../utils/__tests__/hostRequesterFixture.js' +import { SendMessageTool } from './SendMessageTool.js' + +const teams = useEnvFlag('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS') + +afterEach(() => { + teams.restore() +}) + +const AGENT_ID = 'a1234567890abcdef' + +type TestState = { agentNameRegistry: Map; tasks: Record } + +const localAgent = (status: string) => ({ + id: AGENT_ID, + type: 'local_agent', + status, + pendingMessages: [] as string[], +}) + +const validateWith = ( + to: string, + registeredNames: Array<[string, string]> = [], + message: string | { type: 'shutdown_request' } = 'hello', +) => + SendMessageTool.validateInput!( + { to, summary: 'follow up', message } as never, + { + getAppState: () => ({ agentNameRegistry: new Map(registeredNames), tasks: {} }), + } as never, + ) + +const sendWith = async (to: string, state: TestState) => { + let current = state + const input = { to, summary: 'follow up', message: 'hello' } + const context = { + getAppState: () => current, + setAppState: (update: (prev: TestState) => TestState) => { + current = update(current) + }, + } + const validation = await SendMessageTool.validateInput!(input as never, context as never) + const output = + validation.result === true + ? await SendMessageTool.call(input as never, context as never, undefined as never, undefined as never) + : validation + return { output, getState: () => current } +} + +describe('SendMessage to a subagent with agent teams off', () => { + test('accepts a well-formed agent id', async () => { + teams.disable() + expect(await validateWith(AGENT_ID)).toEqual({ result: true }) + }) + + test('accepts a registered subagent name', async () => { + teams.disable() + expect(await validateWith('explorer', [['explorer', AGENT_ID]])).toEqual({ result: true }) + }) + + test('still rejects a teammate name', async () => { + teams.disable() + expect(await validateWith('researcher')).toMatchObject({ + result: false, + message: expect.stringContaining('registered background-agent name'), + }) + }) + + test('rejects a structured message to a subagent id', async () => { + teams.disable() + expect(await validateWith(AGENT_ID, [], { type: 'shutdown_request' })).toMatchObject({ + result: false, + }) + }) + + test('queues the message on a running subagent by agent id', async () => { + teams.disable() + const { output, getState } = await sendWith(AGENT_ID, { + agentNameRegistry: new Map(), + tasks: { [AGENT_ID]: localAgent('running') }, + }) + expect(output).toMatchObject({ data: { success: true } }) + expect( + (getState().tasks[AGENT_ID] as { pendingMessages: string[] }).pendingMessages, + ).toEqual(['hello']) + }) + + test('queues the message on a running subagent by registered name', async () => { + teams.disable() + const { output, getState } = await sendWith('explorer', { + agentNameRegistry: new Map([['explorer', AGENT_ID]]), + tasks: { [AGENT_ID]: localAgent('running') }, + }) + expect(output).toMatchObject({ data: { success: true } }) + expect( + (getState().tasks[AGENT_ID] as { pendingMessages: string[] }).pendingMessages, + ).toEqual(['hello']) + }) + + test('resumes a stopped subagent by agent id', async () => { + teams.disable() + const resume = spyOn(resumeAgent, 'resumeAgentBackground').mockResolvedValue({ + outputFile: '/tmp/agent-output', + } as never) + try { + const { output } = await sendWith(AGENT_ID, { + agentNameRegistry: new Map(), + tasks: { [AGENT_ID]: localAgent('completed') }, + }) + expect(output).toMatchObject({ data: { success: true } }) + expect(resume).toHaveBeenCalledTimes(1) + expect(resume.mock.calls[0]?.[0]).toMatchObject({ agentId: AGENT_ID, prompt: 'hello' }) + } finally { + resume.mockRestore() + } + }) + + test('resumes a subagent from its transcript when its task was evicted', async () => { + teams.disable() + const resume = spyOn(resumeAgent, 'resumeAgentBackground').mockResolvedValue({ + outputFile: '/tmp/agent-output', + } as never) + try { + const { output } = await sendWith(AGENT_ID, { + agentNameRegistry: new Map(), + tasks: {}, + }) + expect(output).toMatchObject({ data: { success: true } }) + expect(resume).toHaveBeenCalledTimes(1) + expect(resume.mock.calls[0]?.[0]).toMatchObject({ agentId: AGENT_ID, prompt: 'hello' }) + } finally { + resume.mockRestore() + } + }) +}) diff --git a/src/tools/SendMessageTool/SendMessageTool.ts b/src/tools/SendMessageTool/SendMessageTool.ts index 577c4743..61ca7f2d 100644 --- a/src/tools/SendMessageTool/SendMessageTool.ts +++ b/src/tools/SendMessageTool/SendMessageTool.ts @@ -53,9 +53,19 @@ function sessionTargetId(to: string): string { return to.slice(SESSION_ADDRESS_PREFIX.length).trim() } +function resolveSubagentId(to: string, context: ToolUseContext): string | null { + const appState = context.getAppState() + return appState.agentNameRegistry.get(to) ?? toAgentId(to) +} + function describeRecipient(): string { + if (!isAgentSwarmsEnabled()) { + const subagent = 'a subagent id or a registered name for a background agent started with a name' + return isSessionLinksEnabled() + ? `Recipient: ${subagent}, or "${SESSION_ADDRESS_PREFIX}" for another session (use ListSessions to discover)` + : `Recipient: ${subagent}` + } const sessionAddress = `"${SESSION_ADDRESS_PREFIX}" for another session (use ListSessions to discover)` - if (!isAgentSwarmsEnabled()) return `Recipient: ${sessionAddress}` return isSessionLinksEnabled() ? `Recipient: teammate name, "*" for broadcast to all teammates, or ${sessionAddress}` : 'Recipient: teammate name, or "*" for broadcast to all teammates' @@ -645,7 +655,7 @@ export const SendMessageTool: Tool = return { behavior: 'allow' as const, updatedInput: input } }, - async validateInput(input, _context) { + async validateInput(input, context) { if (input.to.trim().length === 0) { return { result: false, @@ -653,10 +663,14 @@ export const SendMessageTool: Tool = errorCode: 9, } } - if (!isSessionAddress(input.to) && !isAgentSwarmsEnabled()) { + if ( + !isSessionAddress(input.to) && + !isAgentSwarmsEnabled() && + (typeof input.message !== 'string' || !resolveSubagentId(input.to, context)) + ) { return { result: false, - message: `to must be a session address: "${SESSION_ADDRESS_PREFIX}"`, + message: `to must be a session address: "${SESSION_ADDRESS_PREFIX}", a subagent id, or a registered background-agent name`, errorCode: 9, } } @@ -779,10 +793,9 @@ export const SendMessageTool: Tool = // Route to in-process subagent by name or raw agentId before falling // through to ambient-team resolution. Stopped agents are auto-resumed. if (typeof input.message === 'string' && input.to !== '*') { - const appState = context.getAppState() - const registered = appState.agentNameRegistry.get(input.to) - const agentId = registered ?? toAgentId(input.to) + const agentId = resolveSubagentId(input.to, context) if (agentId) { + const appState = context.getAppState() const task = appState.tasks[agentId] if (isLocalAgentTask(task) && !isMainSessionTask(task)) { if (task.status === 'running') { diff --git a/src/tools/SendMessageTool/prompt.ts b/src/tools/SendMessageTool/prompt.ts index 9bc4cf2b..d3a7b2ea 100644 --- a/src/tools/SendMessageTool/prompt.ts +++ b/src/tools/SendMessageTool/prompt.ts @@ -27,6 +27,10 @@ If you receive a JSON message with \`type: "shutdown_request"\` or \`type: "plan Approving shutdown terminates your process. Rejecting plan sends the teammate back to revise. Don't originate \`shutdown_request\` unless asked. Don't send structured JSON status messages — use TaskUpdate.` +const SUBAGENT_SECTION = `## Background agents + +To continue a background agent started with the Agent tool, set \`to\` to its agent id from the Agent result. You can use its registered name instead if it was started with a name. Send only a plain text message.` + const SESSION_ADDRESS_SECTION = `## Other sessions \`\`\`json @@ -46,6 +50,7 @@ export const DESCRIPTION = 'Send a message to another agent' export function getPrompt(): string { const sections = ['# SendMessage\n\nSend a message to another agent.'] if (isAgentSwarmsEnabled()) sections.push(TEAMMATE_SECTION.trim()) + else sections.push(SUBAGENT_SECTION) if (isSessionLinksEnabled()) sections.push(SESSION_ADDRESS_SECTION) return sections.join('\n\n') }