From 7dc8faef7fd74ecc55ea8c3b0b34093839177c1c Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:39:31 -0500 Subject: [PATCH 1/2] fix(sendmessage): accept subagent names and agent ids when agent teams a --- CHANGELOG.md | 1 + src/tools/AgentTool/prompt.ts | 2 +- .../SendMessageTool.session.test.ts | 5 +- .../SendMessageTool.subagent.test.ts | 93 +++++++++++++++++++ src/tools/SendMessageTool/SendMessageTool.ts | 12 ++- 5 files changed, 109 insertions(+), 4 deletions(-) create mode 100644 src/tools/SendMessageTool/SendMessageTool.subagent.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4da00877..6a20e6c9 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. +- SendMessage accepts a subagent's name or agent id when agent teams are off, so the agent can continue a subagent it started. Teammate names still need agent teams (#272). - **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/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..83d5d084 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) diff --git a/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts b/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts new file mode 100644 index 00000000..0bf22e68 --- /dev/null +++ b/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts @@ -0,0 +1,93 @@ +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]> = []) => + SendMessageTool.validateInput!( + { to, summary: 'follow up', message: 'hello' } 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 }) + }) + + 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('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() + } + }) +}) diff --git a/src/tools/SendMessageTool/SendMessageTool.ts b/src/tools/SendMessageTool/SendMessageTool.ts index 577c4743..2b880ee6 100644 --- a/src/tools/SendMessageTool/SendMessageTool.ts +++ b/src/tools/SendMessageTool/SendMessageTool.ts @@ -53,6 +53,10 @@ function sessionTargetId(to: string): string { return to.slice(SESSION_ADDRESS_PREFIX.length).trim() } +function isSubagentReference(to: string, context: ToolUseContext): boolean { + return toAgentId(to) !== null || context.getAppState().agentNameRegistry.has(to) +} + function describeRecipient(): string { const sessionAddress = `"${SESSION_ADDRESS_PREFIX}" for another session (use ListSessions to discover)` if (!isAgentSwarmsEnabled()) return `Recipient: ${sessionAddress}` @@ -645,7 +649,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,7 +657,11 @@ export const SendMessageTool: Tool = errorCode: 9, } } - if (!isSessionAddress(input.to) && !isAgentSwarmsEnabled()) { + if ( + !isSessionAddress(input.to) && + !isAgentSwarmsEnabled() && + !isSubagentReference(input.to, context) + ) { return { result: false, message: `to must be a session address: "${SESSION_ADDRESS_PREFIX}"`, From 4ed0e687c44b979a553664700bdbbe2021964214 Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:17:53 -0500 Subject: [PATCH 2/2] fix(sendmessage): validate subagent message routing Signed-off-by: jay23606 <4602056+jay23606@users.noreply.github.com> --- CHANGELOG.md | 2 +- docs/features/harness/prompt/tools.md | 2 +- .../SendMessageTool.session.test.ts | 2 +- .../SendMessageTool.subagent.test.ts | 50 +++++++++++++++++-- src/tools/SendMessageTool/SendMessageTool.ts | 21 +++++--- src/tools/SendMessageTool/prompt.ts | 5 ++ 6 files changed, 68 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a20e6c9..20a1e9b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +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. -- SendMessage accepts a subagent's name or agent id when agent teams are off, so the agent can continue a subagent it started. Teammate names still need agent teams (#272). +- 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/SendMessageTool/SendMessageTool.session.test.ts b/src/tools/SendMessageTool/SendMessageTool.session.test.ts index 83d5d084..1a079af8 100644 --- a/src/tools/SendMessageTool/SendMessageTool.session.test.ts +++ b/src/tools/SendMessageTool/SendMessageTool.session.test.ts @@ -115,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 index 0bf22e68..6c54e714 100644 --- a/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts +++ b/src/tools/SendMessageTool/SendMessageTool.subagent.test.ts @@ -20,9 +20,13 @@ const localAgent = (status: string) => ({ pendingMessages: [] as string[], }) -const validateWith = (to: string, registeredNames: Array<[string, string]> = []) => +const validateWith = ( + to: string, + registeredNames: Array<[string, string]> = [], + message: string | { type: 'shutdown_request' } = 'hello', +) => SendMessageTool.validateInput!( - { to, summary: 'follow up', message: 'hello' } as never, + { to, summary: 'follow up', message } as never, { getAppState: () => ({ agentNameRegistry: new Map(registeredNames), tasks: {} }), } as never, @@ -58,7 +62,17 @@ describe('SendMessage to a subagent with agent teams off', () => { test('still rejects a teammate name', async () => { teams.disable() - expect(await validateWith('researcher')).toMatchObject({ result: false }) + 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 () => { @@ -73,6 +87,18 @@ describe('SendMessage to a subagent with agent teams off', () => { ).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({ @@ -90,4 +116,22 @@ describe('SendMessage to a subagent with agent teams off', () => { 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 2b880ee6..61ca7f2d 100644 --- a/src/tools/SendMessageTool/SendMessageTool.ts +++ b/src/tools/SendMessageTool/SendMessageTool.ts @@ -53,13 +53,19 @@ function sessionTargetId(to: string): string { return to.slice(SESSION_ADDRESS_PREFIX.length).trim() } -function isSubagentReference(to: string, context: ToolUseContext): boolean { - return toAgentId(to) !== null || context.getAppState().agentNameRegistry.has(to) +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' @@ -660,11 +666,11 @@ export const SendMessageTool: Tool = if ( !isSessionAddress(input.to) && !isAgentSwarmsEnabled() && - !isSubagentReference(input.to, context) + (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, } } @@ -787,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') }