Skip to content

Commit 00c3ed3

Browse files
authored
fix(headless): let model replies run to 16k tokens (#6382)
Each model reply was capped at 8,192 output tokens, a default from when the runner only answered Slack questions. Workbot now writes whole scripts and documents in one call, and those hit the cap. The default is now 16,384, the value member model access already falls back to. A reply that long takes over three minutes at today's speeds, past the 180-second call limit, so a streamed call no longer has a total time limit: it fails after 180 seconds without any data instead. That is never stricter than before. Non-streamed calls keep the 180-second total. Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 15ee52c commit 00c3ed3

4 files changed

Lines changed: 81 additions & 3 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ Nothing on celld changes, so pointing the URLs back is the rollback.
317317
| `HEADLESS_MAX_STEPS` | `0` | Model calls per turn. `0` means no limit: a long task ends with its answer, Stop, or the stuck check |
318318
| `HEADLESS_TURN_TIMEOUT_MS` | `0` | `0` means no limit. Otherwise at least `10000`, applied to each stretch between credential refreshes |
319319
| `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) |
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 |
320+
| `HEADLESS_MAX_OUTPUT_TOKENS` | `16384` | Output cap per model call: Anthropic `max_tokens`, OpenAI `max_completion_tokens`. A streamed call has no total time limit, only 180 s without any data; a non-streamed call must finish in 180 s. 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 |
321321
| `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 |
322322
| `HEADLESS_SYSTEM_PROMPT` | built-in | |
323323
| `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/model-responses.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,45 @@ test("a response stopped at the output cap is marked cut off, and the call it wa
107107
assert.equal(bare.cutOff, true)
108108
assert.deepEqual(bare.toolCalls, [])
109109
})
110+
111+
/** A Responses stream the test writes to; the runner's abort errors it, as a real fetch body does. */
112+
function liveStream() {
113+
const encoder = new TextEncoder()
114+
let controller!: ReadableStreamDefaultController<Uint8Array>
115+
const fetch = (async (_url: string | URL | Request, init?: RequestInit) => {
116+
const body = new ReadableStream<Uint8Array>({ start: (opened) => void (controller = opened) })
117+
init?.signal?.addEventListener("abort", () => controller.error(init.signal?.reason), { once: true })
118+
return new Response(body, { headers: { "content-type": "text/event-stream" } })
119+
}) as typeof globalThis.fetch
120+
return { fetch, send: (event: unknown) => controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)), end: () => controller.close() }
121+
}
122+
const settle = () => new Promise<void>((resolve) => setImmediate(resolve))
123+
124+
test("a streamed reply may take longer than the call limit while it keeps writing; a silent one is ended", async (t) => {
125+
t.mock.timers.enable({ apis: ["setTimeout"] })
126+
const writing = liveStream()
127+
const reply = openAIResponsesModel({ baseUrl: "https://gateway.test/v1", maxOutputTokens: 100, fetch: writing.fetch, sleep: async () => undefined })
128+
.complete(request({ onText: () => undefined }))
129+
await settle()
130+
// Ten minutes in all, never three minutes without a word.
131+
for (let minute = 0; minute < 4; minute += 1) {
132+
writing.send({ type: "response.output_text.delta", delta: "x" })
133+
await settle()
134+
t.mock.timers.tick(150_000)
135+
await settle()
136+
}
137+
writing.send({ type: "response.completed", response: { status: "completed", output: [{ type: "message", content: [{ type: "output_text", text: "xxxx" }] }] } })
138+
writing.end()
139+
assert.equal((await reply).text, "xxxx")
140+
141+
const silent = liveStream()
142+
const stalled = openAIResponsesModel({ baseUrl: "https://gateway.test/v1", maxOutputTokens: 100, fetch: silent.fetch, sleep: async () => undefined })
143+
.complete(request({ onText: () => undefined }))
144+
const failed = assert.rejects(stalled, (error: unknown) => error instanceof ModelError && error.code === "model_stream_interrupted")
145+
for (let attempt = 0; attempt < 3; attempt += 1) {
146+
await settle()
147+
t.mock.timers.tick(180_000)
148+
await settle()
149+
}
150+
await failed
151+
})

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ const configSchema = z.object({
5252
HEADLESS_MAX_CONCURRENT_TURNS: z.coerce.number().int().min(1).max(1_000).default(32),
5353
/** Model calls per turn; 0 means no limit, so a long task is bounded by the turn timeout and Stop instead. */
5454
HEADLESS_MAX_STEPS: z.coerce.number().int().min(0).default(0),
55-
HEADLESS_MAX_OUTPUT_TOKENS: z.coerce.number().int().min(256).max(128_000).default(8192),
55+
HEADLESS_MAX_OUTPUT_TOKENS: z.coerce.number().int().min(256).max(128_000).default(16_384),
5656
/** 0 means no limit: every model and tool call has its own timeout, so a turn cannot hang. */
5757
HEADLESS_TURN_TIMEOUT_MS: z.coerce
5858
.number()

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

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,36 @@ const defaultSleep: Sleep = (ms, signal) =>
104104

105105
const RETRYABLE_STATUS = new Set([408, 409, 425, 429, 500, 502, 503, 504, 529])
106106
const MAX_ATTEMPTS = 3
107+
/**
108+
* A model call's time limit. A non-streamed call must finish within it; a streamed one must start within it and then
109+
* never go this long without sending anything, so a long reply that keeps writing isn't cut off by the clock.
110+
*/
107111
const CALL_TIMEOUT_MS = 180_000
108112

113+
/** A timer that never keeps a Node process alive by itself (a no-op where timers are plain numbers). */
114+
function unref<T>(timer: T): T {
115+
;(timer as { unref?: () => void }).unref?.()
116+
return timer
117+
}
118+
119+
/** Hands back a streamed response whose body fails after `CALL_TIMEOUT_MS` without a chunk (through `deadline`). */
120+
function abortWhenIdle(response: Response, deadline: AbortController): Response {
121+
if (!response.body) return response
122+
const abort = () => deadline.abort(new Error("The model stream went quiet."))
123+
let idle = unref(setTimeout(abort, CALL_TIMEOUT_MS))
124+
const body = response.body.pipeThrough(
125+
new TransformStream<Uint8Array, Uint8Array>({
126+
transform(chunk, controller) {
127+
clearTimeout(idle)
128+
idle = unref(setTimeout(abort, CALL_TIMEOUT_MS))
129+
controller.enqueue(chunk)
130+
},
131+
flush: () => clearTimeout(idle),
132+
}),
133+
)
134+
return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers })
135+
}
136+
109137
function retryAfterMs(response: Response): number | undefined {
110138
const header = response.headers.get("retry-after")
111139
if (!header) return undefined
@@ -126,18 +154,26 @@ async function openResponse(input: {
126154
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
127155
if (lastError) await input.sleep(lastError.retryAfterMs ?? 1000 * 2 ** (attempt - 2), input.signal)
128156
let response: Response
157+
const deadline = new AbortController()
158+
const started = unref(setTimeout(() => deadline.abort(new Error("The model call timed out.")), CALL_TIMEOUT_MS))
129159
try {
130160
response = await input.fetch(input.url, {
131161
method: "POST",
132162
headers: { "content-type": "application/json", ...input.headers },
133163
body: JSON.stringify(input.body),
134-
signal: AbortSignal.any([input.signal, AbortSignal.timeout(CALL_TIMEOUT_MS)]),
164+
signal: AbortSignal.any([input.signal, deadline.signal]),
135165
})
136166
} catch (error) {
167+
clearTimeout(started)
137168
if (input.signal.aborted) throw error
138169
lastError = new ModelError("model_unreachable", "The AI gateway could not be reached.", true)
139170
continue
140171
}
172+
const streamed = (input.body as { stream?: unknown } | null)?.stream === true
173+
if (response.ok && streamed) {
174+
clearTimeout(started)
175+
return abortWhenIdle(response, deadline)
176+
}
141177
if (response.ok) return response
142178
const body = await response.text().catch(() => "")
143179
const requestId = response.headers.get("x-openwork-request-id") ?? response.headers.get("request-id")

0 commit comments

Comments
 (0)