File size: 11,357 Bytes
94e1b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import { createLogger } from '../../utils/logger'
import { createStudioToolPart } from '../domain/factories'
import type {
  StudioAssistantMessage,
  StudioEventBus,
  StudioMessageStore,
  StudioPartStore,
  StudioProcessorStreamEvent,
  StudioRun,
  StudioSession,
  StudioToolPart,
  StudioToolResult
} from '../domain/types'
import { isDoomLoop } from './doom-loop'
import { StudioPartSynchronizer } from './part-synchronizer'
import { StudioTextStreamAccumulator } from './text-stream-accumulator'
import {
  getToolInput,
  getToolTimeStart,
  mergeToolMetadata,
  mergeToolStateMetadata
} from './tool-state'

const logger = createLogger('StudioRunProcessor')

export type StudioProcessorOutcome = 'continue' | 'stop' | 'compact'

interface StudioRunProcessorOptions {
  messageStore: StudioMessageStore
  partStore: StudioPartStore
}

export class StudioRunProcessor {
  private readonly partStore: StudioPartStore
  private readonly sync: StudioPartSynchronizer
  private readonly textStream: StudioTextStreamAccumulator

  constructor(options: StudioRunProcessorOptions) {
    this.partStore = options.partStore
    this.sync = new StudioPartSynchronizer(options.messageStore, options.partStore)
    this.textStream = new StudioTextStreamAccumulator(options.partStore, this.sync)
  }

  async processStream(input: {
    session: StudioSession
    run: StudioRun
    assistantMessage: StudioAssistantMessage
    events: AsyncIterable<StudioProcessorStreamEvent>
    eventBus?: StudioEventBus
    shouldCompact?: (usage?: { tokens?: number }, assistantMessage?: StudioAssistantMessage) => Promise<boolean>
    onDoomLoop?: (toolName: string, toolInput: Record<string, unknown>) => Promise<boolean>
  }): Promise<StudioProcessorOutcome> {
    const toolCalls = new Map<string, StudioToolPart>()
    let currentAssistantMessage = input.assistantMessage
    let activeTextPartId: string | null = null
    let activeTextValue = ''
    let activeReasoningPartId: string | null = null
    let blocked = false
    let needsCompaction = false

    for await (const event of input.events) {
      switch (event.type) {
        case 'assistant-message-start': {
          currentAssistantMessage = event.message
          activeTextPartId = null
          activeTextValue = ''
          activeReasoningPartId = null
          break
        }

        case 'tool-input-start': {
          input.eventBus?.publish({
            type: 'tool_input_start',
            sessionId: input.session.id,
            runId: input.run.id,
            toolName: event.toolName,
            callId: event.id,
            raw: event.raw
          })
          const part = createStudioToolPart({
            messageId: currentAssistantMessage.id,
            sessionId: currentAssistantMessage.sessionId,
            tool: event.toolName,
            callId: event.id,
            raw: event.raw
          })
          await this.sync.appendPart(currentAssistantMessage, part)
          toolCalls.set(event.id, part)
          break
        }

        case 'tool-call': {
          input.eventBus?.publish({
            type: 'tool_call',
            sessionId: input.session.id,
            runId: input.run.id,
            toolName: event.toolName,
            callId: event.toolCallId,
            input: event.input
          })
          const match = toolCalls.get(event.toolCallId)
          if (!match) {
            break
          }

          const allowed = await this.allowToolCall({
            assistantMessage: currentAssistantMessage,
            toolName: event.toolName,
            toolInput: event.input,
            onDoomLoop: input.onDoomLoop
          })

          if (!allowed) {
            blocked = true
            await this.updateToolState(match.id, {
              status: 'error',
              input: event.input,
              error: `Doom loop rejected for tool "${event.toolName}"`,
              time: { start: Date.now(), end: Date.now() }
            })
            toolCalls.delete(event.toolCallId)
            break
          }

          await this.updateToolState(match.id, {
            status: 'running',
            input: event.input,
            title: undefined,
            metadata: undefined,
            time: { start: Date.now() }
          })
          break
        }

        case 'tool-result': {
          input.eventBus?.publish({
            type: 'tool_result',
            sessionId: input.session.id,
            runId: input.run.id,
            toolName: toolCalls.get(event.toolCallId)?.tool ?? 'unknown',
            callId: event.toolCallId,
            status: 'completed',
            title: event.title,
            output: event.output,
            metadata: event.metadata,
            attachments: event.attachments
          })
          await this.completeToolCall(toolCalls, event)
          break
        }

        case 'tool-error': {
          input.eventBus?.publish({
            type: 'tool_result',
            sessionId: input.session.id,
            runId: input.run.id,
            toolName: toolCalls.get(event.toolCallId)?.tool ?? 'unknown',
            callId: event.toolCallId,
            status: 'failed',
            error: event.error,
            metadata: event.metadata
          })
          blocked = await this.failToolCall(toolCalls, event)
          break
        }

        case 'text-start': {
          activeTextValue = ''
          activeTextPartId = await this.textStream.startPart(currentAssistantMessage, 'text')
          break
        }

        case 'text-delta': {
          activeTextValue += event.text
          await this.textStream.appendDelta(activeTextPartId, event.text, 'text')
          break
        }

        case 'text-end': {
          const text = activeTextValue.trim()
          if (text) {
            input.eventBus?.publish({
              type: 'assistant_text',
              sessionId: input.session.id,
              runId: input.run.id,
              text
            })
          }
          activeTextPartId = null
          activeTextValue = ''
          break
        }

        case 'reasoning-start': {
          activeReasoningPartId = await this.textStream.startPart(currentAssistantMessage, 'reasoning')
          break
        }

        case 'reasoning-delta': {
          await this.textStream.appendDelta(activeReasoningPartId, event.text, 'reasoning')
          break
        }

        case 'reasoning-end': {
          activeReasoningPartId = null
          break
        }

        case 'finish-step': {
          if (!currentAssistantMessage.summary && input.shouldCompact) {
            needsCompaction = await input.shouldCompact(event.usage, currentAssistantMessage)
          }
          break
        }
      }
    }

    if (blocked) {
      return 'stop'
    }
    if (needsCompaction) {
      return 'compact'
    }
    return 'continue'
  }

  async applyToolMetadata(input: {
    assistantMessage: StudioAssistantMessage
    callId: string
    title?: string
    metadata?: Record<string, unknown>
  }): Promise<void> {
    const part = await this.findToolPart(input.assistantMessage, input.callId)
    if (!part) {
      return
    }

    await this.sync.updatePart(part.id, {
      ...part,
      metadata: {
        ...(part.metadata ?? {}),
        ...(input.metadata ?? {})
      },
      state: mergeToolStateMetadata(part.state, input.title, input.metadata)
    })
  }

  async materializeToolResult(input: {
    session: StudioSession
    run: StudioRun
    assistantMessage: StudioAssistantMessage
    callId: string
    toolName: string
    toolInput: Record<string, unknown>
    result: StudioToolResult
  }): Promise<void> {
    const part = createStudioToolPart({
      messageId: input.assistantMessage.id,
      sessionId: input.assistantMessage.sessionId,
      tool: input.toolName,
      callId: input.callId
    })
    const created = await this.sync.appendPart(input.assistantMessage, part)

    await this.updateToolState(created.id, {
      status: 'completed',
      input: input.toolInput,
      output: input.result.output,
      title: input.result.title,
      metadata: input.result.metadata,
      attachments: input.result.attachments,
      time: { start: Date.now(), end: Date.now() }
    })

    logger.info('Materialized direct tool result into assistant message', {
      sessionId: input.session.id,
      runId: input.run.id,
      toolName: input.toolName,
      callId: input.callId
    })
  }

  private async allowToolCall(input: {
    assistantMessage: StudioAssistantMessage
    toolName: string
    toolInput: Record<string, unknown>
    onDoomLoop?: (toolName: string, toolInput: Record<string, unknown>) => Promise<boolean>
  }): Promise<boolean> {
    if (!input.onDoomLoop) {
      return true
    }

    const doomLoop = await isDoomLoop({
      assistantMessage: input.assistantMessage,
      partStore: this.partStore,
      toolName: input.toolName,
      toolInput: input.toolInput
    })

    return doomLoop ? input.onDoomLoop(input.toolName, input.toolInput) : true
  }

  private async completeToolCall(
    toolCalls: Map<string, StudioToolPart>,
    event: Extract<StudioProcessorStreamEvent, { type: 'tool-result' }>
  ): Promise<void> {
    const match = toolCalls.get(event.toolCallId)
    if (!match) {
      return
    }

    const runningState = await this.partStore.getById(match.id)
    await this.updateToolState(match.id, {
      status: 'completed',
      input: getToolInput(runningState),
      output: event.output,
      title: event.title ?? `Completed ${match.tool}`,
      metadata: mergeToolMetadata(runningState, event.metadata),
      attachments: event.attachments,
      time: {
        start: getToolTimeStart(runningState),
        end: Date.now()
      }
    })
    toolCalls.delete(event.toolCallId)
  }

  private async failToolCall(
    toolCalls: Map<string, StudioToolPart>,
    event: Extract<StudioProcessorStreamEvent, { type: 'tool-error' }>
  ): Promise<boolean> {
    const match = toolCalls.get(event.toolCallId)
    if (!match) {
      return false
    }

    const runningState = await this.partStore.getById(match.id)
    await this.updateToolState(match.id, {
      status: 'error',
      input: getToolInput(runningState),
      error: event.error,
      metadata: mergeToolMetadata(runningState, event.metadata),
      time: {
        start: getToolTimeStart(runningState),
        end: Date.now()
      }
    })
    toolCalls.delete(event.toolCallId)
    return event.metadata?.recoverable !== true
  }

  private async findToolPart(
    assistantMessage: StudioAssistantMessage,
    callId: string
  ): Promise<StudioToolPart | null> {
    const parts = await this.partStore.listByMessageId(assistantMessage.id)
    const part = [...parts]
      .reverse()
      .find((candidate) => candidate.type === 'tool' && candidate.callId === callId)

    return part?.type === 'tool' ? part : null
  }

  private async updateToolState(partId: string, state: StudioToolPart['state']): Promise<void> {
    const current = await this.partStore.getById(partId)
    if (!current || current.type !== 'tool') {
      return
    }

    await this.sync.updatePart(partId, {
      ...current,
      state,
      metadata: mergeToolMetadata(current, 'metadata' in state ? state.metadata : undefined)
    })
  }
}