Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stop false merge-queue agent timeouts

Adam Eivy4e601c1aa48c
diff --git a/.changelog/next/fixed-agent-e5bcfbf2.md b/.changelog/next/fixed-agent-e5bcfbf2.md
new file mode 100644
index 0000000000..db5e12af67
--- /dev/null
+++ b/.changelog/next/fixed-agent-e5bcfbf2.md
@@ -0,0 +1 @@
+- Ollama-backed Claude agent runs no longer lose long responses at the default output token ceiling.
diff --git a/server/lib/README.md b/server/lib/README.md
index 96b2922340..4d6587bc61 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -128,7 +128,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |
| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring bare model ids under the selected local provider (`ollama` or `mtplx`) for marked OpenCode providers. Fixes --model rejection. |
-| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
+| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
| `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` predicate, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. |
diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.js
index 675bafb328..0cf6a763a1 100644
--- a/server/lib/cliChildEnv.js
+++ b/server/lib/cliChildEnv.js
@@ -44,6 +44,21 @@ import { withSpawnCwdEnv } from './spawnCwd.js';
import { buildOpencodeEnvVars } from './opencodeConfig.js';
import { agentGuardEnv } from './agentGuard/index.js';
+// Claude Code defaults to 32K output tokens. Thinking-capable local models can
+// legitimately spend more than that before returning their final tool call;
+// when they do, Claude Code paints a terminal API Error and waits forever at an
+// empty composer. Cloud Claude models own their own output budgets, so widen the
+// ceiling only for a Claude harness explicitly marked as Ollama-backed. A value
+// in provider.envVars still wins below.
+const CLAUDE_OLLAMA_MAX_OUTPUT_TOKENS = '65536';
+
+function claudeOllamaEnvDefaults(provider) {
+ const command = String(provider?.command || '').split(/[\\/]/).pop()?.replace(/\.(?:cmd|exe)$/i, '').toLowerCase();
+ return provider?.ollamaBacked === true && command === 'claude'
+ ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: CLAUDE_OLLAMA_MAX_OUTPUT_TOKENS }
+ : {};
+}
+
/**
* The ordered provider env layers, without a base env, PWD pin, or strip.
*
@@ -65,6 +80,7 @@ import { agentGuardEnv } from './agentGuard/index.js';
export function composeProviderEnv({ before = null, provider = null, model = null, extra = null } = {}) {
return {
...(before || {}),
+ ...claudeOllamaEnvDefaults(provider),
...(provider?.envVars || {}),
// Rebuilds OPENCODE_CONFIG_CONTENT with a declared models map for OpenCode
// local providers (an empty object for everyone else) so the injected
diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.js
index 14b7531c3a..9354d6f5b5 100644
--- a/server/lib/cliChildEnv.test.js
+++ b/server/lib/cliChildEnv.test.js
@@ -147,6 +147,21 @@ describe('buildCliChildEnv — pm2 guard', () => {
// are exactly the sites an earlier draft of the guard could not see, and where
// the OpenCode sweep was missed once before.
describe('composeProviderEnv — delta for sites that do not spawn directly', () => {
+ it('widens Claude Code output for Ollama harnesses while preserving explicit provider overrides', () => {
+ const localClaude = { command: '/usr/local/bin/claude', ollamaBacked: true, envVars: {} };
+ expect(composeProviderEnv({ provider: localClaude }).CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBe('65536');
+ expect(composeProviderEnv({
+ provider: { ...localClaude, envVars: { CLAUDE_CODE_MAX_OUTPUT_TOKENS: '48000' } },
+ }).CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBe('48000');
+
+ expect(composeProviderEnv({
+ provider: { command: 'claude', ollamaBacked: false, envVars: {} },
+ }).CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBeUndefined();
+ expect(composeProviderEnv({
+ provider: { command: 'opencode', ollamaBacked: true, envVars: {} },
+ }).CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBeUndefined();
+ });
+
it('emits only the provider layers, with no base env, PWD, or strip', () => {
const delta = composeProviderEnv({
before: { GH_TOKEN: 'forge' },
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 8b2286e762..1435ef73b3 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -298,6 +298,33 @@ export const ERROR_PATTERNS = [
},
// ===== Context & Token Errors =====
+ {
+ // Claude Code's own terminal output-ceiling banner. This exact wording is
+ // structured harness chrome, so it may override an idle-reaper verdict;
+ // otherwise the empty composer that follows gets blamed on whichever phase
+ // marker happened to be latched from the repainted prompt. Keep this ahead
+ // of the generic token/context patterns and require the env-var guidance so
+ // ordinary agent prose about output limits stays an output-scan match.
+ pattern: /Claude's response exceeded the \d+ output token maximum[\s\S]{0,240}?CLAUDE_CODE_MAX_OUTPUT_TOKENS/i,
+ category: 'output-length',
+ actionable: false,
+ origin: 'provider',
+ structuredMarker: /API Error:\s*Claude's response exceeded the \d+ output token maximum[\s\S]{0,240}?CLAUDE_CODE_MAX_OUTPUT_TOKENS/i,
+ extract: (match, output) => ({
+ message: 'Output length exceeded',
+ suggestedFix: 'Claude Code exhausted its response ceiling. Retry with a larger CLAUDE_CODE_MAX_OUTPUT_TOKENS value or reduce the requested response.',
+ compaction: {
+ needed: true,
+ reason: 'output-limit',
+ outputSize: Buffer.byteLength(output || ''),
+ retryHints: [
+ 'Limit output to changed files and a brief summary only',
+ 'Do not echo file contents back — just reference file paths and line numbers',
+ 'Combine related changes into single descriptions'
+ ]
+ }
+ })
+ },
{
pattern: /context.?length|max.?tokens|token.?limit|context.?window/i,
category: 'context-length',
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 73a4d0d4f3..cc310ed53f 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -172,6 +172,27 @@ describe('analyzeAgentFailure — ERROR_PATTERNS classification', () => {
expect(analysis.compaction?.needed).toBe(true);
});
+ it('lets Claude Code\'s structured output-ceiling banner override a false idle phase', () => {
+ const banner = "API Error: Claude's response exceeded the 32000 output token maximum.\nTo configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable.";
+ const analysis = analyzeAgentFailure(withLead(banner), { id: 't' }, 'local-model', {
+ completionReason: 'merge-queue-idle-timeout',
+ });
+ expect(analysis.category).toBe('output-length');
+ expect(analysis.origin).toBe('provider');
+ expect(analysis.actionable).toBe(false);
+ expect(analysis.compaction).toMatchObject({ needed: true, reason: 'output-limit' });
+ expect(analysis.completionReason).toBe('merge-queue-idle-timeout');
+ });
+
+ it('does not promote ordinary prose about Claude Code output limits to provider origin', () => {
+ const prose = "The prior run said Claude's response exceeded the 32000 output token maximum and named CLAUDE_CODE_MAX_OUTPUT_TOKENS.";
+ const analysis = analyzeAgentFailure(withLead(prose), { id: 't' }, 'local-model', {
+ completionReason: 'idle-no-changes',
+ });
+ expect(analysis.category).toBe('no-changes');
+ expect(analysis.origin).toBe('runner');
+ });
+
it('classifies an Ollama context overflow separately from a generic context-length error', () => {
const body = 'API Error: 400 {"error":{"code":400,"message":"request (32768 tokens) exceeds the available ' +
'context size (32768 tokens), try increasing it","type":"exceed_context_size_error",' +