Skip to content

Commit 6739059

Browse files
authored
fix(headless): keep going when a reply hits the output limit (#6379)
A model reply that stopped at the output-token cap while writing a tool call came back with no complete call, and the runner took that as the final answer: the turn ended "completed" with nothing done. Background tasks that wrote one large script (a whole Blender scene) finished this way with an empty report. Every provider now reports a cut-off reply. A call it was writing gets an error saying to split the work, and a reply with no complete call is dropped; the next step is told to send less. Three cut-off replies in a row fail the turn with output_limit, which Workbot and task reports explain in plain words. The desktop tool now suggests building Blender scenes in several short scripts, or with blender -b for long builds. Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent ac09838 commit 6739059

11 files changed

Lines changed: 140 additions & 23 deletions

File tree

‎ee/apps/headless-runner/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ Turn status is one of `queued`, `running`, `completed`, `failed`, `interrupted`
7373
- `turn_timeout`
7474
- `max_steps_exceeded` (only with `HEADLESS_MAX_STEPS` set)
7575
- `stuck_repeating`
76+
- `output_limit` (the model's replies stopped at `HEADLESS_MAX_OUTPUT_TOKENS` three times in a row)
7677
- `runner_restarted`
7778
- `credentials_refresh` (an `interrupted` turn waiting to be resumed with a fresh MCP token)
7879
- `step_crash_loop` (step mode: one step kept dying, see [Step mode](#step-mode))
@@ -316,7 +317,7 @@ Nothing on celld changes, so pointing the URLs back is the rollback.
316317
| `HEADLESS_MAX_STEPS` | `0` | Model calls per turn. `0` means no limit: a long task ends with its answer, Stop, or the stuck check |
317318
| `HEADLESS_TURN_TIMEOUT_MS` | `0` | `0` means no limit. Otherwise at least `10000`, applied to each stretch between credential refreshes |
318319
| `HEADLESS_CREDENTIAL_REFRESH_MS` | `3000000` | A turn with an MCP token pauses between steps after this long so the caller resumes it with a fresh one. Keep it under the token lifetime (60 minutes for Den) |
319-
| `HEADLESS_MAX_OUTPUT_TOKENS` | `8192` | Output cap per model call: Anthropic `max_tokens`, OpenAI `max_completion_tokens` |
320+
| `HEADLESS_MAX_OUTPUT_TOKENS` | `8192` | Output cap per model call: Anthropic `max_tokens`, OpenAI `max_completion_tokens`. A reply cut off there never ends a turn: a call it was writing gets an error, a reply with no complete call is dropped, and the next step asks for less |
320321
| `HEADLESS_CONTEXT_CHAR_BUDGET` | `400000` | Past this, the oldest whole turns are left out, down to 60% of it (see [Long conversations](#long-conversations)). A turn that outgrows it alone replaces its oldest large tool outputs with a short note, in blocks of eight |
321322
| `HEADLESS_SYSTEM_PROMPT` | built-in | |
322323
| `HEADLESS_FILES` | `off` | Saved files: `off`, `disk`, or `s3`. Only sessions created with `files: true` use them. Off means the file routes answer `files_not_configured` |

‎ee/apps/headless-runner/scripts/celld-smoke-result.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export const smokeView = z.object({
99

1010
// Never echo provider details, arbitrary error strings, or conversation content into deployment logs.
1111
const safeErrors = new Set([
12-
"model_credentials_missing", "mcp_unavailable", "credentials_refresh", "stuck_repeating",
12+
"model_credentials_missing", "mcp_unavailable", "credentials_refresh", "stuck_repeating", "output_limit",
1313
"max_steps_exceeded", "runner_shutdown", "turn_timeout", "runner_error", "superseded",
1414
"model_unreachable", "model_failed", "model_bad_response", "model_stream_interrupted",
1515
])

‎ee/apps/headless-runner/scripts/model-responses.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import assert from "node:assert/strict"
22
import test from "node:test"
3-
import { ModelError, openAIResponsesModel, toResponsesInput } from "../src/model.js"
3+
import { CUT_OFF_CALL, ModelError, openAIResponsesModel, toResponsesInput } from "../src/model.js"
44
import type { Message } from "../src/types.js"
55

66
const tool = { name: "mail_search", description: "Search mail", inputSchema: { type: "object", properties: { query: { type: "string" } } } }
@@ -90,3 +90,20 @@ test("a failed response is a model error, not an empty answer", async () => {
9090
(error: unknown) => error instanceof ModelError && error.code === "model_failed" && /The model crashed/.test(error.message),
9191
)
9292
})
93+
94+
test("a response stopped at the output cap is marked cut off, and the call it was writing is not run", async () => {
95+
const { fetch } = recorder(() => sse([
96+
{ type: "response.output_item.added", item: { type: "function_call", name: "mail_search" } },
97+
{ type: "response.incomplete", response: { status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, output: [
98+
{ type: "function_call", call_id: "call_3", name: "mail_search", arguments: "{\"query\":\"Blue Har" },
99+
], usage: { input_tokens: 10, output_tokens: 100 } } },
100+
]))
101+
const step = await openAIResponsesModel({ baseUrl: "https://gateway.test/v1", maxOutputTokens: 100, fetch }).complete(request({ onText: () => undefined }))
102+
assert.equal(step.cutOff, true)
103+
assert.deepEqual(step.toolCalls, [{ id: "call_3", name: "mail_search", input: {}, inputError: CUT_OFF_CALL }])
104+
105+
const { fetch: empty } = recorder(() => Response.json({ status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, output: [] }))
106+
const bare = await openAIResponsesModel({ baseUrl: "https://gateway.test/v1", maxOutputTokens: 100, fetch: empty }).complete(request())
107+
assert.equal(bare.cutOff, true)
108+
assert.deepEqual(bare.toolCalls, [])
109+
})

‎ee/apps/headless-runner/scripts/steps.test.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import type { ModelClient, ModelRequest } from "../src/model.js"
1313
import { nodeSqlite } from "../src/node-sqlite.js"
1414
import type { SqlDriver } from "../src/sql.js"
1515
import { grantVault } from "../src/resume-grants.js"
16-
import { Runner, type RunnerOptions } from "../src/runner.js"
16+
import { CUT_OFF_INSTRUCTION, Runner, type RunnerOptions } from "../src/runner.js"
1717
import { SelfResume } from "../src/self-resume.js"
1818
import { FRESH_REPEAT, type StepState } from "../src/steps.js"
1919
import { Store } from "../src/store.js"
@@ -532,3 +532,37 @@ test("a Node runner that shuts down mid-step leaves the turn to go on when it st
532532
assert.equal(second.store.getTurn(session.id, "m1")?.status, "completed")
533533
assert.equal(second.store.getTurn(session.id, "m2")?.status, "completed")
534534
})
535+
536+
test("a reply cut off at the output cap never ends the turn: it is dropped, the model is asked for less, and repeats fail", async () => {
537+
for (const execution of [undefined, "steps" as const]) {
538+
using temp = tempDir()
539+
const systems: string[] = []
540+
// Cut off twice (text only, then nothing), then answers.
541+
const model: ModelClient = {
542+
async complete(request) {
543+
systems.push(request.system)
544+
if (systems.length === 1) return { text: "Here is the whole scri", toolCalls: [], usage, cutOff: true }
545+
if (systems.length === 2) return { text: "", toolCalls: [], usage, cutOff: true }
546+
return { text: "Built it in parts.", toolCalls: [], usage }
547+
},
548+
}
549+
const { store, runner } = world(temp.directory, { model })
550+
store.putSession("hs_cut_off", { owner: "test" })
551+
runner.send({ sessionId: "hs_cut_off", messageId: "m1", prompt: "Model an apartment", credentials: {}, ...(execution ? { execution } : {}) })
552+
await runner.idle()
553+
await drain(runner, store)
554+
assert.equal(store.getTurn("hs_cut_off", "m1")?.status, "completed", `${execution ?? "one go"}`)
555+
assert.deepEqual(transcript(store, "hs_cut_off", "m1").filter((message) => message.role === "assistant").map((message) => message.text), ["Built it in parts."])
556+
assert.deepEqual(systems.map((system) => system.includes(CUT_OFF_INSTRUCTION)), [false, true, true])
557+
558+
const always: ModelClient = { async complete() { return { text: "", toolCalls: [], usage, cutOff: true } } }
559+
using other = tempDir()
560+
const failing = world(other.directory, { model: always })
561+
failing.store.putSession("hs_cut_off", { owner: "test" })
562+
failing.runner.send({ sessionId: "hs_cut_off", messageId: "m1", prompt: "Model an apartment", credentials: {}, ...(execution ? { execution } : {}) })
563+
await failing.runner.idle()
564+
await drain(failing.runner, failing.store)
565+
const turn = failing.store.getTurn("hs_cut_off", "m1")
566+
assert.deepEqual([turn?.status, turn?.error], ["failed", "output_limit"], `${execution ?? "one go"}`)
567+
}
568+
})

‎ee/apps/headless-runner/src/model.ts‎

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ export type ModelStep = {
4141
toolCalls: ToolCall[]
4242
/** inputTokens includes cachedInputTokens. */
4343
usage: Usage
44+
/** The reply stopped at the output-token cap: it is unfinished, and a call it was writing carries `CUT_OFF_CALL`. */
45+
cutOff?: boolean
4446
}
4547
export type Usage = { inputTokens: number; cachedInputTokens: number; outputTokens: number }
4648
export type ModelClient = {
@@ -216,6 +218,16 @@ async function withStreamRetries(request: ModelRequest, sleep: Sleep, run: () =>
216218

217219
const streamInterrupted = () => new ModelError("model_stream_interrupted", "The AI gateway stream ended early.", true)
218220

221+
/** The error a call gets when the reply stopped at the output-token cap while writing it. */
222+
export const CUT_OFF_CALL =
223+
"Your reply reached the output limit while writing this call, so it was cut off and not run. Send less in one call: split long code, scripts or documents into parts (for example, write a file in several pieces, then run it)."
224+
225+
/** Marks a step that stopped at the output-token cap; a call left unparsable by the cut gets `CUT_OFF_CALL`. */
226+
function cutOffStep(step: ModelStep, cutOff: boolean): ModelStep {
227+
if (!cutOff) return step
228+
return { ...step, cutOff: true, toolCalls: step.toolCalls.map((call) => (call.inputError ? { ...call, input: {}, inputError: CUT_OFF_CALL } : call)) }
229+
}
230+
219231
function parseArguments(raw: string): Pick<ToolCall, "input" | "inputError"> {
220232
try {
221233
const value: unknown = JSON.parse(raw || "{}")
@@ -367,6 +379,7 @@ const reportedModel = (value: string | null | undefined) => value && /^[A-Za-z0-
367379

368380
const anthropicResponse = z.object({
369381
model: z.string().nullish(),
382+
stop_reason: z.string().nullish(),
370383
content: z.array(
371384
z.discriminatedUnion("type", [
372385
z.object({ type: z.literal("text"), text: z.string() }),
@@ -405,7 +418,7 @@ const anthropicEvent = z
405418
message: z.object({ model: z.string().nullish(), usage: z.record(z.string(), z.unknown()).optional() }).loose().optional(),
406419
content_block: z.object({ type: z.string(), id: z.string().optional(), name: z.string().optional() }).loose().optional(),
407420
delta: z
408-
.object({ type: z.string().optional(), text: z.string().optional(), partial_json: z.string().optional() })
421+
.object({ type: z.string().optional(), text: z.string().optional(), partial_json: z.string().optional(), stop_reason: z.string().nullish() })
409422
.loose()
410423
.optional(),
411424
usage: z.record(z.string(), z.unknown()).optional(),
@@ -425,6 +438,7 @@ async function readAnthropicStream(
425438
const blocks = new Map<number, { kind: "text"; text: string } | { kind: "tool"; id: string; name: string; json: string } | { kind: "other" }>()
426439
const usage: Usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 }
427440
let stopped = false
441+
let stopReason: string | null | undefined
428442
let model: string | undefined
429443
try {
430444
for await (const raw of sseData(response, signal)) {
@@ -456,8 +470,9 @@ async function readAnthropicStream(
456470
} else if (block?.kind === "tool" && value.delta.partial_json) {
457471
block.json += value.delta.partial_json
458472
}
459-
} else if (value.type === "message_delta" && value.usage) {
460-
usage.outputTokens = tokenCount(value.usage.output_tokens) || usage.outputTokens
473+
} else if (value.type === "message_delta") {
474+
stopReason = value.delta?.stop_reason ?? stopReason
475+
if (value.usage) usage.outputTokens = tokenCount(value.usage.output_tokens) || usage.outputTokens
461476
} else if (value.type === "message_stop") {
462477
stopped = true
463478
} else if (value.type === "error") {
@@ -477,12 +492,12 @@ async function readAnthropicStream(
477492
}
478493
if (!stopped) throw streamInterrupted()
479494
const ordered = [...blocks.entries()].sort(([left], [right]) => left - right).map(([, block]) => block)
480-
return {
495+
return cutOffStep({
481496
...(model ? { model } : {}),
482497
text: ordered.flatMap((block) => (block.kind === "text" ? [block.text] : [])).join(""),
483498
toolCalls: ordered.flatMap((block) => (block.kind === "tool" ? [{ id: block.id, name: block.name, ...parseArguments(block.json) }] : [])),
484499
usage,
485-
}
500+
}, stopReason === "max_tokens")
486501
}
487502

488503
export function anthropicModel(options: {
@@ -543,7 +558,7 @@ export function anthropicModel(options: {
543558
)
544559
}
545560
}
546-
return {
561+
return cutOffStep({
547562
...(reportedModel(parsed.data.model) ? { model: reportedModel(parsed.data.model) } : {}),
548563
text: continued + text.join(""),
549564
toolCalls,
@@ -555,7 +570,7 @@ export function anthropicModel(options: {
555570
cachedInputTokens: parsed.data.usage?.cache_read_input_tokens ?? 0,
556571
outputTokens: parsed.data.usage?.output_tokens ?? 0,
557572
},
558-
}
573+
}, parsed.data.stop_reason === "max_tokens")
559574
},
560575
}
561576
}
@@ -647,6 +662,7 @@ const openAIResponse = z.object({
647662
.nullable()
648663
.optional(),
649664
}),
665+
finish_reason: z.string().nullish(),
650666
}),
651667
)
652668
.min(1),
@@ -705,6 +721,7 @@ async function readOpenAIStream(
705721
const calls = new Map<number, { id: string; name: string; args: string }>()
706722
const usage: Usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 }
707723
let finished = false
724+
let cutOff = false
708725
let model: string | undefined
709726
try {
710727
for await (const raw of sseData(response, signal)) {
@@ -727,6 +744,7 @@ async function readOpenAIStream(
727744
calls.set(part.index, entry)
728745
}
729746
if (choice?.finish_reason) finished = true
747+
if (choice?.finish_reason === "length") cutOff = true
730748
if (chunk.data.usage) {
731749
usage.inputTokens = chunk.data.usage.prompt_tokens ?? 0
732750
usage.cachedInputTokens = chunk.data.usage.prompt_tokens_details?.cached_tokens ?? 0
@@ -738,14 +756,14 @@ async function readOpenAIStream(
738756
throw streamInterrupted()
739757
}
740758
if (!finished) throw streamInterrupted()
741-
return {
759+
return cutOffStep({
742760
...(model ? { model } : {}),
743761
text,
744762
toolCalls: [...calls.entries()]
745763
.sort(([left], [right]) => left - right)
746764
.map(([, call]) => ({ id: call.id, name: call.name, ...parseArguments(call.args) })),
747765
usage,
748-
}
766+
}, cutOff)
749767
}
750768

751769
export function openAIModel(options: { baseUrl: string; maxOutputTokens: number; fetch?: Fetch; sleep?: Sleep }): ModelClient {
@@ -782,7 +800,7 @@ export function openAIModel(options: { baseUrl: string; maxOutputTokens: number;
782800
const parsed = openAIResponse.safeParse(json)
783801
if (!parsed.success) throw new ModelError("model_bad_response", "Unexpected response from the AI gateway.", false)
784802
const message = parsed.data.choices[0].message
785-
return {
803+
return cutOffStep({
786804
...(reportedModel(parsed.data.model) ? { model: reportedModel(parsed.data.model) } : {}),
787805
text: message.content ?? "",
788806
toolCalls: (message.tool_calls ?? []).map((call) => ({
@@ -795,7 +813,7 @@ export function openAIModel(options: { baseUrl: string; maxOutputTokens: number;
795813
cachedInputTokens: parsed.data.usage?.prompt_tokens_details?.cached_tokens ?? 0,
796814
outputTokens: parsed.data.usage?.completion_tokens ?? 0,
797815
},
798-
}
816+
}, parsed.data.choices[0].finish_reason === "length")
799817
},
800818
}
801819
}
@@ -846,6 +864,7 @@ const responsesResult = z
846864
.object({
847865
model: z.string().nullish(),
848866
status: z.string().optional(),
867+
incomplete_details: z.object({ reason: z.string().nullish() }).loose().nullish(),
849868
output: z.array(
850869
z
851870
.object({
@@ -876,7 +895,7 @@ function responsesStep(result: z.infer<typeof responsesResult>): ModelStep {
876895
if (item.type === "message") for (const part of item.content ?? []) if (part.type === "output_text" && part.text) text += part.text
877896
if (item.type === "function_call" && item.call_id && item.name) toolCalls.push({ id: item.call_id, name: item.name, ...parseArguments(item.arguments ?? "") })
878897
}
879-
return {
898+
return cutOffStep({
880899
text,
881900
toolCalls,
882901
...(reportedModel(result.model) ? { model: reportedModel(result.model) } : {}),
@@ -885,7 +904,7 @@ function responsesStep(result: z.infer<typeof responsesResult>): ModelStep {
885904
cachedInputTokens: result.usage?.input_tokens_details?.cached_tokens ?? 0,
886905
outputTokens: result.usage?.output_tokens ?? 0,
887906
},
888-
}
907+
}, result.status === "incomplete" && result.incomplete_details?.reason === "max_output_tokens")
889908
}
890909

891910
const responsesEvent = z

0 commit comments

Comments
 (0)