{"record":{"id":"35e6bfa412b99937","repo":"JuliusBrussee/caveman","slug":"cave-provider-terminal-finalmessage-stopreason","errorCode":"cave_provider_terminal_${finalMessage.stopReason}","errorMessage":"cave_provider_terminal_${finalMessage.stopReason}","messagePattern":"cave_provider_terminal_(.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent/src/runtime.ts","lineNumber":2111,"sourceCode":"        (efficiencyPlan !== undefined ||\n          executionContext.spendLedgers.length > 0 ||\n          usageFailure.message === \"cave_provider_model_identity_mismatch\" ||\n          usageFailure.message === \"cave_provider_identity_missing\")) {\n      throw usageFailure;\n    }\n    if (pendingSpendReservations.length > 0) {\n      markSpendIncomplete(executionContext.spendLedgers);\n      throw new Error(\"cave_subagent_spend_evidence_incomplete\");\n    }\n    // A run stopped before its first call has no assistant message, and that is\n    // the honest outcome rather than missing evidence: the caller gets an empty\n    // answer, zero usage, and the reason the runtime declined to spend.\n    if (!finalMessage && stopReason === undefined) {\n      throw new Error(\"cave_incomplete_evidence: Pi emitted no final assistant message\");\n    }\n    if (finalMessage &&\n        (finalMessage.stopReason === \"error\" || finalMessage.stopReason === \"aborted\")) {\n      throw new Error(`cave_provider_terminal_${finalMessage.stopReason}`);\n    }\n    const text = finalMessage === undefined ? \"\" : assistantText(finalMessage);\n    if (definition.output?.schema && finalMessage !== undefined) {\n      let parsed: unknown;\n      try {\n        parsed = JSON.parse(text);\n      } catch {\n        throw new Error(\"cave_output_schema_invalid_json\");\n      }\n      if (!Value.Check(definition.output.schema, parsed)) {\n        throw new Error(\"cave_output_schema_mismatch\");\n      }\n    }\n    if (appliedPlan.appliedTransformIDs.length > 0 && !cacheBoundaryKnown) {\n      cacheBust = true;\n      markRequestPassThrough(headers, appliedPlan, \"cache_boundary_unobserved\");\n    }\n    for (const child of nestedReceipts) receipt.recordSubagent(child);","sourceCodeStart":2093,"sourceCodeEnd":2129,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/agent/src/runtime.ts#L2093-L2129","documentation":"'cave_provider_terminal_error' or 'cave_provider_terminal_aborted' is thrown when the final assistant message reports a terminal stopReason of \"error\" or \"aborted\" (runtime.ts:2109-2111). The template interpolates the actual stopReason, so the message tells you exactly which terminal provider state ended the run.","triggerScenarios":"The provider's last assistant message carries stopReason === 'error' (provider-side failure during generation) or 'aborted' (the run was aborted via options.signal or pi.abort()) and that message became finalMessage at the end of streamAgentInternal.","commonSituations":"Caller aborts the AbortSignal mid-run (yields _aborted); provider API error mid-stream (rate limit, overloaded, auth revoked) surfaces as stopReason error; network interruption terminates the stream with an error stop.","solutions":["If _aborted: check whether your code (or a timeout) called abort on the signal; remove premature aborts or extend the deadline.","If _error: inspect provider status — check rate limits, quota, and API key validity, then retry with backoff.","Check RunResult/receipt breakers and budget state to confirm a framework guard didn't trigger the abort path.","Retry the run; transient provider errors (overloaded) usually clear."],"exampleFix":"// before: aborting as soon as the first chunk arrives, producing cave_provider_terminal_aborted\nconst controller = new AbortController();\nstreamAgent(agent, input, { signal: controller.signal });\ncontroller.abort();\n\n// after: let the run finish; abort only on genuine cancellation\nconst controller = new AbortController();\nprocess.on(\"SIGINT\", () => controller.abort());\nawait collect(streamAgent(agent, input, { signal: controller.signal }));","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"function isProviderTerminal(msg: AssistantMessage): boolean {\n  return msg.stopReason === \"error\" || msg.stopReason === \"aborted\";\n}","tryCatchPattern":"try {\n  const result = await runAgent(agent, input, { signal });\n} catch (e) {\n  const msg = e instanceof Error ? e.message : \"\";\n  if (msg === \"cave_provider_terminal_aborted\") {\n    // your signal aborted the run — handle cancellation\n  } else if (msg === \"cave_provider_terminal_error\") {\n    // provider failed mid-stream — retry with backoff\n  }\n}","preventionTips":["Only abort the signal on genuine user cancellation, not proactively.","Prefer RunOptions.deadlineMs for time limits — it stops between calls.","Watch provider rate limits and quota to avoid mid-stream error stops.","Wrap runs with bounded exponential-backoff retries for transient provider errors."],"tags":["provider","abort","terminal-stop","streaming"],"backgroundTag":"upstream-api-error","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}