GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor(ai): simplify response stream state (#45835) · anomalyco/opencode@18e22cd

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/ai
    • src/protocols
      • open-responses.ts
    • test/provider
      • open-responses-lifecycle.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/ai/src/protocols/open-responses.ts‎

Copy file name to clipboardExpand all lines: packages/ai/src/protocols/open-responses.ts
+31-50Lines changed: 31 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -391,21 +391,19 @@ export interface ParserState {
391391
readonly name: string
392392
readonly providerMetadataKey: string
393393
readonly tools: ToolStream.State<string>
394-
// Call ids that already emitted their terminal tool-call event, so duplicate
395-
// or late item events for the same call stay no-ops. Keyed by `call_id`
396-
// because duplicate events may disagree on whether `item.id` is present.
394+
// Call ids stay independent of item ids, which may be omitted or reused.
397395
readonly completedTools: ReadonlySet<string>
398396
readonly hasFunctionCall: boolean
399397
readonly lifecycle: Lifecycle.State
400398
readonly outputItems: Readonly<Record<number, string>>
401-
readonly messageItems: ReadonlySet<string>
402-
readonly messagePhases: Readonly<Record<string, MessagePhase | null>>
399+
readonly message: { readonly id: string; readonly phase: MessagePhase | null | undefined } | undefined
403400
readonly reasoningItems: Readonly<Record<string, ReasoningStreamItem>>
404401
}
405402

406403
type ReasoningSummaryStatus = "active" | "can-conclude" | "concluded"
407404

408405
interface ReasoningStreamItem {
406+
readonly open: boolean
409407
readonly encryptedContent: string | null | undefined
410408
// Keyed by the wire protocol's numeric `summary_index`. JS object keys coerce to
411409
// strings, but typing the map as `Record<number, ...>` documents intent
@@ -830,16 +828,16 @@ const TERMINAL_TYPES = new Set(["error", "response.completed", "response.incompl
830828
export const terminal = (event: Event) => TERMINAL_TYPES.has(event.type)
831829

832830
const onOutputTextDelta = (state: ParserState, event: Event, id: string): StepResult => {
833-
if (!event.delta || !state.messageItems.has(id)) return [state, NO_EVENTS]
831+
if (!event.delta || state.message?.id !== id) return [state, NO_EVENTS]
834832
const events: LLMEvent[] = []
835-
const phase = state.messagePhases[id]
833+
const phase = state.message.phase
836834
const metadata = providerMetadata(state, { itemId: id, ...(phase === undefined ? {} : { phase }) })
837835
const lifecycle = Lifecycle.textStart(state.lifecycle, events, id, metadata)
838836
return [{ ...state, lifecycle: Lifecycle.textDelta(lifecycle, events, id, event.delta) }, events]
839837
}
840838

841839
const onOutputTextDone = (state: ParserState, event: Event, id: string): StepResult => {
842-
if (state.messageItems.has(id)) {
840+
if (state.message?.id === id) {
843841
if (state.lifecycle.text.has(id) || event.text === undefined) return [state, NO_EVENTS]
844842
return onOutputTextDelta(state, { ...event, delta: event.text }, id)
845843
}
@@ -852,8 +850,7 @@ export const outputItemID = (state: ParserState, event: Event) =>
852850

853851
const startReasoningSummaryPart = (state: ParserState, itemID: string, index: number): StepResult => {
854852
const item = state.reasoningItems[itemID]
855-
if (!item || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
856-
if (Object.values(item.summaryParts).every((status) => status === "concluded")) return [state, NO_EVENTS]
853+
if (!item?.open || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
857854

858855
const events: LLMEvent[] = []
859856
const lifecycle = Object.entries(item.summaryParts)
@@ -893,26 +890,19 @@ const startReasoningSummaryPart = (state: ParserState, itemID: string, index: nu
893890

894891
export const onReasoningDelta = (state: ParserState, event: Event, itemID: string): StepResult => {
895892
const item = state.reasoningItems[itemID]
896-
if (!event.delta || !item) return [state, NO_EVENTS]
893+
if (!event.delta || !item?.open) return [state, NO_EVENTS]
897894
const index = event.summary_index ?? 0
898895
if (item.summaryParts[index] === "concluded") return [state, NO_EVENTS]
899-
// An unseen index cannot reopen an item whose parts have all concluded.
900-
if (
901-
item.summaryParts[index] === undefined &&
902-
Object.values(item.summaryParts).every((status) => status === "concluded")
903-
)
904-
return [state, NO_EVENTS]
905-
const started: StepResult =
906-
item.summaryParts[index] === undefined ? startReasoningSummaryPart(state, itemID, index) : [state, NO_EVENTS]
907-
const current = started[0].reasoningItems[itemID]
908-
if (!current) return started
909-
const events: LLMEvent[] = [...started[1]]
896+
const [started, emitted] = startReasoningSummaryPart(state, itemID, index)
897+
const current = started.reasoningItems[itemID]
898+
if (!current) return [started, emitted]
899+
const events: LLMEvent[] = [...emitted]
910900
return [
911901
{
912-
...started[0],
913-
lifecycle: Lifecycle.reasoningDelta(started[0].lifecycle, events, `${itemID}:${index}`, event.delta),
902+
...started,
903+
lifecycle: Lifecycle.reasoningDelta(started.lifecycle, events, `${itemID}:${index}`, event.delta),
914904
reasoningItems: {
915-
...started[0].reasoningItems,
905+
...started.reasoningItems,
916906
[itemID]: { ...current, deltaIndexes: new Set([...current.deltaIndexes, index]) },
917907
},
918908
},
@@ -925,7 +915,7 @@ export const onReasoningDelta = (state: ParserState, event: Event, itemID: strin
925915
// as a single delta unless that summary index already streamed one.
926916
export const onReasoningDone = (state: ParserState, event: Event, itemID: string): StepResult => {
927917
const item = state.reasoningItems[itemID]
928-
if (!item || typeof event.text !== "string") return [state, NO_EVENTS]
918+
if (!item?.open || typeof event.text !== "string") return [state, NO_EVENTS]
929919
const index = event.summary_index ?? 0
930920
if (item.deltaIndexes.has(index)) return [state, NO_EVENTS]
931921
return onReasoningDelta(state, { ...event, delta: event.text }, itemID)
@@ -949,28 +939,27 @@ const onOutputItemAdded = (state: ParserState, event: Event): StepResult => {
949939
if (item?.type === "message" && item.id !== undefined) {
950940
const itemID = item.id
951941
const phase = messagePhase(item.phase)
952-
// A new message item is an implicit boundary for every earlier message
953-
// item: text still streaming is ended, and all older items leave the
954-
// tracked set so their late deltas stay no-ops instead of overlapping.
942+
// A new message closes earlier messages, including ones that never streamed.
955943
const events: LLMEvent[] = []
956944
const lifecycle = [...state.lifecycle.text]
957945
.filter((id) => id !== itemID)
958946
.reduce((lifecycle, id) => {
959-
const openPhase = state.messagePhases[id]
947+
const openPhase = state.message?.id === id ? state.message.phase : undefined
960948
return Lifecycle.textEnd(
961949
lifecycle,
962950
events,
963951
id,
964952
providerMetadata(state, { itemId: id, ...(openPhase === undefined ? {} : { phase: openPhase }) }),
965953
)
966954
}, state.lifecycle)
967-
const nextPhase = phase === undefined ? state.messagePhases[itemID] : phase
968955
return [
969956
{
970957
...state,
971958
lifecycle,
972-
messageItems: new Set([itemID]),
973-
messagePhases: nextPhase === undefined ? {} : { [itemID]: nextPhase },
959+
message: {
960+
id: itemID,
961+
phase: phase === undefined && state.message?.id === itemID ? state.message.phase : phase,
962+
},
974963
},
975964
events,
976965
]
@@ -985,6 +974,7 @@ const onOutputItemAdded = (state: ParserState, event: Event): StepResult => {
985974
reasoningItems: {
986975
...state.reasoningItems,
987976
[item.id]: {
977+
open: true,
988978
encryptedContent: item.encrypted_content,
989979
summaryParts: { 0: "active" },
990980
deltaIndexes: new Set(),
@@ -996,8 +986,6 @@ const onOutputItemAdded = (state: ParserState, event: Event): StepResult => {
996986
}
997987
if (item?.type !== "function_call" || !item.call_id) return [state, NO_EVENTS]
998988
const id = item.id ?? item.call_id
999-
// Pending tools always store the call id, so this also catches duplicates
1000-
// that disagree on whether `item.id` is present.
1001989
if (Object.values(state.tools).some((tool) => tool?.id === item.call_id) || state.completedTools.has(item.call_id))
1002990
return [state, NO_EVENTS]
1003991
const metadata = item.id !== undefined ? providerMetadata(state, { itemId: item.id }) : undefined
@@ -1026,7 +1014,7 @@ const onReasoningSummaryPartAdded = (state: ParserState, event: Event): StepResu
10261014
const onReasoningSummaryPartDone = (state: ParserState, event: Event): StepResult => {
10271015
if (event.item_id === undefined || event.summary_index === undefined) return [state, NO_EVENTS]
10281016
const item = state.reasoningItems[event.item_id]
1029-
if (!item) return [state, NO_EVENTS]
1017+
if (!item?.open) return [state, NO_EVENTS]
10301018
if (item.summaryParts[event.summary_index] !== "active") return [state, NO_EVENTS]
10311019
return [
10321020
{
@@ -1083,11 +1071,8 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
10831071

10841072
if (item.type === "message" && item.id !== undefined) {
10851073
const itemPhase = messagePhase(item.phase)
1086-
const phase = itemPhase === undefined ? state.messagePhases[item.id] : itemPhase
1074+
const phase = itemPhase === undefined && state.message?.id === item.id ? state.message.phase : itemPhase
10871075
const events: LLMEvent[] = []
1088-
const messageItems = new Set(state.messageItems)
1089-
messageItems.delete(item.id)
1090-
const { [item.id]: _phase, ...messagePhases } = state.messagePhases
10911076
return [
10921077
{
10931078
...state,
@@ -1097,8 +1082,7 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
10971082
item.id,
10981083
providerMetadata(state, { itemId: item.id, ...(phase === undefined ? {} : { phase }) }),
10991084
),
1100-
messageItems,
1101-
messagePhases,
1085+
message: state.message?.id === item.id ? undefined : state.message,
11021086
},
11031087
events,
11041088
] satisfies StepResult
@@ -1157,14 +1141,13 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
11571141
const metadata = reasoningMetadata(state, item)
11581142
const reasoningItem = state.reasoningItems[item.id]
11591143
if (reasoningItem) {
1144+
if (!reasoningItem.open) return [state, NO_EVENTS] satisfies StepResult
11601145
const lifecycle = Object.entries(reasoningItem.summaryParts)
11611146
.filter((entry) => entry[1] === "active" || entry[1] === "can-conclude")
11621147
.reduce(
11631148
(lifecycle, entry) => Lifecycle.reasoningEnd(lifecycle, events, `${item.id}:${entry[0]}`, metadata),
11641149
state.lifecycle,
11651150
)
1166-
// Keep the fully-concluded entry so duplicate or late events for this
1167-
// item remain no-ops instead of reopening lifecycle state.
11681151
return [
11691152
{
11701153
...state,
@@ -1173,10 +1156,8 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
11731156
...state.reasoningItems,
11741157
[item.id]: {
11751158
...reasoningItem,
1159+
open: false,
11761160
encryptedContent: item.encrypted_content ?? reasoningItem.encryptedContent,
1177-
summaryParts: Object.fromEntries(
1178-
Object.keys(reasoningItem.summaryParts).map((index) => [index, "concluded" as const]),
1179-
),
11801161
},
11811162
},
11821163
},
@@ -1194,6 +1175,7 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
11941175
reasoningItems: {
11951176
...state.reasoningItems,
11961177
[item.id]: {
1178+
open: false,
11971179
encryptedContent: item.encrypted_content,
11981180
summaryParts: { 0: "concluded" },
11991181
deltaIndexes: new Set(),
@@ -1223,7 +1205,7 @@ const onResponseFinish = Effect.fn("OpenResponses.onResponseFinish")(function* (
12231205
if (
12241206
id === undefined ||
12251207
((item.type !== "function_call" || !current.tools[id]) &&
1226-
(item.type !== "reasoning" || !current.reasoningItems[id]))
1208+
(item.type !== "reasoning" || !current.reasoningItems[id]?.open))
12271209
)
12281210
return Effect.succeed([current, events] satisfies StepResult)
12291211
return onOutputItemDone(current, { type: "response.output_item.done", item }).pipe(
@@ -1399,8 +1381,7 @@ export const initial = (request: LLMRequest, extension: Extension = BASE): Parse
13991381
completedTools: new Set<string>(),
14001382
lifecycle: Lifecycle.initial(),
14011383
outputItems: {},
1402-
messageItems: new Set<string>(),
1403-
messagePhases: {},
1384+
message: undefined,
14041385
reasoningItems: {},
14051386
})
14061387

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.