File size: 3,567 Bytes
6cda6d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createStudioOpenAIToolLoop } from '../../../orchestration/openai-tool-loop/controller'
import { readRunElapsedMs } from '../../../infrastructure/telemetry/studio-telemetry'
import { recordTokenUsage } from '../../../../access'
import type { CustomApiConfig } from '../../../../types'
import type { StudioModelPort } from '../../../model/studio-model-port'
import type { StudioToolChoice } from '../../../domain/types'
import type { StudioPreparedRunContext, StudioPreparedRunExecution, StudioSessionRunnerDependencies } from './dependency-center'

export function createAgentLoopExecution(
  deps: StudioSessionRunnerDependencies,
  input: {
    prepared: StudioPreparedRunContext
    customApiConfig?: CustomApiConfig
    modelPort?: StudioModelPort
    toolChoice?: StudioToolChoice
    abortSignal: AbortSignal
  },
): StudioPreparedRunExecution {
  return {
    startLog: {
      event: 'loop.started',
      payload: {
        sessionId: input.prepared.input.session.id,
        runId: input.prepared.run.id,
        model: input.customApiConfig?.model ?? 'studio-port',
        toolChoice: input.toolChoice ?? null,
        runElapsedMs: readRunElapsedMs(input.prepared.run),
      }
    },
    events: createStudioOpenAIToolLoop({
      projectId: input.prepared.input.projectId,
      session: input.prepared.input.session,
      run: input.prepared.run,
      assistantMessage: input.prepared.assistantMessage,
      inputText: input.prepared.input.inputText,
      messageStore: deps.messageStore,
      registry: deps.registry,
      eventBus: input.prepared.eventBus,
      renderStore: deps.renderStore,
      renderContext: input.prepared.renderContext,
      executionScope: input.prepared.executionScope,
      // The Run scope is copied explicitly: a later message created inside the loop (compaction,
      // new step) must never fall back to the Legacy whole-Session scope.
      createAssistantMessage: () => deps.createAssistantMessage(
        input.prepared.input.session,
        input.prepared.run.id,
        input.prepared.run.sceneId
      ),
      setToolMetadata: (assistantMessage, callId, metadata) => {
        void deps.processor.applyToolMetadata({
          assistantMessage,
          callId,
          title: metadata.title,
          metadata: metadata.metadata
        })
      },
      customApiConfig: input.customApiConfig,
      modelPort: input.modelPort,
      toolChoice: input.toolChoice,
      abortSignal: input.abortSignal,
      onCheckpoint: async (patch) => {
        const nextRun = deps.runStore
          ? await deps.runStore.update(input.prepared.run.ownerId, input.prepared.run.id, patch) ?? { ...input.prepared.run, ...patch }
          : { ...input.prepared.run, ...patch }
        input.prepared.run = nextRun
        input.prepared.eventBus.publish({
          type: 'run_updated',
          sessionId: input.prepared.input.session.id,
          run: nextRun
        })

        // The checkpoint that persists `token_usage` onto the Run also writes the CatKey ledger, so
        // the two can never disagree about how much this Run has spent. Step-boundary checkpoints
        // carry metadata only and are skipped. BYOK runs have no catKeyId and write nothing.
        if (patch.tokenUsage) {
          await recordTokenUsage({
            catKeyId: input.prepared.input.catKeyId,
            model: input.customApiConfig?.model ?? '',
            sourceKind: 'studio_run',
            sourceId: nextRun.id,
            totals: patch.tokenUsage
          })
        }
      }
    })
  }
}