Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(core): time out a request on silence, and let a retry that got somewhere start over (#571)

Yaowei Zheng88562f9c7344
diff --git a/changelog/unreleased/2026-09-01-llm-idle-timeout-and-retry-ladder.md b/changelog/unreleased/2026-09-01-llm-idle-timeout-and-retry-ladder.md
new file mode 100644
index 00000000..e1a25753
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-llm-idle-timeout-and-retry-ladder.md
@@ -0,0 +1,25 @@
+# An LLM request times out on silence, not on length
+
+- **Date:** 2026-09-01
+- **Type:** fix
+- **Scope:** `core`, `web`, `docs`
+- **PR:** [#571](https://github.com/Prism-Shadow/penguin-harness/pull/571)
+
+[中文版](2026-09-01-llm-idle-timeout-and-retry-ladder.zh.md)
+
+`model.timeoutMs` has always measured the wait for the **next** upstream event: the timer runs only while awaiting the gateway, resets on every event, and never counts consumer-side time. It was documented as "per-Request timeout", which reads as a cap on how long a response may take. The two readings agree on a model that streams as it writes. They part company on a model that keeps its reasoning off the wire — GPT-5 and Gemini send nothing at all while they think, so the whole thinking phase lands in the single gap before the first event, and 120000 quietly meant "thinking may not exceed two minutes". A request cut off there produces no usage, and the retry goes silent in exactly the same place.
+
+## Details
+
+- The wording now says what the value is: an idle budget between upstream events, bounding the connect and first-event wait and the gaps between events, not the request's total duration. Same text in the configuration table, the interface listing, and the agent settings field.
+- The default is **300000**, up from 120000. That is a kernel change (generation `2026-09-01`, runtime tab): an existing Agent whose runtime tab is still the built-in default picks the new value up on a kernel update, while one the user has edited keeps what it says.
+- Every request now asks for thought summaries (`thinking_summary`). No provider rejects the flag — the gateway maps it where the family has one and drops it where it does not — so reasoning reaches the wire wherever it can: the reader gets to watch the model think, and the idle timer keeps being reset while it does. Two families read it as something more specific: the Claude family switches its thinking stream to summarized, and some Gemini models accept `include_thoughts` and still return no summary. The raised default is what covers the ones that stay silent.
+
+## Retries count consecutive failures, not failures
+
+The reconnect ladder gave up after 5 retries within one turn, whatever happened in between. A drop like `terminated: other side closed (UND_ERR_SOCKET)` usually lands mid-response, after the model has already written part of its answer — an attempt that connected and produced content, which the old count read as one more piece of evidence that the endpoint was unreachable.
+
+- An attempt that **received content** — anything at all, a cut-off thinking block or half a tool call's arguments included — now resets the ladder: the next drop starts from the 2s rung again. `[turn_retried]` carries everything produced so far into each retry, so a turn retried this way keeps moving forward instead of repeating itself.
+- What bounds that reset is a separate absolute ceiling of **20 attempts per turn**, which only an endpoint that streams a little and drops every single time ever reaches.
+- `attempt` on `request_end` still counts every attempt and never rewinds, so the "attempt N" the Web App and the CLI print stays monotonic — and the announced `retry_in_ms` still matches the wait that actually follows, reset included.
+- The compaction loop shares the retry budget but not the reset: its budget also covers a response that was committed but unusable (an empty summary, or one that called tools), and there "produced content" is not evidence of progress at all.
diff --git a/changelog/unreleased/2026-09-01-llm-idle-timeout-and-retry-ladder.zh.md b/changelog/unreleased/2026-09-01-llm-idle-timeout-and-retry-ladder.zh.md
new file mode 100644
index 00000000..7df22e86
--- /dev/null
+++ b/changelog/unreleased/2026-09-01-llm-idle-timeout-and-retry-ladder.zh.md
@@ -0,0 +1,25 @@
+# LLM 请求超时计的是沉默,不是长度
+
+- **Date:** 2026-09-01
+- **Type:** fix
+- **Scope:** `core`, `web`, `docs`
+- **PR:** [#571](https://github.com/Prism-Shadow/penguin-harness/pull/571)
+
+[English](2026-09-01-llm-idle-timeout-and-retry-ladder.md)
+
+`model.timeoutMs` 一直计的是等待上游**下一个**事件的时长:计时只在等待网关时进行,收到任一事件即归零,消费侧的时间一概不计。而文档把它写成"单次 Request 超时",这会被读成"一次回复最多能生成多久"。在边写边吐字的模型上,两种读法没有差别;在思考不外露的模型上,两者相去甚远——GPT-5 与 Gemini 在思考期间什么都不发,整段推理因此落进首个事件之前的那一个间隔里,120000 于是悄悄变成了"思考不得超过两分钟"。在那里被切断的请求不产生任何 usage,而重试会在同一个地方再沉默一次。
+
+## 细节
+
+- 措辞改为它本来的样子:上游事件之间的空闲预算,约束的是连接建立与首个事件的等待、以及流式过程中的事件间隔,不是整次请求的总时长。配置表、接口清单与 Agent 设置里的字段说明同步。
+- 缺省值由 120000 提到 **300000**。这是一次内核变更(generation `2026-09-01`,runtime 标签页):运行时标签页仍是内置缺省的 Agent 会在内核更新时取到新值,用户改过的则保留自己的取值。
+- 每次请求现在都索取思考摘要(`thinking_summary`)。没有 Provider 会因这个字段报错——网关在有对应能力的家族上映射它,在没有的家族上丢弃它——于是凡是能外露推理的模型都会把推理发到线上:读者看得见模型在想什么,空闲计时也在这段时间里不断归零。有两个家族对它的理解更具体:Claude 系会把思考流切为摘要,而部分 Gemini 型号接受 `include_thoughts` 却仍然不返回摘要。仍会沉默的那些,正是提高缺省值所覆盖的。
+
+## 重试计的是连续失败,而不是失败
+
+重连阶梯此前在同一轮里重试 5 次就放弃,中间发生过什么都不算数。而 `terminated: other side closed (UND_ERR_SOCKET)` 这类断开通常发生在响应中途,此时模型已经写出了一部分答案——那是一次已经连上、并且产出过内容的尝试,旧的计数却把它读成"端点不通"的又一个证据。
+
+- **收到过内容**的尝试——任何内容都算,哪怕只是一段被切断的思考、或半个工具调用的参数——现在会把阶梯归零:下一次断开重新从 2s 那一级开始。`[turn_retried]` 会把此前已产出的内容一路带进每次重试,因此这样重试的一轮是在往前推进,而不是原地重复。
+- 为归零兜底的是另一条绝对上限:**单轮总尝试 20 次**,只有"每次吐几个字就断"的端点才够得着它。
+- `request_end` 上的 `attempt` 仍然计所有尝试、从不回退,Web 与 CLI 打印的"第 N 次"因此保持单调;宣告的 `retry_in_ms` 也仍与随后真正的等待一致,含归零之后的那一次。
+- 压缩循环共用这份重试预算,但不适用归零规则:它的预算同时覆盖"已提交但不可用的响应"(空摘要,或调用了工具的响应),在那里"产出过内容"根本不是进展的证据。
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index 977d18fb..3077c215 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -187,6 +187,14 @@ export interface ContextEngineDeps {
* recovery window instead of five retries burning out in about a second (issue #218).
*/
maxReconnects?: number;
+ /**
+ * Absolute ceiling on the attempts a single turn may make, counting every attempt whether
+ * or not it received anything. Defaults to 20. It only binds once received content has
+ * reset the consecutive ladder (`maxReconnects`) at least once, and exists solely to keep
+ * that reset from turning an endpoint that streams a few tokens and drops into an endless
+ * retry loop.
+ */
+ maxTurnAttempts?: number;
/**
* Exponential backoff base (ms): the wait before reconnect retry N is
* `base × 2^(N−1)`, capped at `reconnectBackoffMaxMs` (see reconnectDelayMs).
@@ -320,10 +328,31 @@ interface TurnResult {
toolCalls: OmniMessage<ToolCallPayload>[];
/** Complete thinking/text segments produced by the model this turn (including partial segments finalized on interruption), for carry-over flattening. */
assistantSegments: OmniMessage[];
+ /**
+ * Whether this attempt received anything at all from the LLM stream. It is what the
+ * reconnect loop resets its ladder on: one message is proof the connection was established
+ * and the model was producing. Deliberately wider than the collected arrays — a drop
+ * mid-tool-call synthesizes a tool_call that is never dispatched and so never reaches
+ * `toolCalls`, yet those bytes did arrive.
+ */
+ receivedContent: boolean;
/** Terminal state of this turn's LLM request (completed / failed / aborted / timeout / malformed). */
outcome: LLMOutcome;
}
+/**
+ * A turn's retry bookkeeping, threaded into `runTurn` so its `request_end` can announce the
+ * next attempt's planned backoff. `attempts` counts every attempt the turn has made so far
+ * (the ordinal hosts render, and what the absolute ceiling measures); `consecutive` counts
+ * only the tail of them that came back having received nothing — the backoff rung, and what
+ * `maxReconnects` measures. The two diverge as soon as an attempt receives content: see the
+ * reconnect loop in runToCompletion.
+ */
+interface TurnRetryState {
+ attempts: number;
+ consecutive: number;
+}
+
/**
* Merge queue: lets multiple concurrent producers (the LLM stream consumer + several tool
* executions) push OmniMessage entries; a single consumer (run's generator) pulls and
@@ -422,6 +451,12 @@ function downgradeCarriedGoalInput(msg: OmniMessage): OmniMessage {
* set explicitly (issue #170 — a compaction request is an ordinary LLM request and gets the
* turn loop's patience; compaction additionally routes a committed-but-unusable summary
* through the same budget, see summarizeContext).
+ *
+ * One rule is the turn loop's alone: received content resets its ladder. Compaction cannot
+ * borrow it precisely because of that extra class — its budget also covers responses that
+ * were committed but unusable (an empty summary, or tool calls), where "produced content" is
+ * not evidence of progress at all, and resetting on it would turn issue #83's guard into a
+ * loop that re-asks a model already answering wrong, at maximum context, forever.
*/
const RETRY_STATUSES: readonly StopReason[] = ["retryable"];
@@ -443,6 +478,7 @@ export function reconnectDelayMs(base: number, max: number, attempt: number): nu
export class ContextEngine {
private readonly maxTurns: number;
private readonly maxReconnects: number;
+ private readonly maxTurnAttempts: number;
private readonly reconnectBackoffMs: number;
private readonly reconnectBackoffMaxMs: number;
private readonly compactionMaxReconnects: number;
@@ -513,6 +549,7 @@ export class ContextEngine {
this.pendingBootstrapRecords = deps.bootstrapRecords ?? null;
this.maxTurns = deps.maxTurns ?? -1;
this.maxReconnects = deps.maxReconnects ?? 5;
+ this.maxTurnAttempts = deps.maxTurnAttempts ?? 20;
this.reconnectBackoffMs = deps.reconnectBackoffMs ?? 2000;
this.reconnectBackoffMaxMs = deps.reconnectBackoffMaxMs ?? 30_000;
this.compactionMaxReconnects = deps.compactionMaxReconnects ?? this.maxReconnects;
@@ -741,7 +778,11 @@ export class ContextEngine {
// GenerativeModel precisely so it never reaches this loop.)
const failedTurns: TurnResult[] = [];
let attemptInput = nextInput;
- let reconnects = 0;
+ // Two counters, because the ladder and the ceiling answer different questions (see
+ // TurnRetryState): `attempts` is every attempt this turn has made, `consecutive` only
+ // the tail that received nothing. Both live and die with the turn.
+ let attempts = 0;
+ let consecutive = 0;
let turn: TurnResult;
for (;;) {
@@ -750,7 +791,11 @@ export class ContextEngine {
// it decides retry/resend purely from `outcome`. The retry count so far is threaded
// in so the turn's request_end can announce the planned backoff (retry_in_ms) —
// the counter lives in this loop while the event is built inside the turn.
- turn = yield* this.runTurn(attemptInput, approve, signal, thinkingLevel, reconnects);
+ turn = yield* this.runTurn(attemptInput, approve, signal, thinkingLevel, {
+ attempts,
+ consecutive,
+ });
+ attempts += 1;
// User interruption (the LLM stream was aborted, outcome=aborted, or `signal` fired
// during tool execution): stop and hand control back to the user.
@@ -790,11 +835,20 @@ export class ContextEngine {
// request_end(retryable) followed by the next request_begin.
failedTurns.push(turn);
attemptInput = this.withRetriedTurns(nextInput, failedTurns);
+ // Received content resets the ladder. An attempt the stream sent anything to had a
+ // working connection and a model writing into it, so its drop is a fresh transport
+ // fault — not the n-th piece of evidence that this endpoint is unreachable. A socket
+ // that dies twice in one turn shouldn't add up to a reason to stop while
+ // `[turn_retried]` carries the accumulated output into every retry and the turn keeps
+ // inching forward. What bounds this is the ceiling below, not the ladder: an endpoint
+ // that streams a few tokens and drops, every single time, would otherwise be retried
+ // forever.
+ if (turn.receivedContent) consecutive = 0;
// Exhausted: give up without an abort event — abort marks a user interruption,
// and the last failure's request_end (status `retryable` with no `retry_in_ms`,
// since no retry is planned) is the terminal record frontends and observability
// read; `attempt` and `error_message` ride on it.
- if (reconnects >= this.maxReconnects) {
+ if (consecutive >= this.maxReconnects || attempts >= this.maxTurnAttempts) {
this.pendingCarryOver = attemptInput;
return {
kind: "llm_failure",
@@ -804,8 +858,8 @@ export class ContextEngine {
: {}),
};
}
- reconnects += 1;
- if (!(await this.backoff(reconnects, signal))) {
+ consecutive += 1;
+ if (!(await this.backoff(consecutive, signal))) {
this.pendingCarryOver = attemptInput;
yield* this.emitAbort("backoff_interrupted");
return { kind: "abort", errorCode: "backoff_interrupted" };
@@ -1088,8 +1142,8 @@ export class ContextEngine {
approve: ApproveFn,
signal?: AbortSignal,
thinkingLevel?: ThinkingLevelName,
- /** Retries already performed for this turn (from the caller's reconnect loop): lets request_end announce the NEXT attempt's planned backoff. */
- reconnectsSoFar = 0,
+ /** This turn's retry bookkeeping from the caller's reconnect loop: lets request_end announce the NEXT attempt's planned backoff (and announce none once a budget is spent). */
+ retry: TurnRetryState = { attempts: 0, consecutive: 0 },
): AsyncGenerator<OmniMessage, TurnResult> {
const queue = new MergeQueue();
// Tool outputs are collected in **completion order** (for streaming yield to the frontend);
@@ -1103,6 +1157,8 @@ export class ContextEngine {
const assistantSegments: OmniMessage[] = [];
// This turn's LLM terminal state: taken from streamGenerate's generator return value.
let outcome: LLMOutcome = { status: "completed" };
+ // Set by the first message the stream yields (see TurnResult.receivedContent).
+ let receivedContent = false;
// Driver task: consumes the LLM stream + approves one at a time + dispatches tool
// execution. It is itself a producer.
@@ -1131,19 +1187,28 @@ export class ContextEngine {
// (the errors panel) can learn the real reason (e.g. a quota code). When the
// engine will retry in-run, the planned backoff rides along as retry_in_ms
// (the frontend's live countdown); absent on final failures and completions.
- const retryInMs = this.plannedRetryDelayMs(
- outcome,
- reconnectsSoFar,
- this.maxReconnects,
- RETRY_STATUSES,
- );
+ // Mirrors the reconnect loop exactly, or the announced countdown is a lie: an
+ // attempt that received content restarts the ladder at its first rung, and either
+ // budget running out means no retry is planned at all.
+ const retryInMs =
+ retry.attempts + 1 >= this.maxTurnAttempts
+ ? undefined
+ : this.plannedRetryDelayMs(
+ outcome,
+ receivedContent ? 0 : retry.consecutive,
+ this.maxReconnects,
+ RETRY_STATUSES,
+ );
const stopEvt = requestEnd(outcome.status, {
...(outcome.errorCode !== undefined ? { errorCode: outcome.errorCode } : {}),
...(outcome.errorMessage !== undefined ? { errorMessage: outcome.errorMessage } : {}),
- // The authoritative attempt ordinal (1-based, within this retry run); a clean
- // first-try completion stays unstamped so the common case adds no noise.
- ...(outcome.status !== "completed" || reconnectsSoFar > 0
- ? { attempt: reconnectsSoFar + 1 }
+ // The authoritative attempt ordinal (1-based, within this retry run): the
+ // turn's TOTAL attempt count, which never rewinds when received content resets
+ // the backoff ladder — hosts render "attempt N", and a counter that went
+ // backwards mid-turn would read as a lost attempt. A clean first-try completion
+ // stays unstamped so the common case adds no noise.
+ ...(outcome.status !== "completed" || retry.attempts > 0
+ ? { attempt: retry.attempts + 1 }
: {}),
...(retryInMs !== undefined ? { retryInMs } : {}),
});
@@ -1152,6 +1217,7 @@ export class ContextEngine {
break;
}
const msg = res.value;
+ receivedContent = true;
queue.push(msg);
await this.write(msg);
// token_usage means "this Request completed normally": record the context usage /
@@ -1259,7 +1325,7 @@ export class ContextEngine {
const out = byId.get(id);
if (out) orderedOutputs.push(out);
}
- return { toolOutputs: orderedOutputs, toolCalls, assistantSegments, outcome };
+ return { toolOutputs: orderedOutputs, toolCalls, assistantSegments, receivedContent, outcome };
}
/**
diff --git a/packages/core/src/interfaces/llm.ts b/packages/core/src/interfaces/llm.ts
index 3829c452..2e82a9c3 100644
--- a/packages/core/src/interfaces/llm.ts
+++ b/packages/core/src/interfaces/llm.ts
@@ -55,7 +55,15 @@ export interface GenerativeModelConfig {
fastMode?: boolean;
/** Construction-time default thinking level; a per-request `GenerativeModelParameters.thinkingLevel` overrides it for that request. */
thinkingLevel?: ThinkingLevelName;
- /** LLM Request timeout (ms): from system_config.model.timeoutMs; <=0 disables it. Defaults to 120000. */
+ /**
+ * Idle budget (ms) for an LLM Request: the longest wait for the NEXT upstream event, not a
+ * cap on the request's total duration — the timer runs only while awaiting upstream, resets
+ * on every event, and excludes consumer-side time (yielding, approvals, Trace writes). It
+ * therefore bounds the connect + first-event wait and the gaps between events, never how
+ * long the model generates. From system_config.model.timeoutMs; <=0 disables it. Defaults
+ * to 300000: a model whose reasoning never reaches the wire spends its whole thinking phase
+ * inside the first-event gap.
+ */
requestTimeoutMs?: number;
/**
* tool_call_id uniqueness registry (Session-level). Pass the same instance when rebuilding a new
diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.ts
index 4bc9d80c..881380fd 100644
--- a/packages/core/src/llm/generative-model.ts
+++ b/packages/core/src/llm/generative-model.ts
@@ -996,7 +996,7 @@ export class GenerativeModel implements LLMInterface {
this.uniConfig = buildUniConfig(config);
this.defaultThinkingLevel = config.thinkingLevel;
- this.requestTimeoutMs = config.requestTimeoutMs ?? 120000;
+ this.requestTimeoutMs = config.requestTimeoutMs ?? 300000;
this.toolCallIds = config.toolCallIds ?? new ToolCallIdAllocator();
this.configuredMaxTokens = config.maxTokens;
this.contextWindow = resolveContextWindow(config.contextWindow);
@@ -1416,5 +1416,12 @@ export function buildUniConfig(config: GenerativeModelConfig): UniConfig {
if (config.fastMode === true) {
uniConfig.fast_mode = true;
}
+ // Thought summaries, always requested. Two things ride on it: the user gets to watch the
+ // model reason, and — because the request timeout is an idle budget between upstream events
+ // — a reasoning phase that reaches the wire keeps resetting that timer instead of counting
+ // as one long silence. No model rejects the flag (unlike fast_mode): AgentHub maps it where
+ // it exists and drops it where it doesn't, so the only cost of asking is on families that
+ // answer with a summarized thinking stream (Claude) instead of the raw one.
+ uniConfig.thinking_summary = true;
return uniConfig;
}
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 8f51eb21..c1d628e4 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -948,7 +948,13 @@ export function defaultSystemConfig(): SystemConfig {
model: {
max_tokens: 32000,
thinking_level: "medium",
- timeoutMs: 120000,
+ // Idle budget between two upstream events, not a cap on how long a response may take
+ // (see GenerativeModelConfig.requestTimeoutMs). It has to cover the wait for the FIRST
+ // event, which is where a model that keeps its reasoning off the wire spends its whole
+ // thinking phase: requests ask for thought summaries so most models stream something,
+ // but the ones that accept the flag and return nothing still go silent, and 120s used
+ // to cut them off mid-thought.
+ timeoutMs: 300000,
},
compaction: {
max_context_length: DEFAULT_MAX_CONTEXT_LENGTH,
diff --git a/packages/core/src/state/kernel-history.ts b/packages/core/src/state/kernel-history.ts
index 52a297d6..3188e5c7 100644
--- a/packages/core/src/state/kernel-history.ts
+++ b/packages/core/src/state/kernel-history.ts
@@ -22,7 +22,7 @@ import { createHash } from "node:crypto";
* change without it moving. (The reverse — moving it with no default change — is inert rather
* than an error: nothing is keyed by version, so there is no table to fall out of sync with.)
*/
-export const KERNEL_VERSION = "2026-08-26";
+export const KERNEL_VERSION = "2026-09-01";
function isPlainObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -179,16 +179,20 @@ export function isKernelOutdated(kernelVersion: string | null | undefined): bool
* `kill` parameter, `kill_subagent` was removed outright (a subagent session is never
* destroyed — `input_subagent` resumes a released id), and `input_subagent` gained `abort`
* and now returns the subagent's latest reply: the tools tab moved.
- * - `2026-08-26` (current) — the schedules prompt's default target became the Session the
+ * - `2026-08-26` — the schedules prompt's default target became the Session the
* model is already in (`session_id` taken from the Environment section) instead of a fresh
* Session per trigger, alongside the hygiene line that bounds a self-directed recurring task
* and the carve-outs from the new default (an open-ended reminder keeps no `end_at`, work
* that must outlive the conversation takes the new-Session form, and a subagent omits the
* field): the schedules tab moved.
+ * - `2026-09-01` (current) — `model.timeoutMs` rose to 300000: the value is the idle budget
+ * between upstream events, and a model that keeps its reasoning off the wire spends its
+ * whole thinking phase inside the wait for the first one, which 120000 cut short. The
+ * runtime tab moved.
*/
export const KERNEL_DEFAULT_TAB_HASHES: Readonly<Record<KernelTab, string>> = {
prompt: "048198c37b8d7840352c225fdfcb15baf2679973c6eab4bf400d492daf6ce254",
- runtime: "c952d44ecdd6790e17f02bc1b5056118b56ec7f0987dc2cbe950f6051fddbd20",
+ runtime: "5dfea06a5e801950c24f44f5527e62435ae4facc311a6587e53aa69983ab0346",
tools: "c24bcf47b1377e9da4dcfb69a1f7240dcdbfff2d420df5db0a5eaec2b7d4087d",
skills: "7e343aa692e5eaeadfc8add6bb375fb50ac33ef81ebe460490fc219b0f3d707f",
memory: "53d190390829cc0132bb12e468a6891f2e0576ec0c4022a9b4a5d9233666900d",
@@ -212,8 +216,10 @@ export type KernelSupersededTabHashes = Readonly<Partial<Record<KernelTab, reado
export const KERNEL_SUPERSEDED_TAB_HASHES: KernelSupersededTabHashes = {
// The pre-toggles template, with the hardcoded # Vault / # Skills sections (before #257).
prompt: ["99b8babb72d95c636a2c2893b657ac9c92d60c270a2e04e346b35b1fb720c932"],
- // compaction.max_context_length was 128000, before the rise to 256000 in 2026-08-20.
- runtime: ["808ae1d1b544f46daff4f59f1e62357b89a61f60803061e86b10635616e0102c"],
+ runtime: [
+ "808ae1d1b544f46daff4f59f1e62357b89a61f60803061e86b10635616e0102c", // compaction.max_context_length was 128000, before the rise to 256000
+ "c952d44ecdd6790e17f02bc1b5056118b56ec7f0987dc2cbe950f6051fddbd20", // model.timeoutMs was 120000, before the rise to 300000
+ ],
tools: [
"238440586ad2e075bde04948cf8dc9876301da538aafeb8926cd9c6a5738081b", // before run_subagent's `thinking_level` (#306)
"c719f2fe8a25bc5c644a4e1a78d26cf960dd0561efc453614af2e395000ed4de", // before `max` joined the ladder
diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.ts
index 118cd988..6dbc43c7 100644
--- a/packages/core/test/engine.test.ts
+++ b/packages/core/test/engine.test.ts
@@ -1819,15 +1819,18 @@ describe("ContextEngine LLM timeout / network interruption (PRN-012)", () => {
workspaceDir: workspace,
toolConfig: execCommandToolConfig(),
});
+ // Every attempt streams text before failing, so the consecutive ladder resets on each of
+ // them: the absolute per-turn ceiling is what ends this run.
const engine = new ContextEngine({
llm,
environment,
maxReconnects: 1,
+ maxTurnAttempts: 2,
reconnectBackoffMs: 0,
});
const all = await collectRun(engine, [userText("go")], allowAll);
- expect(calls).toBe(2); // Initial attempt + maxReconnects(1) retries.
+ expect(calls).toBe(2); // Initial attempt + one retry, then the ceiling.
// No abort event — abort marks a user interruption; the last failure's request_end
// (retryable, no retry_in_ms since no retry is planned) is the terminal record.
expect(all.some((m) => (m.payload as { type?: string }).type === "abort")).toBe(false);
@@ -2122,6 +2125,82 @@ describe("ContextEngine LLM timeout / network interruption (PRN-012)", () => {
expect(last.retry_in_ms).toBeUndefined();
});
+ it("received content restarts the ladder; a fruitless tail is what runs the budget out", async () => {
+ // Attempts 1-2 stream text before dropping — the shape of a socket that dies mid-response
+ // (UND_ERR_SOCKET). Each of them proves the connection worked and the model was writing,
+ // so the consecutive budget goes back to zero and the next wait is the base again. Only
+ // the two attempts that come back with nothing accumulate, and those are what exhausts
+ // maxReconnects: four attempts, of which two counted.
+ let calls = 0;
+ const llm: LLMInterface = {
+ async *streamGenerate() {
+ calls += 1;
+ if (calls <= 2) yield assistantText("partial...", "retryable");
+ return { status: "retryable" };
+ },
+ };
+ const environment = new Environment({
+ workspaceDir: workspace,
+ toolConfig: execCommandToolConfig(),
+ });
+ const engine = new ContextEngine({
+ llm,
+ environment,
+ maxReconnects: 2,
+ reconnectBackoffMs: 10,
+ reconnectBackoffMaxMs: 15,
+ });
+
+ const all = await collectRun(engine, [userText("go")], allowAll);
+ expect(calls).toBe(4);
+ const ends = all.filter((m) => (m.payload as { type?: string }).type === "request_end") as {
+ payload: { attempt?: number; retry_in_ms?: number };
+ }[];
+ // The announced waits show the reset: base, base again (the ladder restarted after each
+ // productive attempt), then the climb over the fruitless tail, then none.
+ expect(ends.map((e) => e.payload.retry_in_ms)).toEqual([10, 10, 15, undefined]);
+ // The ordinal counts every attempt and never rewinds when the ladder does — a counter
+ // that went backwards mid-turn would read as a lost attempt.
+ expect(ends.map((e) => e.payload.attempt)).toEqual([1, 2, 3, 4]);
+ expect(all.some((m) => (m.payload as { type?: string }).type === "abort")).toBe(false);
+ });
+
+ it("the absolute ceiling stops an endpoint that streams a little and drops every time", async () => {
+ // Every attempt produces content, so the consecutive ladder resets every time and would
+ // never run out; maxTurnAttempts is the only thing between this turn and an unbounded
+ // retry loop that pays for the whole context on each pass.
+ let calls = 0;
+ const llm: LLMInterface = {
+ async *streamGenerate() {
+ calls += 1;
+ yield assistantText("partial...", "retryable");
+ return { status: "retryable" };
+ },
+ };
+ const environment = new Environment({
+ workspaceDir: workspace,
+ toolConfig: execCommandToolConfig(),
+ });
+ const engine = new ContextEngine({
+ llm,
+ environment,
+ maxReconnects: 2,
+ maxTurnAttempts: 4,
+ reconnectBackoffMs: 1,
+ });
+
+ const all = await collectRun(engine, [userText("go")], allowAll);
+ expect(calls).toBe(4);
+ const ends = all.filter((m) => (m.payload as { type?: string }).type === "request_end") as {
+ payload: { attempt?: number; retry_in_ms?: number };
+ }[];
+ // The ladder stays on its first rung throughout (each attempt resets it): the count, not
+ // the backoff, is what ends the run.
+ expect(ends.map((e) => e.payload.retry_in_ms)).toEqual([1, 1, 1, undefined]);
+ expect(ends.map((e) => e.payload.attempt)).toEqual([1, 2, 3, 4]);
+ expect(all.some((m) => (m.payload as { type?: string }).type === "abort")).toBe(false);
+ });
+
it("skipReconnectWait wakes the backoff early ('retry now'): attempt numbering unchanged; no-op without a wait", async () => {
let calls = 0;
const llm: LLMInterface = {
@@ -2414,12 +2493,14 @@ describe("ContextEngine LLM timeout / network interruption (PRN-012)", () => {
workspaceDir: workspace,
toolConfig: execCommandToolConfig(),
});
- // maxReconnects=1 -> exhausted after attempt 2; the original input is stashed as carry-over
- // for the next run.
+ // Both failed attempts produce content (a tool call, then thinking), which resets the
+ // consecutive ladder; maxTurnAttempts=2 is therefore the budget that runs out after
+ // attempt 2, stashing the original input as carry-over for the next run.
const engine = new ContextEngine({
llm,
environment,
maxReconnects: 1,
+ maxTurnAttempts: 2,
reconnectBackoffMs: 0,
});
diff --git a/packages/core/test/llm.test.ts b/packages/core/test/llm.test.ts
index d1b0bfe5..c1d1734c 100644
--- a/packages/core/test/llm.test.ts
+++ b/packages/core/test/llm.test.ts
@@ -1137,6 +1137,20 @@ describe("config helpers", () => {
expect("max_tokens" in uncapped).toBe(false);
});
+ it("defaults the request idle budget to 300s (a silent reasoning phase fits inside it)", () => {
+ // The budget is the wait for the NEXT upstream event, and a model that keeps its
+ // reasoning off the wire spends its whole thinking phase inside the first-event gap.
+ const model = new GenerativeModel({ modelId: "claude-sonnet-4-6", tools: [] });
+ expect((model as unknown as { requestTimeoutMs: number }).requestTimeoutMs).toBe(300000);
+ // An explicit value still wins, and <=0 still disables the timer.
+ const explicit = new GenerativeModel({
+ modelId: "claude-sonnet-4-6",
+ tools: [],
+ requestTimeoutMs: 5000,
+ });
+ expect((explicit as unknown as { requestTimeoutMs: number }).requestTimeoutMs).toBe(5000);
+ });
+
it("omits tools when empty and never sets tool_choice (strict endpoints reject both)", () => {
// Empty tool list (connectivity probe, bare/meta LLM, vision describer): the `tools` key
// must be absent, not `[]` — AgentHub forwards any defined array verbatim, and strict
@@ -1161,6 +1175,17 @@ describe("config helpers", () => {
const unset = buildUniConfig({ modelId: "m", tools: [] });
expect("fast_mode" in unset).toBe(false);
});
+
+ it("always asks for thought summaries (they keep a reasoning phase on the wire)", () => {
+ // Unconditional, unlike fast_mode: no client rejects the flag — AgentHub maps it where the
+ // provider has one and drops it where it doesn't. Beyond showing the user the reasoning,
+ // it keeps events arriving while the model thinks, which is what the request timeout (an
+ // idle budget between upstream events) actually measures.
+ expect(buildUniConfig({ modelId: "m", tools: [] }).thinking_summary).toBe(true);
+ expect(
+ buildUniConfig({ modelId: "m", tools: [], thinkingLevel: "none" }).thinking_summary,
+ ).toBe(true);
+ });
});
describe("isFatalProviderRejection (the fatal allowlist; everything it misses stays retryable)", () => {
diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.ts
index 4f797429..58ddc484 100644
--- a/packages/core/test/state.test.ts
+++ b/packages/core/test/state.test.ts
@@ -217,7 +217,7 @@ describe("loadOrInitAgentState", () => {
expect(tpl.indexOf(SCHEDULES_PLACEHOLDER)).toBeLessThan(tpl.indexOf("# Environment"));
expect(state.systemConfig.model?.max_tokens).toBe(32000);
expect(state.systemConfig.model?.thinking_level).toBe("medium");
- expect(state.systemConfig.model?.timeoutMs).toBe(120000);
+ expect(state.systemConfig.model?.timeoutMs).toBe(300000);
expect(state.systemConfig.tools?.mcpServers).toEqual([]);
expect(Object.hasOwn(state.systemConfig, "description")).toBe(false);
expect(Object.hasOwn(state.systemConfig, "subagents")).toBe(false);
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index db9cc122..5b71001a 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -26,7 +26,7 @@ session.run(newMessages, { approve, signal })
│ │ output streams back │
│ └─ LLMOutcome: │
│ failed/timeout/malformed ──► reconnect within the turn │
-│ (≤5, with [turn_retried]; tools not rerun) │
+│ (≤5 fruitless, with [turn_retried]; tools not rerun) │
│ token_usage + request_end (at LLM-stream end; not waiting │
│ for tools) │
│ │
@@ -103,7 +103,7 @@ Goal mode is the exception because its objective is re-injected as text every ro
## Automatic reconnect
-Every LLM-side failure except `auth` triggers an in-run reconnect — `timeout` (transport-shaped errors: network timeouts, transport disconnects, rate limits, 5xx), `malformed` (truncated streams, JSON parse failures), and **`failed` as well** — every provider rejection that isn't an explicit credential failure, bare 403s and quota/subscription errors included. The statuses are taxonomy, not policy: the classifier only picks the label, and a gateway phrasing a transient fault its own way (`Upstream HTTP/2 stream failed`, say) or a quota that refills mid-ladder retries exactly like a network drop. Retrying a genuinely permanent error costs the ladder and ends the same way; aborting a transient one destroys the turn. Note this changes the *policy*, not the *taxonomy*: a `failed` request is still recorded as `failed` on its `request_end` and in the Cost center, rather than being relabelled a timeout. On a reconnect the engine re-sends the original input plus a `[turn_retried]` block carrying the previous partial output, so tools are never re-executed. Default limit is 5 reconnects with exponential backoff under a ceiling (base 2s, cap 30s: 2s, 4s, 8s, 16s, 30s ≈ 60s of total patience — one shared schedule for every retryable class, sized so transient provider failures such as restarts and rate limits get a real recovery window instead of five retries burning out in about a second, and so every planned wait clears the Web App's 2s countdown floor and stays visible); beyond that the turn settles as `failed`. Each failure's `request_end` announces the planned wait as `retry_in_ms` (same formula as the sleep) and stamps `attempt`, the authoritative 1-based ordinal of the request within its retry run (the CLI and Web App display it verbatim); the Web App renders the wait as a live countdown with "retry now" (skips the remaining wait via `Session.skipReconnectWait` — the attempt counter is unchanged) and "give up" (the ordinary abort; the engine's abort-during-backoff path ends the turn) controls; the CLI prints its own `[retry]` line. All three retryable statuses render identically — a retry the user cannot see is a stalled session with no explanation and no way out. A compaction request is an ordinary LLM request and by default retries on the same cap and ladder (an unusable summary draws on the same budget — see "Context compaction"); a compaction that gives up keeps the original context and tries again at the next trigger. Authentication errors are classified before any retry heuristic and never retry: the request ends with its own terminal status `auth` (only the model reference is fixed at Session creation — credentials are read from the current Project config when the Session loads), and the Web App disables that Session's composer until the model's credential is updated (which auto-unlocks it) or the notice is dismissed for a retry. Tool errors are never retried — they are fed back to the model as `tool_call_output` and the model decides what to do next.
+Every LLM-side failure except `auth` triggers an in-run reconnect — `timeout` (transport-shaped errors: network timeouts, transport disconnects, rate limits, 5xx), `malformed` (truncated streams, JSON parse failures), and **`failed` as well** — every provider rejection that isn't an explicit credential failure, bare 403s and quota/subscription errors included. The statuses are taxonomy, not policy: the classifier only picks the label, and a gateway phrasing a transient fault its own way (`Upstream HTTP/2 stream failed`, say) or a quota that refills mid-ladder retries exactly like a network drop. Retrying a genuinely permanent error costs the ladder and ends the same way; aborting a transient one destroys the turn. Note this changes the *policy*, not the *taxonomy*: a `failed` request is still recorded as `failed` on its `request_end` and in the Cost center, rather than being relabelled a timeout. On a reconnect the engine re-sends the original input plus a `[turn_retried]` block carrying the previous partial output, so tools are never re-executed. Default limit is 5 **consecutive fruitless** reconnects with exponential backoff under a ceiling (base 2s, cap 30s: 2s, 4s, 8s, 16s, 30s ≈ 60s of total patience — one shared schedule for every retryable class, sized so transient provider failures such as restarts and rate limits get a real recovery window instead of five retries burning out in about a second, and so every planned wait clears the Web App's 2s countdown floor and stays visible); beyond that the turn settles as `failed`. An attempt that **received content** before dropping (a `terminated: other side closed (UND_ERR_SOCKET)` mid-response, say) had a working connection and a model writing into it, so its failure restarts the ladder at 2s instead of climbing it — two socket drops in one turn shouldn't add up to a reason to give up while `[turn_retried]` carries the accumulated output into every retry. The bound on that reset is a separate absolute ceiling of 20 attempts per turn, which only an endpoint that streams a little and drops every time ever reaches. `attempt` keeps counting every attempt and never rewinds when the ladder resets. Each failure's `request_end` announces the planned wait as `retry_in_ms` (same formula as the sleep) and stamps `attempt`, the authoritative 1-based ordinal of the request within its retry run (the CLI and Web App display it verbatim); the Web App renders the wait as a live countdown with "retry now" (skips the remaining wait via `Session.skipReconnectWait` — the attempt counter is unchanged) and "give up" (the ordinary abort; the engine's abort-during-backoff path ends the turn) controls; the CLI prints its own `[retry]` line. All three retryable statuses render identically — a retry the user cannot see is a stalled session with no explanation and no way out. A compaction request is an ordinary LLM request and by default retries on the same cap and ladder (an unusable summary draws on the same budget — see "Context compaction"); a compaction that gives up keeps the original context and tries again at the next trigger. Authentication errors are classified before any retry heuristic and never retry: the request ends with its own terminal status `auth` (only the model reference is fixed at Session creation — credentials are read from the current Project config when the Session loads), and the Web App disables that Session's composer until the model's credential is updated (which auto-unlocks it) or the notice is dismissed for a retry. Tool errors are never retried — they are fed back to the model as `tool_call_output` and the model decides what to do next.
## Compaction
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index 4ebdd717..b89f423b 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -24,7 +24,7 @@ session.run(newMessages, { approve, signal })
│ │ ▼ │
│ │ Environment.executeTool ──► 并发执行,输出流式回传 │
│ └─ LLMOutcome: │
-│ failed/timeout/malformed ──► 同轮自动重连(≤5 次, │
+│ failed/timeout/malformed ──► 同轮自动重连(≤5 次连续无进展, │
│ 附 [turn_retried],工具不重跑) │
│ token_usage + request_end(LLM 流结束即产出,不等工具) │
│ │
@@ -100,7 +100,7 @@ Task 运行期间,宿主可通过 `session.steer(input)` 排队一条用户消
## 自动重连
-除 `auth` 外,LLM 侧的所有失败都会触发引擎内自动重连——`timeout`(传输形态的错误:网络超时、传输层断连、限流、5xx)、`malformed`(流截断、JSON 解析失败),**以及 `failed`**——凡不是明确凭据错误的供应商拒绝都在此列,普通 403 与配额/订阅错误也一样重试。终态只是分类而非策略:分类器只挑标签,用自己说法描述瞬时故障的网关(例如 `Upstream HTTP/2 stream failed`)或阶梯中途恢复的配额,都与断网一样走满同一阶梯。重试一个真正的永久错误,代价是走完退避梯度后以同样的方式收场;而把瞬时错误直接中断,则毁掉这一轮。注意改的是**策略**而非**分类**:`failed` 请求在 `request_end` 与成本中心里仍然记为 `failed`,不会被改标成超时。重连时同一次 `run` 内重发原始输入,并附加 `[turn_retried]` 块携带上一次的部分输出,避免工具重复执行。默认最多重连 5 次,指数退避并设上限(基数 2s、上限 30s:2s、4s、8s、16s、30s,总耐心约 60s——所有可重试类别共用一张时间表,按较慢的类别定基数:供应商重启、限流这类瞬时故障需要以秒计的恢复时间,旧的 250ms 基数约 7.75s 就烧完整个阶梯;每次计划等待也都达到 Web App 2s 的倒计时下限,重试始终可见);超限后该轮以 `failed` 收场。每次失败的 `request_end` 会以 `retry_in_ms` 宣告计划中的等待(与实际休眠同一公式)、以 `attempt` 标注这是本轮第几次尝试(权威序号,CLI 与 Web 的重试行直接显示它),Web App 据此实时倒计时,并提供「立即重试」(经 `Session.skipReconnectWait` 跳过剩余等待——重试计数不变)与「放弃」(普通中断;引擎的退避中中断路径结束本轮)两个内联按钮,CLI 则打印自己的 `[重试]` 行。三种可重试终态的渲染完全一致——用户看不见的重试,等于一次没有任何解释、也无从退出的卡顿。压缩请求是一次普通的 LLM 请求,默认沿用同一重连上限与退避阶梯(无效摘要也计入同一预算,见「上下文压缩」一节);压缩放弃后保留原上下文、等下一次触发再试。鉴权错误在任何重试启发式之前判定、从不重试:请求以专属终态 `auth` 收场(Session 锁定的只是模型引用,凭据在会话装载时取自当前 Project 配置),Web App 据此禁用该 Session 的输入框,直到该模型的凭据被更新(更新后自动解锁)或用户点击「重试」。工具错误从不重试——它们作为 `tool_call_output` 反馈给模型,由模型决定下一步。
+除 `auth` 外,LLM 侧的所有失败都会触发引擎内自动重连——`timeout`(传输形态的错误:网络超时、传输层断连、限流、5xx)、`malformed`(流截断、JSON 解析失败),**以及 `failed`**——凡不是明确凭据错误的供应商拒绝都在此列,普通 403 与配额/订阅错误也一样重试。终态只是分类而非策略:分类器只挑标签,用自己说法描述瞬时故障的网关(例如 `Upstream HTTP/2 stream failed`)或阶梯中途恢复的配额,都与断网一样走满同一阶梯。重试一个真正的永久错误,代价是走完退避梯度后以同样的方式收场;而把瞬时错误直接中断,则毁掉这一轮。注意改的是**策略**而非**分类**:`failed` 请求在 `request_end` 与成本中心里仍然记为 `failed`,不会被改标成超时。重连时同一次 `run` 内重发原始输入,并附加 `[turn_retried]` 块携带上一次的部分输出,避免工具重复执行。默认最多 5 次**连续无进展**的重连,指数退避并设上限(基数 2s、上限 30s:2s、4s、8s、16s、30s,总耐心约 60s——所有可重试类别共用一张时间表,按较慢的类别定基数:供应商重启、限流这类瞬时故障需要以秒计的恢复时间,旧的 250ms 基数约 7.75s 就烧完整个阶梯;每次计划等待也都达到 Web App 2s 的倒计时下限,重试始终可见);超限后该轮以 `failed` 收场。**收到过内容的尝试不计入**:一次尝试若已经吐出内容才断开(例如响应中途的 `terminated: other side closed (UND_ERR_SOCKET)`),说明连接已建立、模型已在产出,阶梯归零、从 2s 重新起步——同一轮里断两次 socket,不该被累加成放弃的理由,何况 `[turn_retried]` 会把已产出的内容一路带进每次重试。归零的兜底是另一条绝对上限:单轮总尝试 20 次,只有「每次吐几个字就断」的端点才够得着它。`attempt` 始终计的是总尝试序号,不随阶梯归零回退。每次失败的 `request_end` 会以 `retry_in_ms` 宣告计划中的等待(与实际休眠同一公式)、以 `attempt` 标注这是本轮第几次尝试(权威序号,CLI 与 Web 的重试行直接显示它),Web App 据此实时倒计时,并提供「立即重试」(经 `Session.skipReconnectWait` 跳过剩余等待——重试计数不变)与「放弃」(普通中断;引擎的退避中中断路径结束本轮)两个内联按钮,CLI 则打印自己的 `[重试]` 行。三种可重试终态的渲染完全一致——用户看不见的重试,等于一次没有任何解释、也无从退出的卡顿。压缩请求是一次普通的 LLM 请求,默认沿用同一重连上限与退避阶梯(无效摘要也计入同一预算,见「上下文压缩」一节);压缩放弃后保留原上下文、等下一次触发再试。鉴权错误在任何重试启发式之前判定、从不重试:请求以专属终态 `auth` 收场(Session 锁定的只是模型引用,凭据在会话装载时取自当前 Project 配置),Web App 据此禁用该 Session 的输入框,直到该模型的凭据被更新(更新后自动解锁)或用户点击「重试」。工具错误从不重试——它们作为 `tool_call_output` 反馈给模型,由模型决定下一步。
## 上下文压缩(Compaction)
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index 2c84ebc3..2869fa50 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -147,7 +147,7 @@ Manage it from the Security policy tab of Project Settings in the Web App (owner
| `max_turns` | `-1` | Maximum LLM turns per Task (`-1` = unlimited; a positive integer caps the Task) |
| `model.max_tokens` | `32000` | Output Token ceiling per Request (-1 = no cap, provider default); each request clamps the effective value to the model's `context_window` minus the estimated input, so a small-window model never gets asked for more than fits |
| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`; the session default, overridable per-Task |
-| `model.timeoutMs` | `120000` | Per-Request timeout (milliseconds) |
+| `model.timeoutMs` | `300000` | **Idle** budget for a Request (milliseconds): the longest wait for the next upstream event, reset by every event — not a cap on the request's total duration. It bounds the connect + first-event wait and the gaps between events; a model that keeps its reasoning off the wire spends its whole thinking phase inside that first gap, which is what the default leaves room for |
| `compaction.max_context_length` | `256000` | Context Token threshold that triggers compaction; the effective threshold is the smaller of this and the model's `context_window` − 2048, so a small-window model compacts inside its window while a window above 258048 fires at this number (an entry with no `context_window` assumes a 128000 window) |
| `compaction.max_session_turns` | `-1` | Cumulative Session turn threshold (`-1` = unlimited) |
| `compaction.mode` | `summarize` | `summarize` / `discard` |
@@ -183,7 +183,7 @@ max_turns: -1
model:
max_tokens: 32000
thinking_level: medium
- timeoutMs: 120000
+ timeoutMs: 300000
compaction:
max_context_length: 256000
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 1485a0b9..a16ffd42 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -147,7 +147,7 @@ enabled = false
| `max_turns` | `-1` | 单个 Task 的最大 LLM 轮数(`-1` 不限制,正整数为上限) |
| `model.max_tokens` | `32000` | 单次输出 Token 天花板(-1 不设上限,用服务商默认);每次请求会把实际值收敛到模型 `context_window` 减估算输入以内,小窗口模型不会被索要放不下的输出 |
| `model.thinking_level` | `medium` | `none` / `low` / `medium` / `high` / `xhigh` / `max`;作为会话默认档位,可被逐轮 Task 参数覆盖 |
-| `model.timeoutMs` | `120000` | 单次 Request 超时(毫秒) |
+| `model.timeoutMs` | `300000` | 单次 Request 的**空闲**超时(毫秒):等待上游下一个事件的上限,收到任一事件即归零重计,不是整次请求的总时长上限。它约束的是连接建立与首个事件的等待、以及流式过程中的事件间隔——思考不外露的模型整段推理都落在「首个事件」这一段里,缺省值为此留足余量 |
| `compaction.max_context_length` | `256000` | 触发压缩的上下文 Token 阈值;生效阈值取它与模型 `context_window` − 2048 中的较小者,故小窗口模型在自己的窗口内压缩,窗口大于 258048 时则在该数值处触发(条目未配置 `context_window` 时按 128000 的假定窗口计) |
| `compaction.max_session_turns` | `-1` | Session 累计轮数阈值(`-1` 不限制) |
| `compaction.mode` | `summarize` | `summarize` / `discard` |
@@ -183,7 +183,7 @@ max_turns: -1
model:
max_tokens: 32000
thinking_level: medium
- timeoutMs: 120000
+ timeoutMs: 300000
compaction:
max_context_length: 256000
diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.md
index 8a7eb2e4..8213d64e 100644
--- a/packages/docs/content/interfaces.en.md
+++ b/packages/docs/content/interfaces.en.md
@@ -103,7 +103,7 @@ interface GenerativeModelConfig {
maxTokens?: number;
fastMode?: boolean; // per-model fast mode (AgentHub fast_mode; premium faster tier), off by default
thinkingLevel?: ThinkingLevelName; // construction default (a per-request parameter can override); "none" | "low" | "medium" | "high" | "xhigh" | "max"
- requestTimeoutMs?: number; // per-Request timeout, default 120000; <=0 disables
+ requestTimeoutMs?: number; // Request idle budget: the longest wait for the next upstream event, default 300000; <=0 disables
toolCallIds?: ToolCallIdAllocator; // Session-level tool_call_id registry (pass the same instance across compaction)
}
```
@@ -114,6 +114,7 @@ interface GenerativeModelConfig {
- the gateway maintains conversation history **statefully**, receiving only new messages each turn; resuming a Session replays committed history through a one-time `setHistory`;
- an internal `EventTranslator` translates gateway stream events into `partial_*` fragments plus complete messages, preserving each item's opaque `fidelity` payload verbatim; segmentation mirrors the gateway's own aggregation — a thinking block is closed by its fidelity payload and a run of equal fidelity stays one block (OpenAI-compatible clients stamp every delta with the same `{ reasoning_field }`, which must not split blocks), while a text segment splits on a differing `fidelity.phase` and closes on a `fidelity.signature`, fidelity keys accumulating on merge; complete messages settle in thinking → text → tool_call order;
+- every request asks the gateway for thought summaries (`thinking_summary`), which no provider rejects — it is dropped where the family has no such thing, and read as "summarized thinking" by the Claude family. Besides letting the reader watch the model reason, it keeps events arriving during a reasoning phase, which is what `requestTimeoutMs` measures: the timer runs only while awaiting the next upstream event, resets on each one, and never counts consumer-side time (yielding, approvals, Trace writes), so it bounds silence rather than the length of a response;
- `ToolCallIdAllocator` disambiguates providers that use the function name as the call id (append `#n` inbound, strip outbound), scoped to the whole Session;
- provider differences (tool-call formats, reasoning content, streaming events) are absorbed entirely inside the gateway — see [Models & Providers](/models).
diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.md
index 9189e6b5..11ca3851 100644
--- a/packages/docs/content/interfaces.zh.md
+++ b/packages/docs/content/interfaces.zh.md
@@ -103,7 +103,7 @@ interface GenerativeModelConfig {
maxTokens?: number;
fastMode?: boolean; // 单模型快速模式(AgentHub fast_mode;溢价快速档位),默认关闭
thinkingLevel?: ThinkingLevelName; // 构造期默认档位(逐请求参数可覆盖);"none" | "low" | "medium" | "high" | "xhigh" | "max"
- requestTimeoutMs?: number; // 单次 Request 超时,默认 120000;<=0 关闭
+ requestTimeoutMs?: number; // Request 的空闲超时:等待上游下一个事件的上限,默认 300000;<=0 关闭
toolCallIds?: ToolCallIdAllocator; // Session 级 tool_call_id 唯一性登记表(压缩重建时传同一实例)
}
```
@@ -114,6 +114,7 @@ interface GenerativeModelConfig {
- 网关**有状态**地维护会话历史,每轮只接收新消息;恢复 Session 时经一次性的 `setHistory` 重放已提交历史;
- 内部的 `EventTranslator` 把网关流式事件翻译为 `partial_*` 分片 + 完整消息,逐条原样保留不透明的 `fidelity` 保真负载;分段与网关自身的聚合一致——thinking 块由其 fidelity 负载闭合,连续相同的 fidelity 归为同一块(OpenAI 兼容客户端给每条增量盖同一个 `{ reasoning_field }`,不能因此切块),text 段遇到不同的 `fidelity.phase` 即切分、遇到 `fidelity.signature` 即闭合,合并时 fidelity 键累积;完整消息按 thinking → text → tool_call 顺序落盘;
+- 每次请求都向网关索取思考摘要(`thinking_summary`),没有 Provider 会因此报错——没有对应能力的家族由网关丢弃该字段,Claude 系则据此把思考切为摘要展示。它除了让读者看得见模型在想什么,也让推理阶段持续有事件到达,而这正是 `requestTimeoutMs` 计的东西:计时只在等待上游下一个事件时进行、收到任一事件即归零,消费侧的时间(向前端产出、等待审批、写 Trace)一概不计——它约束的是沉默,不是回复的长度;
- `ToolCallIdAllocator` 处理个别 Provider 用函数名充当调用 id 的情况(入站追加 `#n`、出站剥离),作用域覆盖整个 Session;
- Provider 协议差异(工具调用格式、思考内容、流式事件)全部在网关内抹平,见[模型与 Provider](/models)。
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 235d41b6..94fc6e7a 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -563,7 +563,7 @@ export const en: Strings = {
thinkingLevelNoneKept:
"Stored legacy tier: new selections no longer offer the off tier (many models cannot disable thinking).",
timeoutMs: "model.timeoutMs",
- timeoutMsHint: "Per-request timeout, ms",
+ timeoutMsHint: "Idle budget between upstream events, ms — not a cap on the whole request",
compaction: "Context compaction",
maxContextLength: "max_context_length",
maxContextLengthHint: "Context threshold that triggers compaction",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index c20b9445..39d232a4 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -536,7 +536,7 @@ export const zh = {
/** Row description shown only while the stored config is `none`: displayed as-is, never rewritten, and no longer offered as a choice. */
thinkingLevelNoneKept: "已存的历史档位:新选择不再提供关闭档(多数模型不支持关闭思考)。",
timeoutMs: "model.timeoutMs",
- timeoutMsHint: "单次 Request 超时,毫秒",
+ timeoutMsHint: "等待上游下一个事件的空闲上限,毫秒;不是整次请求的总时长上限",
compaction: "上下文压缩(compaction)",
maxContextLength: "max_context_length",
maxContextLengthHint: "触发压缩的上下文阈值",