Skip to content

Commit 39e618a

Browse files
anandgupta42claude
andcommitted
fix(analyst): structured policy codes win over overflow-looking text; never finalize onto a completed compaction summary
- `message-v2.ts`: an explicit policy code (`guardrail_intervened` incl. nested orchestration codes, `content_filter`, `content_policy*`, `policy_violation`, `safety_*`, `moderation_*`) keeps the error fatal even when the message text looks like a context overflow; explicit overflow codes (`context_length_exceeded`, `content_length_exceeded`) and HTTP 413 stay overflows; policy metadata survives response truncation - `prompt.ts`: when the message that would carry a recovered committed answer is a finished, error-free, non-empty compaction summary (a user request was queued during compaction), the summary stays intact as the compaction boundary and the committed text is published once on a new assistant message with the committed request's parent, agent, mode, model, variant and path; failed/empty summariser recovery still converts its own summary message - tests: 503 guardrail with overflow text during echo stays fatal without publishing or compacting; queued user after successful compaction keeps the summary and gets tools after the new committed-answer message; 413 `content_length_exceeded` still compacts and resumes; 21 `fromError` cases for code vs text precedence Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 09e9581 commit 39e618a

4 files changed

Lines changed: 246 additions & 24 deletions

File tree

‎packages/opencode/src/session/message-v2.ts‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -544,15 +544,15 @@ export namespace MessageV2 {
544544

545545
function isEchoPolicyCode(code: string | undefined): boolean {
546546
if (!code) return false
547-
return echoPolicyCodes.has(code.toLowerCase()) || /^(safety|moderation)_.+$/i.test(code)
547+
return echoPolicyCodes.has(code.toLowerCase()) || /^(content_policy.*|(safety|moderation)_.+)$/i.test(code)
548548
}
549549

550-
function echoPolicyCode(responseBody: string | undefined): string | undefined {
550+
function responseErrorCode(responseBody: string | undefined, matches: (code: string) => boolean): string | undefined {
551551
if (!responseBody) return undefined
552552
const find = (value: unknown): string | undefined => {
553553
if (!value || typeof value !== "object") return undefined
554554
for (const [key, child] of Object.entries(value)) {
555-
if (key === "code" && typeof child === "string" && isEchoPolicyCode(child)) return child
555+
if (key === "code" && typeof child === "string" && matches(child)) return child
556556
const nested = find(child)
557557
if (nested) return nested
558558
}
@@ -564,6 +564,10 @@ export namespace MessageV2 {
564564
}
565565
}
566566

567+
function echoPolicyCode(responseBody: string | undefined): string | undefined {
568+
return responseErrorCode(responseBody, isEchoPolicyCode)
569+
}
570+
567571
export function isEchoTransportError(error: Assistant["error"]): boolean {
568572
if (error?.name !== "APIError") return false
569573
const { statusCode, responseBody, metadata, isRetryable } = error.data
@@ -1271,23 +1275,25 @@ export namespace MessageV2 {
12711275
providerID: ctx.providerID,
12721276
error: e,
12731277
})
1274-
// altimate_change start — retain policy decisions before response truncation without overriding context overflow
1278+
// altimate_change start — structured policy decisions override overflow text, while explicit overflow codes win
1279+
const overflowCode = responseErrorCode(e.responseBody, (code) =>
1280+
["context_length_exceeded", "content_length_exceeded"].includes(code.toLowerCase()),
1281+
)
12751282
const policyCode = echoPolicyCode(e.responseBody)
1276-
if (parsed.type === "api_error" && policyCode) {
1283+
if (policyCode && e.statusCode !== 413 && !overflowCode) {
12771284
return new MessageV2.APIError(
12781285
{
12791286
message: parsed.message,
12801287
statusCode: e.statusCode,
1281-
isRetryable: parsed.isRetryable,
1282-
responseHeaders: parsed.responseHeaders,
1288+
isRetryable: parsed.type === "api_error" ? parsed.isRetryable : e.isRetryable,
1289+
responseHeaders: parsed.type === "api_error" ? parsed.responseHeaders : e.responseHeaders,
12831290
responseBody: parsed.responseBody,
1284-
metadata: { ...parsed.metadata, code: policyCode },
1291+
metadata: { ...(parsed.type === "api_error" ? parsed.metadata : undefined), code: policyCode },
12851292
},
12861293
{ cause: e },
12871294
).toObject()
12881295
}
1289-
// altimate_change end
1290-
if (parsed.type === "context_overflow") {
1296+
if (parsed.type === "context_overflow" || overflowCode) {
12911297
return new MessageV2.ContextOverflowError(
12921298
{
12931299
message: parsed.message,
@@ -1296,6 +1302,7 @@ export namespace MessageV2 {
12961302
{ cause: e },
12971303
).toObject()
12981304
}
1305+
// altimate_change end
12991306

13001307
return new MessageV2.APIError(
13011308
{

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -827,8 +827,12 @@ export namespace SessionPrompt {
827827
})
828828
using _unsubToolsChanged = defer(unsubscribeToolsChanged)
829829
// altimate_change end
830-
// altimate_change start - retain the exact committed text through automatic compaction
831-
let committedAnswer: { userID: MessageID; output: string } | undefined
830+
// altimate_change start — retain the exact committed text through automatic compaction
831+
let committedAnswer: {
832+
userID: MessageID
833+
output: string
834+
assistant: Pick<MessageV2.Assistant, "agent" | "mode" | "modelID" | "providerID" | "variant" | "path">
835+
} | undefined
832836
const compactionContinuations = new Set<MessageID>()
833837
// The legacy message table has no explicit sequence column. Its SQLite rowid
834838
// records insertion order and survives updateMessage's data-only upserts.
@@ -870,6 +874,14 @@ export namespace SessionPrompt {
870874
commit.state.status === "completed"
871875
? {
872876
userID: user.id,
877+
assistant: {
878+
agent: assistant.agent,
879+
mode: assistant.mode,
880+
modelID: assistant.modelID,
881+
providerID: assistant.providerID,
882+
variant: assistant.variant,
883+
path: assistant.path,
884+
},
873885
// Completed-tool metadata retains the full answer through the per-result output cap.
874886
output:
875887
typeof commit.state.metadata.committed_text === "string"
@@ -915,7 +927,31 @@ export namespace SessionPrompt {
915927
return false
916928
// Once the echo has started, this answer still belongs to the earlier request.
917929
// Publish it before the loop continues to any user request queued during generation.
918-
const storedText = MessageV2.parts(message.id).filter((part) => part.type === "text")
930+
const recoveryCause = error ?? message.metadata?.answer_commit_echo_error
931+
const cause =
932+
recoveryCause ??
933+
(message.finish !== "stop" ? { finish: message.finish ?? "unknown" } : undefined)
934+
let storedText = MessageV2.parts(message.id).filter((part) => part.type === "text")
935+
if (
936+
message.summary && message.finish && !message.error &&
937+
!message.metadata?.answer_commit_echo_error &&
938+
storedText.some((part) => part.text.trim().length > 0)
939+
) {
940+
// A successful summary remains the compaction boundary. Deliver the
941+
// committed request's answer separately, retaining its original identity.
942+
message = await Session.updateMessage({
943+
...committedAnswer.assistant,
944+
id: MessageID.ascending(),
945+
parentID: committedAnswer.userID,
946+
sessionID,
947+
role: "assistant",
948+
cost: 0,
949+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
950+
time: { created: Date.now() },
951+
}) as MessageV2.Assistant
952+
storedText = []
953+
deferredText = []
954+
}
919955
// Only buffered parts are safe to reuse: stored parts may already have
920956
// streamed deltas, and a blank update does not reset client text.
921957
const first = deferredText[0]
@@ -930,10 +966,6 @@ export namespace SessionPrompt {
930966
for (const old of storedText) {
931967
if (old.id !== part.id) await Session.removePart({ sessionID, messageID: message.id, partID: old.id })
932968
}
933-
const recoveryCause = error ?? message.metadata?.answer_commit_echo_error
934-
const cause =
935-
recoveryCause ??
936-
(message.finish !== "stop" ? { finish: message.finish ?? "unknown" } : undefined)
937969
if (cause) message.metadata = { ...message.metadata, answer_commit_echo_error: cause }
938970
delete message.error
939971
// A failed summariser becomes the exiting answer, so clients must no longer hide it as compaction machinery.

0 commit comments

Comments
 (0)