Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
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
1 change: 1 addition & 0 deletions docs/users/configuration/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ Settings are organized into categories. Most settings should be placed within th
| `model.maxSessionTurns` | number | Maximum number of user/model/tool turns to keep in a session. -1 means unlimited. | `-1` |
| `model.maxWallTimeSeconds` | number | Wall-clock budget for headless / unattended runs, in seconds. `-1` means unlimited. Overridable per-invocation via `--max-wall-time`, which requires a positive duration (`90`, `30s`, `5m`, `1h`, `1.5h`); the minimum is 1 second — sub-second values (`500ms`, `0.5`) are rejected as typos. Omit the flag to fall back to this setting. Aborts with exit code 55 when exceeded. | `-1` |
| `model.maxToolCalls` | number | Cumulative tool-call budget for a run (counts every executed tool, success or failure; `structured_output` under `--json-schema` is exempt). `-1` means unlimited; `0` means "no tool calls allowed". Capped at 1,000,000 to catch typos. Overridable via `--max-tool-calls`. Aborts with exit code 55 when exceeded. | `-1` |
| `model.maxSubagentDepth` | number | Maximum sub-agent nesting depth (1-based levels: a top-level sub-agent is level 1). `1` keeps sub-agents available but disables nesting — the pre-nesting behavior. Values clamp to the range 1–100; non-finite values fall back to the default. Teammates, forks, and workflow-spawned agents never nest regardless of this setting. Overridable via `--max-subagent-depth`. | `5` |
| `model.generationConfig` | object | Advanced overrides passed to the underlying content generator. Supports request controls such as `timeout`, `maxRetries`, `enableCacheControl`, `splitToolMedia` (default `true`; splits tool-returned media — including images read by the built-in read_file — into a follow-up user message instead of the spec-violating `role: "tool"` message, so strict OpenAI-compatible servers like doubao / new-api / LM Studio can see it; set `false` to restore the legacy embed-in-tool behavior), `toolResultContentFormat` (default `"parts"`; set `"string"` only for legacy OpenAI-compatible runtimes whose tool templates ignore text content parts), `contextWindowSize` (override model's context window size), `modalities` (override auto-detected input modalities), `customHeaders` (custom HTTP headers for API requests), and `extra_body` (additional body parameters for OpenAI-compatible API requests only), along with fine-tuning knobs under `samplingParams` (for example `temperature`, `top_p`, `max_tokens`). Leave unset to rely on provider defaults. | `undefined` |
| `model.chatCompression.contextPercentageThreshold` | number | **REMOVED.** Replaced by `context.autoCompactThreshold` (see `#### context` section below). Auto-compaction now uses a three-tier threshold ladder (warn / auto / hard) computed internally from the model's context window via the `computeThresholds()` function. The old setting is silently ignored (no startup warning). See PR #4345 / `docs/design/auto-compaction-threshold-redesign.md` for the redesign rationale. | `N/A` |
| `model.chatCompression.maxRecentFilesToRetain` | number | Number of most-recently-touched files whose current content is restored (embedded if small, otherwise referenced by path) into history after auto-compaction. `0` restores none. Env override: `QWEN_COMPACT_MAX_RECENT_FILES`. | `5` |
Expand Down
34 changes: 34 additions & 0 deletions packages/cli/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ export interface CliArgs {
maxSessionTurns: number | undefined;
maxWallTime: string | undefined;
maxToolCalls: number | undefined;
maxSubagentDepth: number | undefined;
coreTools: string[] | undefined;
excludeTools: string[] | undefined;
disabledSlashCommands: string[] | undefined;
Expand Down Expand Up @@ -887,6 +888,11 @@ export async function parseArguments(): Promise<CliArgs> {
description:
'Maximum cumulative tool calls executed during the run (success or failure; `structured_output` under --json-schema is exempt). Aborts with exit code 55 when exceeded. -1 / unset means no limit; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos.',
})
.option('max-subagent-depth', {
type: 'number',
description:
'Maximum sub-agent nesting depth (1-based levels). 1 keeps sub-agents available but disables nesting; capped at 100. Overrides model.maxSubagentDepth from settings. Defaults to 5.',
})
.option('core-tools', {
type: 'array',
string: true,
Expand Down Expand Up @@ -1235,6 +1241,32 @@ function resolveMaxToolCalls(argv: CliArgs, settings: Settings): number {
return -1;
}

/**
* Resolves the sub-agent nesting cap. Order of precedence:
* `--max-subagent-depth` flag, then `model.maxSubagentDepth` from settings,
* else undefined (Config applies the default of 5).
*
* Yargs accepts `NaN` from non-numeric flag values, and Config's clamp
* would silently fall back to the default — validate up front so a typo
* fails loudly. Settings values stay lenient (Config clamps them) so a bad
* settings.json cannot break startup.
*/
function resolveMaxSubagentDepth(
argv: CliArgs,
settings: Settings,
): number | undefined {
const value = argv.maxSubagentDepth;
if (value !== undefined && value !== null) {
if (!Number.isInteger(value) || value < 1 || value > 100) {

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.

Cleanup: the {default 5, min 1, max 100} triple is hand-duplicated at three sites.

This validator (bounds in the condition and the error text), normalizeMaxSubagentDepth in core config.ts, and settingsSchema.ts's default: 5 (the vscode settings.schema.json is generated from it, so that one's free). If core's cap or default ever changes, this flag validator drifts — and the failure mode is precisely the one this function's docstring says it exists to prevent: an explicitly passed --max-subagent-depth accepted here, then silently clamped by core.

The codebase already has the exact pattern for this: DEFAULT_STOP_HOOK_BLOCK_CAP and SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH_LIMIT are exported from core and consumed by settingsSchema.ts (both as default: and maximum:). Suggest exporting DEFAULT_MAX_SUBAGENT_DEPTH / MAX_SUBAGENT_DEPTH_LIMIT next to normalizeMaxSubagentDepth, using them there, here (condition + interpolated message), and in the schema default.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4b0c5ac following the DEFAULT_STOP_HOOK_BLOCK_CAP pattern — DEFAULT_MAX_SUBAGENT_DEPTH and MAX_SUBAGENT_DEPTH_LIMIT are exported from core next to the normalizer and consumed by it, the CLI flag validator (condition + interpolated error message), and settingsSchema's default:. The vscode schema stays generated.

throw new Error(
`--max-subagent-depth must be an integer between 1 and 100; got ${value}.`,
);
}
return value;
}
return settings.model?.maxSubagentDepth;
}

export function isDebugMode(argv: CliArgs): boolean {
if (argv.debug) return true;
const debugVal = process.env['DEBUG'];
Expand Down Expand Up @@ -1996,6 +2028,8 @@ export async function loadCliConfig(
argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1,
maxWallTimeSeconds: resolveMaxWallTimeSeconds(argv, settings),
maxToolCalls: resolveMaxToolCalls(argv, settings),
// Undefined flows through to Config's default (5) and clamp logic.

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] No --max-subagent-depth CLI flag, unlike sibling settings --max-session-turns (resolved via resolveMaxSessionTurns(argv, settings)) and --max-tool-calls (resolved via resolveMaxToolCalls(argv, settings)). Users cannot override nesting depth for a single run from the command line. Consider adding a --max-subagent-depth flag with a resolver for consistency.

— qwen3.7-max via Qwen Code /review

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added in 2c50077 — --max-subagent-depth mirrors the sibling budget flags: flag takes precedence over model.maxSubagentDepth, validates loudly as an integer in 1–100 (yargs NaN from a typo fails at startup instead of silently falling back), and the setting is now documented in settings.md alongside the flag.

maxSubagentDepth: resolveMaxSubagentDepth(argv, settings),
experimentalZedIntegration: argv.acp || argv.experimentalAcp || false,
cronEnabled: settings.experimental?.cron ?? true,
agentTeamEnabled: settings.experimental?.agentTeam ?? false,
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/config/settingsSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1360,6 +1360,16 @@ const SETTINGS_SCHEMA = {
'Cumulative tool-call budget for a run (counts every executed tool, success or failure; structured_output under --json-schema is exempt). -1 means unlimited; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos. Overridable via --max-tool-calls.',
showInDialog: false,
},
maxSubagentDepth: {
type: 'number',
label: 'Max Sub-agent Nesting Depth',
category: 'Model',
requiresRestart: false,
default: 5,
description:
'Maximum sub-agent nesting depth (1-based levels: a top-level sub-agent is level 1). 1 keeps sub-agents available but disables nesting; the default 5 allows nesting up to five levels deep. Values clamp to the range 1-100; non-finite values fall back to the default. Teammates, forks, and workflow-spawned agents never nest regardless of this setting. Overridable via --max-subagent-depth.',
showInDialog: false,
},
chatCompression: {
type: 'object',
label: 'Chat Compression',
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/gemini.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1005,6 +1005,7 @@ describe('gemini.tsx main function kitty protocol', () => {
maxSessionTurns: undefined,
maxWallTime: undefined,
maxToolCalls: undefined,
maxSubagentDepth: undefined,
experimentalLsp: undefined,
channel: undefined,
chatRecording: undefined,
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/agents/agent-transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ export interface AgentMeta {
agentColor?: string;
/** Number of explicit resume attempts performed so far. */
resumeCount?: number;
/** Nesting depth at launch time; restored on background/foreground resume. */
depth?: number;
/** Last terminal error, if any. */
lastError?: string;
}
Expand All @@ -135,6 +137,12 @@ export interface AgentPersistedCliFlags {
model?: string;
maxSessionTurns?: number;
maxToolCalls?: number;
/**
* Launch-time nesting cap. Interprets the persisted `depth` — without it a
* nested agent launched under a lower cap would resume after restart under
* the new session's (or default) cap and regain spawn capacity.
*/
maxSubagentDepth?: number;
}

/**
Expand Down
82 changes: 82 additions & 0 deletions packages/core/src/agents/background-agent-resume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from './agent-transcript.js';
import { AgentTerminateMode } from './runtime/agent-types.js';
import { AgentEventEmitter } from './runtime/agent-events.js';
import { getCurrentAgentDepth } from './runtime/agent-context.js';
import { AgentHeadless } from './runtime/agent-headless.js';
import {
FORK_DEFAULT_MAX_TURNS,
Expand Down Expand Up @@ -1058,6 +1059,10 @@ describe('BackgroundAgentResumeService', () => {
model: 'agent-model',
maxSessionTurns: 7,
maxToolCalls: 11,
// Deliberately out of range: the resume path must re-normalize
// persisted values with Config semantics (clamp to 1–100), so a
// malformed or tampered sidecar cannot bypass the nesting cap.
maxSubagentDepth: 5000,
},
});
fs.writeFileSync(
Expand Down Expand Up @@ -1120,6 +1125,83 @@ describe('BackgroundAgentResumeService', () => {
expect(overriddenConfig.getModel()).toBe('agent-model');
expect(overriddenConfig.getMaxSessionTurns()).toBe(7);
expect(overriddenConfig.getMaxToolCalls()).toBe(11);
expect(overriddenConfig.getMaxSubagentDepth()).toBe(100);
}, 20000);

it('restores the persisted launch depth so a resumed nested agent keeps its level', async () => {
// Resume happens from a top-level frame (depth would recompute to 0);
// the persisted meta.depth must be pinned via the runWithAgentContext
// depthOverride, or a resumed nested agent would regain spawn capacity.
const sessionId = 'session-depth';
const agentId = 'agent-depth';
const metaPath = getAgentMetaPath(tempDir, sessionId, agentId);
const outputFile = getAgentJsonlPath(tempDir, sessionId, agentId);

writeAgentMeta(metaPath, {
agentId,
agentType: 'researcher',
description: 'Resume nested agent',
parentSessionId: sessionId,
parentAgentId: 'agent-parent',
createdAt: '2026-04-20T00:00:00.000Z',
status: 'running',
subagentName: 'researcher',
depth: 2,
});
fs.writeFileSync(
outputFile,
JSON.stringify({
uuid: 'u1',
parentUuid: null,
sessionId,
timestamp: '2026-04-20T00:00:00.000Z',
type: 'user',
message: { role: 'user', parts: [{ text: 'Resume nested agent' }] },
}) + '\n',
'utf8',
);

registry.register({
agentId,
description: 'Resume nested agent',
subagentType: 'researcher',
status: 'paused',
startTime: Date.now(),
abortController: new AbortController(),
prompt: 'Resume nested agent',
outputFile,
metaPath,
isBackgrounded: true,
});

let observedDepth = -1;
const createAgentHeadless = vi.fn().mockResolvedValue({
subagent: {
execute: vi.fn(async () => {
observedDepth = getCurrentAgentDepth();
}),
setExternalMessageProvider: vi.fn(),
getCore: () => ({ getEventEmitter: () => new AgentEventEmitter() }),
getExecutionSummary: () => ({
totalTokens: 0,
outputTokens: 0,
totalDurationMs: 0,
}),
getTerminateMode: () => AgentTerminateMode.GOAL,
getFinalText: () => 'done',
},
dispose: vi.fn().mockResolvedValue(undefined),
});

const { service, subagentManager } = createService();
subagentManager.createAgentHeadless = createAgentHeadless;

const resumed = await service.resumeBackgroundAgent(agentId, 'continue');

expect(resumed).toBeDefined();
await vi.waitFor(() => {
expect(observedDepth).toBe(2);
});
}, 20000);

it('coalesces concurrent resume calls into a single running agent', async () => {
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/agents/background-agent-resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,11 @@ export class BackgroundAgentResumeService {
}
};

const framedRunBody = () => runWithAgentContext(meta.agentId, runBody);
// Restore the persisted launch depth so a resumed nested agent keeps
// its original nesting level (and spawn eligibility) instead of
// recomputing to depth 0 from this top-level resume frame.
const framedRunBody = () =>
runWithAgentContext(meta.agentId, runBody, meta.depth);

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.

meta.depth flows into the depth override unvalidated — the other half of the tampered-sidecar defense is missing.

meta comes from readAgentMeta(), which is a bare JSON.parse(...) as AgentMeta, and nothing downstream clamps the value: runWithAgentContext only does depthOverride ?? ... (catches null/undefined only), and childLaunchDepth() / canSpawnNestedAgent() do raw arithmetic.

So a malformed or hand-edited sidecar with "depth": -50 pins the resumed frame at −50 → childLaunchDepth() = −49 → canSpawnNestedAgent() passes for every cap, and the resumed subtree gains ~50 levels beyond maxSubagentDepth. Worse, "depth": -1e309 parses to -Infinity, and since -Infinity + 1 === -Infinity, every descendant inherits it — the cap is permanently defeated for the whole subtree.

This is exactly the threat model the same resume path already defends against for the sibling field: applyPersistedCliFlagOverrides re-normalizes persistedCliFlags.maxSubagentDepth because "a malformed or tampered sidecar … must not bypass the nesting cap". The cap check is effectively depth + 2 <= maxDepth; right now the right-hand operand is hardened and the left-hand operand is trusted raw from the same JSON file. This is also the only place a disk-persisted depth re-enters the runtime, so it's the complete fix site.

Suggest mirroring the normalize pattern before pinning:

const restoredDepth = Number.isFinite(meta.depth)
  ? Math.max(0, Math.floor(meta.depth!))
  : undefined; // fall back to auto-increment
const framedRunBody = () =>
  runWithAgentContext(meta.agentId, runBody, restoredDepth);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 4b0c5ac — normalizeResumedAgentDepth() (next to the AgentMeta type) now guards the depthOverride. Absent values resume as a fresh launch; anything but an integer in 0–100 fails CLOSED to the depth ceiling — clamping a corrupt value down to 0 would fail open by granting full spawn capacity, so the resumed agent keeps running but cannot spawn. Unit tests cover -50, ±Infinity, NaN, fractionals, and >100; the resume-path test is parameterized over a tampered -50 sidecar asserting the frame pins at 100.

void (target.isFork ? runInForkContext(framedRunBody) : framedRunBody());
return entry;
} catch (error) {
Expand Down
Loading
Loading