-
Notifications
You must be signed in to change notification settings - Fork 4.6k
fix(delegate-task): guard subagent prompt size against model context limits (fixes #951) #3432
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,11 @@ | ||
| import type { BackgroundTask, LaunchInput, ResumeInput } from "./types" | ||
| import type { OpencodeClient, OnSubagentSessionCreated, QueueItem } from "./constants" | ||
| import { TMUX_CALLBACK_DELAY_MS } from "./constants" | ||
| import { log, getAgentToolRestrictions, promptWithModelSuggestionRetry, createInternalAgentTextPart } from "../../shared" | ||
| import { log } from "../../shared/logger" | ||
| import { getAgentToolRestrictions } from "../../shared/agent-tool-restrictions" | ||
| import { promptWithModelSuggestionRetry } from "../../shared/model-suggestion-retry" | ||
| import { createInternalAgentTextPart } from "../../shared/internal-initiator-marker" | ||
| import { buildSubagentSessionCreateBody } from "../../shared/subagent-context-window" | ||
| import { applySessionPromptParams } from "../../shared/session-prompt-params-helpers" | ||
| import { subagentSessions } from "../claude-code-session-state" | ||
| import { getTaskToastManager } from "../task-toast-manager" | ||
|
|
@@ -95,10 +99,12 @@ export async function startTask( | |
| log(`[background-agent] Parent dir: ${parentSession?.data?.directory}, using: ${parentDirectory}`) | ||
|
|
||
| const createResult = await client.session.create({ | ||
| body: { | ||
| parentID: input.parentSessionID, | ||
| ...(input.sessionPermission ? { permission: input.sessionPermission } : {}), | ||
| } as Record<string, unknown>, | ||
| body: buildSubagentSessionCreateBody({ | ||
| parentSessionID: input.parentSessionID, | ||
| title: input.description, | ||
| permission: input.sessionPermission, | ||
| model: input.model, | ||
| }), | ||
|
Comment on lines
+102
to
+107
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This change applies Useful? React with 👍 / 👎. |
||
| query: { | ||
| directory: parentDirectory, | ||
| }, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import { describe, expect, test } from "bun:test" | ||
| import { createLoopStateController } from "./loop-state-controller" | ||
| import { continueIteration } from "./iteration-continuation" | ||
| import type { RalphLoopState } from "./types" | ||
|
|
||
| describe("ralph-loop default reset strategy", () => { | ||
| test("#given no strategy is configured #when loop starts #then state defaults to reset", () => { | ||
| const loopState = createLoopStateController({ | ||
| directory: process.cwd(), | ||
| stateDir: ".tmp-ralph-loop-default-reset-test", | ||
| config: undefined, | ||
| }) | ||
|
|
||
| const started = loopState.startLoop("session-123", "Ship fix") | ||
|
|
||
| expect(started).toBe(true) | ||
| expect(loopState.getState()?.strategy).toBe("reset") | ||
| loopState.clear() | ||
| }) | ||
|
|
||
| test("#given legacy state without strategy #when loop continues #then it creates a fresh session", async () => { | ||
| const createCalls: Array<{ parentID?: string; directory?: string }> = [] | ||
| const promptCalls: Array<{ sessionID: string; text: string }> = [] | ||
| const selectCalls: string[] = [] | ||
| let currentSessionID = "session-123" | ||
|
|
||
| const state: RalphLoopState = { | ||
| active: true, | ||
| iteration: 2, | ||
| max_iterations: 100, | ||
| completion_promise: "DONE", | ||
| started_at: new Date().toISOString(), | ||
| prompt: "Ship fix", | ||
| session_id: currentSessionID, | ||
| } | ||
|
|
||
| await continueIteration( | ||
| { | ||
| directory: process.cwd(), | ||
| client: { | ||
| session: { | ||
| create: async (options: { body: { parentID?: string }; query?: { directory?: string } }) => { | ||
| createCalls.push({ | ||
| parentID: options.body.parentID, | ||
| directory: options.query?.directory, | ||
| }) | ||
|
|
||
| return { data: { id: "session-456" } } | ||
| }, | ||
| promptAsync: async (options: { path: { id: string }; body: { parts: Array<{ text: string }> } }) => { | ||
| promptCalls.push({ | ||
| sessionID: options.path.id, | ||
| text: options.body.parts[0]?.text ?? "", | ||
| }) | ||
|
|
||
| return {} | ||
| }, | ||
| }, | ||
| tui: { | ||
| selectSession: async (options: { body: { sessionID: string } }) => { | ||
| selectCalls.push(options.body.sessionID) | ||
| return {} | ||
| }, | ||
| }, | ||
| }, | ||
| } as Parameters<typeof continueIteration>[0], | ||
| state, | ||
| { | ||
| directory: process.cwd(), | ||
| apiTimeoutMs: 100, | ||
| previousSessionID: "session-123", | ||
| loopState: { | ||
| setSessionID: (sessionID: string) => { | ||
| currentSessionID = sessionID | ||
| return { ...state, session_id: sessionID } | ||
| }, | ||
| }, | ||
| }, | ||
| ) | ||
|
|
||
| expect(createCalls).toEqual([{ parentID: "session-123", directory: process.cwd() }]) | ||
| expect(promptCalls).toHaveLength(1) | ||
| expect(promptCalls[0]?.sessionID).toBe("session-456") | ||
| expect(selectCalls).toEqual(["session-456"]) | ||
| expect(currentSessionID).toBe("session-456") | ||
| }) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import type { DelegatedModelConfig } from "./model-resolution-types" | ||
| import { findProviderModelMetadata, readProviderModelsCache } from "./connected-providers-cache" | ||
|
|
||
| const SMALL_SUBAGENT_CONTEXT_WINDOW_TOKENS = 32_768 | ||
| const SUBAGENT_PROMPT_CONTEXT_RATIO = 0.5 | ||
| const MIN_SUBAGENT_PROMPT_BUDGET_TOKENS = 2_048 | ||
|
|
||
| function normalizeContextLimit(value: unknown): number | undefined { | ||
| return typeof value === "number" && Number.isFinite(value) && value > 0 | ||
| ? value | ||
| : undefined | ||
| } | ||
|
|
||
| export function resolveModelContextWindowTokens( | ||
| model: DelegatedModelConfig | undefined, | ||
| ): number | undefined { | ||
| if (!model) { | ||
| return undefined | ||
| } | ||
|
|
||
| const metadata = findProviderModelMetadata( | ||
| model.providerID, | ||
| model.modelID, | ||
| readProviderModelsCache(), | ||
| ) | ||
|
|
||
| return normalizeContextLimit(metadata?.limit?.context) | ||
| ?? normalizeContextLimit(metadata?.limit?.input) | ||
| ?? normalizeContextLimit(metadata?.context) | ||
| } | ||
|
|
||
| export function shouldDetachSubagentSession( | ||
| model: DelegatedModelConfig | undefined, | ||
| ): boolean { | ||
| const contextWindow = resolveModelContextWindowTokens(model) | ||
| return contextWindow !== undefined && contextWindow <= SMALL_SUBAGENT_CONTEXT_WINDOW_TOKENS | ||
| } | ||
|
|
||
| export function resolveSubagentPromptTokenBudget( | ||
| model: DelegatedModelConfig | undefined, | ||
| ): number | undefined { | ||
| const contextWindow = resolveModelContextWindowTokens(model) | ||
| if (contextWindow === undefined || contextWindow > SMALL_SUBAGENT_CONTEXT_WINDOW_TOKENS) { | ||
| return undefined | ||
| } | ||
|
|
||
| return Math.max( | ||
| MIN_SUBAGENT_PROMPT_BUDGET_TOKENS, | ||
| Math.floor(contextWindow * SUBAGENT_PROMPT_CONTEXT_RATIO), | ||
| ) | ||
| } | ||
|
|
||
| export function buildSubagentSessionCreateBody(input: { | ||
| parentSessionID: string | ||
| title: string | ||
| permission?: unknown | ||
| model?: DelegatedModelConfig | ||
| }): Record<string, unknown> { | ||
| const body: Record<string, unknown> = { | ||
| title: input.title, | ||
| } | ||
|
|
||
| if (input.permission !== undefined) { | ||
| body.permission = input.permission | ||
| } | ||
|
|
||
| if (!shouldDetachSubagentSession(input.model)) { | ||
| body.parentID = input.parentSessionID | ||
| } | ||
|
|
||
| return body | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: Changing the schema default from
continuetoresetsilently changes behavior for configs that omitdefault_strategy.Prompt for AI agents