Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 4 additions & 41 deletions packages/opencode/src/context-edit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export namespace ContextEdit {

// ── Constants ──────────────────────────────────────────

const MAX_EDITS_PER_TURN = 10
const MAX_HIDDEN_RATIO = 0.7
const PROTECTED_RECENT_TURNS = 2
const PROTECTED_TOOLS = ["skill"]
Expand Down Expand Up @@ -589,11 +588,14 @@ export namespace ContextEdit {
for (const part of msg.parts) {
if (!part.lifecycle) continue
if (part.lifecycle.hint === "pinned") continue
if (part.lifecycle.hint === "ephemeral") continue // ephemeral parts are filtered upstream
if (part.edit?.hidden) continue

const turns = part.lifecycle.afterTurns
if (turns == null) continue
const elapsed = currentTurn - part.lifecycle.turnWhenSet
const turnWhenSet = part.lifecycle.turnWhenSet
if (turnWhenSet == null) continue
const elapsed = currentTurn - turnWhenSet
if (elapsed < turns) continue

const lifecycle = part.lifecycle
Expand Down Expand Up @@ -632,45 +634,6 @@ export namespace ContextEdit {
})
})
changed = true
} else if (lifecycle.hint === "ephemeral") {
Database.transaction(() => {
const casHash = CAS.store(JSON.stringify(part), {
contentType: part.type === "tool" ? "tool-output" : part.type,
sessionID: msg.info.sessionID,
partID: part.id,
tokens: Token.estimate(getPartContent(part)),
})

// Track in EditGraph for reversibility
const version = EditGraph.commit({
sessionID: msg.info.sessionID,
partID: part.id,
operation: "sweep-externalize",
casHash,
agent: "sweeper",
})

const summary = lifecycle.reason ?? "Auto-externalized ephemeral content"
const summaryText = `[Externalized: ${summary}. Use context_deref("${casHash}") to retrieve.]`
if (part.type === "text") {
Session.updatePart({
...part,
text: summaryText,
edit: { hidden: false, casHash, editedAt: Date.now(), editedBy: "sweeper", version },
})
} else {
Session.updatePart({
...part,
edit: { hidden: true, casHash, editedAt: Date.now(), editedBy: "sweeper", version },
})
}
log.info("swept ephemeral", {
partID: part.id.slice(0, 12),
reason: lifecycle.reason,
casHash: casHash.slice(0, 12),
})
})
changed = true
}
}
}
Expand Down
23 changes: 19 additions & 4 deletions packages/opencode/src/session/message-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ import { Snapshot } from "@/snapshot"
import { fn } from "@/util/fn"
import { Database, NotFoundError, and, desc, eq, inArray, lt, or } from "@/storage/db"
import { MessageTable, PartTable, SessionTable } from "./session.sql"
import { ProviderTransform } from "@/provider/transform"
import { STATUS_CODES } from "http"
import { Storage } from "@/storage/storage"
import { ProviderError } from "@/provider/error"
import { iife } from "@/util/iife"
import { type SystemError } from "bun"
Expand Down Expand Up @@ -85,7 +82,7 @@ export namespace MessageV2 {
reason: z.string().optional(),
setAt: z.number(),
setBy: z.string(),
turnWhenSet: z.number(),
turnWhenSet: z.number().optional(),
})
.optional()
.meta({ ref: "LifecycleMeta" })
Expand Down Expand Up @@ -939,6 +936,24 @@ export namespace MessageV2 {
return result
}

export function filterEphemeral(messages: WithParts[]): WithParts[] {
const ephemeralMsgIDs = new Set<string>()
// Collect message IDs where every part is ephemeral
for (const msg of messages) {
if (msg.parts.length > 0 && msg.parts.every((p) => p.lifecycle?.hint === "ephemeral")) {
ephemeralMsgIDs.add(msg.info.id)
}
}
if (ephemeralMsgIDs.size === 0) return messages
// Also drop the paired assistant response (or user prompt) for ephemeral messages
for (const msg of messages) {
if (msg.info.role === "assistant" && "parentID" in msg.info && ephemeralMsgIDs.has(msg.info.parentID)) {
ephemeralMsgIDs.add(msg.info.id)
}
}
return messages.filter((m) => !ephemeralMsgIDs.has(m.info.id))
}

export function filterEdited(messages: WithParts[]): WithParts[] {
let hasEdits = false
for (const msg of messages) {
Expand Down
10 changes: 4 additions & 6 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ export namespace SessionPrompt {
log.info("loop", { step, sessionID })
if (abort.aborted) break
let msgs = await MessageV2.filterCompacted(MessageV2.stream(sessionID))
msgs = MessageV2.filterEphemeral(msgs)
msgs = MessageV2.filterEdited(msgs)
const currentTurn = msgs.filter((m) => m.info.role === "user").length
msgs = ContextEdit.sweep(msgs, currentTurn)
Expand Down Expand Up @@ -1920,19 +1921,16 @@ NOTE: At any point in time through this workflow you should feel free to ask the
})) as MessageV2.WithParts

if (command.ephemeral) {
const msgs: MessageV2.WithParts[] = []
for await (const m of MessageV2.stream(input.sessionID)) msgs.push(m)
const turn = msgs.filter((m) => m.info.role === "user").length
const lifecycle: MessageV2.LifecycleMeta = {
hint: "ephemeral",
afterTurns: 0,
reason: "Ephemeral command output",
setAt: Date.now(),
setBy: "system",
turnWhenSet: turn,
}

// Mark the user's command input parts as ephemeral too
// Mark the user's command input parts as ephemeral
const msgs: MessageV2.WithParts[] = []
for await (const m of MessageV2.stream(input.sessionID)) msgs.push(m)
const parentID = (result.info as MessageV2.Assistant).parentID
const userMsg = msgs.find((m) => m.info.id === parentID)
if (userMsg) {
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/tool/context-edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ Constraints: own messages only (unless focus agent), not last 2 turns, max 10/tu
.describe("Lifecycle hint (for mark operation)"),
afterTurns: z
.number()
.int()
.min(1)
.optional()
.describe("Turns before auto-action (for mark; default 3 for discardable, 5 for ephemeral)"),
reason: z.string().optional().describe("Why this part was marked (for mark)"),
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/js/src/v2/gen/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ export type LifecycleMeta = {
reason?: string
setAt: number
setBy: string
turnWhenSet: number
turnWhenSet?: number
}

export type TextPart = {
Expand Down
Loading