Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions packages/core/src/tools/agent/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ describe('AgentTool', () => {
getTranscriptPath: vi.fn().mockReturnValue('/test/transcript'),
getApprovalMode: vi.fn().mockReturnValue('default'),
isTrustedFolder: vi.fn().mockReturnValue(true),
isInteractive: vi.fn().mockReturnValue(false),
getBackgroundTaskRegistry: vi.fn().mockReturnValue(stubRegistry),
getMonitorRegistry: vi.fn().mockReturnValue(stubMonitorRegistry),
getToolRegistry: vi.fn().mockReturnValue(stubToolRegistry),
Expand Down Expand Up @@ -235,6 +236,43 @@ describe('AgentTool', () => {
expect(failedAgentTool.description).toContain('general-purpose');
expect(failedAgentTool.description).toContain('Explore');
});

it('includes "When to fork" section in description when interactive', async () => {
(config as unknown as Record<string, unknown>)['isInteractive'] = vi
.fn()
.mockReturnValue(true);

const interactiveTool = new AgentTool(config);
await vi.runAllTimersAsync();

expect(interactiveTool.description).toContain('When to fork');
expect(interactiveTool.description).toContain("Don't peek");
expect(interactiveTool.description).toContain("Don't race");
expect(interactiveTool.description).toContain('Writing a fork prompt');
});

it('omits fork discipline but keeps "Writing the prompt" when non-interactive', async () => {
(config as unknown as Record<string, unknown>)['isInteractive'] = vi
.fn()
.mockReturnValue(false);

const nonInteractiveTool = new AgentTool(config);
await vi.runAllTimersAsync();

// Fork-specific sections must be absent
expect(nonInteractiveTool.description).not.toContain('When to fork');
expect(nonInteractiveTool.description).not.toContain("Don't peek");
expect(nonInteractiveTool.description).not.toContain("Don't race");
expect(nonInteractiveTool.description).not.toContain(
'Writing a fork prompt',
);

// "Writing the prompt" section is always present (useful for fresh agents too)
expect(nonInteractiveTool.description).toContain('Writing the prompt');
expect(nonInteractiveTool.description).toContain(
'Never delegate understanding',
);
});
});

describe('schema generation', () => {
Expand Down Expand Up @@ -782,6 +820,31 @@ describe('AgentTool', () => {
} as unknown as ReturnType<Config['getGeminiClient']>);

vi.mocked(AgentHeadless.create).mockResolvedValue(mockAgent);

// Fork requires interactive mode — gate added by isForkSubagentEnabled().
(config as unknown as Record<string, unknown>)['isInteractive'] = vi
.fn()
.mockReturnValue(true);
});

it('rejects fork in non-interactive mode', async () => {
vi.mocked(
config.isInteractive as ReturnType<typeof vi.fn>,
).mockReturnValue(false);

const params: AgentParams = {
description: 'fork task',
prompt: 'do the thing',
};

const invocation = (
agentTool as AgentToolWithProtectedMethods
).createInvocation(params);
const result = await invocation.execute();

const llmText = partToString(result.llmContent);
expect(llmText).toContain('not available in non-interactive mode');
expect(AgentHeadless.create).not.toHaveBeenCalled();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The "rejects fork in non-interactive mode" test verifies llmContent and that AgentHeadless.create was not called, but does not verify the returnDisplay shape. Other tests in this file (e.g., the subagent-not-found test) verify returnDisplay.status, returnDisplay.subagentName, and returnDisplay.terminateReason. This gap means a regression in the UI-facing error display would go undetected.

Suggested change
expect(AgentHeadless.create).not.toHaveBeenCalled();
const llmText = partToString(result.llmContent);
expect(llmText).toContain('not available in non-interactive mode');
expect(AgentHeadless.create).not.toHaveBeenCalled();
const display = result.returnDisplay as {
status: string;
subagentName: string;
terminateReason: string;
};
expect(display.status).toBe('failed');
expect(display.subagentName).toBe('fork');
expect(display.terminateReason).toBe(
'Fork subagent is not available in non-interactive mode',
);

— qwen3.7-max via Qwen Code /review

});

it('should call AgentHeadless.create directly and execute without options', async () => {
Expand Down
50 changes: 50 additions & 0 deletions packages/core/src/tools/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
buildChildMessage,
buildWorktreeNotice,
isInForkExecution,
isForkSubagentEnabled,
runInForkContext,
} from './fork-subagent.js';
import {
Expand Down Expand Up @@ -547,7 +548,37 @@ Usage notes:
- If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Agent tool use content blocks. For example, if you need to launch both a build-validator agent and a test-runner agent in parallel, send a single message with both tool calls.
- You can optionally set \`run_in_background: true\` to run the agent in the background. You will be notified when it completes. Use this when you have genuinely independent work to do in parallel and don't need the agent's results before you can proceed.
- You can optionally set \`isolation: "worktree"\` to run the agent in a temporary git worktree, giving it an isolated copy of the repository. The worktree is automatically cleaned up if the agent makes no changes; if changes are made, the worktree path and branch are returned in the result so you can review or merge them.
${
isForkSubagentEnabled(this.config)
? `
## When to fork

Fork yourself (omit \`subagent_type\`) when the intermediate tool output isn't worth keeping in your context. The criterion is qualitative — "will I need this output again" — not task size.
- **Research**: fork open-ended questions. If research can be broken into independent questions, launch parallel forks in one message. A fork beats a fresh subagent for this — it inherits context and shares your cache.
- **Implementation**: prefer to fork implementation work that requires more than a couple of edits. Do research before jumping to implementation.

Forks are cheap because they share your prompt cache. Don't set \`model\` on a fork — a different model can't reuse the parent's cache. Pass a short \`name\` (one or two words, lowercase) so the user can track the fork.

**Don't peek.** The tool result includes an output — do not read or tail it unless the user explicitly asks for a progress check. You get a completion notification; trust it. Reading the transcript mid-flight pulls the fork's tool noise into your context, which defeats the point of forking.

**Don't race.** After launching, you know nothing about what the fork found. Never fabricate or predict fork results in any format — not as prose, summary, or structured output. The notification arrives as a user-role message in a later turn; it is never something you write yourself. If the user asks a follow-up before the notification lands, tell them the fork is still running — give status, not a guess.

**Writing a fork prompt.** Since the fork inherits your context, the prompt is a *directive* — what to do, not what the situation is. Be specific about scope: what's in, what's out, what another agent is handling. Don't re-explain background.
`
: ''
}
## Writing the prompt

${isForkSubagentEnabled(this.config) ? 'When spawning a fresh agent (with a `subagent_type`), it starts with zero context. ' : ''}Brief the agent like a smart colleague who just walked into the room — it hasn't seen this conversation, doesn't know what you've tried, doesn't understand why this task matters.
- Explain what you're trying to accomplish and why.
- Describe what you've already learned or ruled out.
- Give enough context about the surrounding problem that the agent can make judgment calls rather than just following a narrow instruction.
- If you need a short response, say so ("report in under 200 words").
- Lookups: hand over the exact command. Investigations: hand over the question — prescribed steps become dead weight when the premise is wrong.

${isForkSubagentEnabled(this.config) ? 'For fresh agents, terse' : 'Terse'} command-style prompts produce shallow, generic work.

**Never delegate understanding.** Don't write "based on your findings, fix the bug" or "based on the research, implement it." Those phrases push synthesis onto the agent instead of doing it yourself. Write prompts that prove you understood: include file paths, line numbers, what specifically to change.
Comment thread
DennisYu07 marked this conversation as resolved.
Resolved
Example usage:

<example_agent_descriptions>
Expand Down Expand Up @@ -1389,6 +1420,25 @@ class AgentToolInvocation extends BaseToolInvocation<AgentParams, ToolResult> {
let subagentConfig: SubagentConfig;

if (isFork) {
// Gate: fork is only available in interactive sessions.
// Non-interactive sessions (qwen -p, SDK headless, CI/CD) lack a
// terminal UI for fork progress display and permission bubble-up.
if (!isForkSubagentEnabled(this.config)) {
return {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The fork gate rejection returns an error to the LLM but emits no log or telemetry. Other tool-level events in this file use debugLogger.warn/info/error. In headless/SDK mode, nobody watches the returnDisplay — the LLM may retry the fork multiple times, burning tokens, with zero log trail for debugging.

Suggested change
return {
if (!isForkSubagentEnabled(this.config)) {
debugLogger.warn(
'[Agent] Fork subagent blocked: session is not interactive',
);
return {

— qwen-latest-series-invite-beta-v38 via Qwen Code /review

llmContent:
'Error: Fork subagent is not available in non-interactive mode. Use an explicit subagent_type instead.',
returnDisplay: {
type: 'task_execution' as const,
subagentName: FORK_AGENT.name,
taskDescription: this.params.description,
taskPrompt: this.params.prompt,
status: 'failed' as const,
terminateReason:
'Fork subagent is not available in non-interactive mode',
},
};
}

subagentConfig = FORK_AGENT;

// Recursive-fork guard. A fork child's reasoning loop runs inside
Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/tools/agent/fork-subagent.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import type { Content } from '@google/genai';
import type { Config } from '../../config/config.js';

export const FORK_SUBAGENT_TYPE = 'fork';

/**
* Fork subagent feature gate.
*
* Fork is only available in interactive sessions. Non-interactive sessions
* (e.g. `qwen -p`, SDK headless, CI/CD) lack a terminal UI for fork progress
* display and permission bubble-up, which can cause hangs or silent failures.
*/
export function isForkSubagentEnabled(config: Config): boolean {
return config.isInteractive();
}

export const FORK_BOILERPLATE_TAG = 'fork-boilerplate';
export const FORK_DIRECTIVE_PREFIX = 'Directive: ';

Expand Down
Loading