File size: 7,314 Bytes
5433b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from 'node:crypto'
import { createStudioWorkResult } from '../../domain/factories'
import type { StudioFileAttachment, StudioToolDefinition, StudioToolResult, StudioWorkResult } from '../../domain/types'
import type { StudioRuntimeBackedToolContext } from '../../runtime/tool-runtime-context'
import { createWorkAndTask, publishWorkUpdated, updateTaskAndWork } from '../../works/work-lifecycle'
import { executeMatplotlibRender } from '../../../services/plot-runtime/matplotlib-executor'

interface PlotRenderToolInput {
  concept: string
  code: string
}

export function createPlotStudioRenderTool(): StudioToolDefinition<PlotRenderToolInput> {
  return {
    name: 'render',
    description: 'Execute matplotlib code and persist static plot outputs for preview.',
    category: 'render',
    permission: 'render',
    allowedAgents: ['builder'],
    allowedStudioKinds: ['plot'],
    requiresTask: true,
    execute: async (input, context) => executePlotRenderTool(input, context as StudioRuntimeBackedToolContext)
  }
}

async function executePlotRenderTool(
  input: PlotRenderToolInput,
  context: StudioRuntimeBackedToolContext
): Promise<StudioToolResult> {
  if (!input.concept?.trim() || !input.code?.trim()) {
    throw new Error('Render tool requires non-empty "concept" and "code"')
  }

  const renderId = `plot_${randomUUID()}`
  const title = `Plot render: ${input.concept.slice(0, 80)}`
  const lifecycleMetadata = {
    renderId,
    concept: input.concept,
    studioKind: 'plot',
    outputMode: 'image'
  }

  const { work, task } = await createWorkAndTask({
    context,
    work: {
      sessionId: context.session.id,
      runId: context.run.id,
      type: 'plot',
      title,
      status: 'running',
      metadata: lifecycleMetadata
    },
    task: {
      sessionId: context.session.id,
      runId: context.run.id,
      type: 'render',
      status: 'running',
      title,
      detail: input.concept,
      metadata: lifecycleMetadata
    },
    workMetadata: lifecycleMetadata
  })

  context.setToolMetadata?.({
    title,
    metadata: {
      renderId,
      workId: work?.id,
      taskId: task?.id,
      studioKind: 'plot'
    }
  })

  try {
    const execution = await executeMatplotlibRender({
      workspaceDirectory: context.session.directory,
      renderId,
      code: input.code
    })

    const workResult = await persistWorkResult({
      context,
      workId: work?.id,
      taskId: task?.id,
      renderId,
      code: input.code,
      codeLanguage: 'python',
      execution,
    })

    const completed = await updateTaskAndWork({
      context,
      task,
      work,
      taskPatch: {
        status: 'completed',
        metadata: {
          ...(task?.metadata ?? {}),
          ...lifecycleMetadata,
          result: {
            status: 'completed',
            timestamp: Date.now(),
            data: {
              outputMode: 'image',
              imageUrls: execution.imageDataUris,
              imageCount: execution.imageDataUris.length,
              workspaceImagePaths: execution.imagePaths,
              code: input.code,
              codeLanguage: 'python',
              usedAI: true,
              quality: 'medium',
              generationType: 'studio-plot'
            }
          }
        }
      },
      workMetadata: {
        ...lifecycleMetadata,
        currentResultId: workResult?.id,
        workspaceImagePaths: execution.imagePaths,
        scriptPath: execution.scriptPath
      }
    })

    if (workResult && completed.work && context.workStore) {
      const updatedWork = await context.workStore.update(completed.work.id, {
        currentResultId: workResult.id,
        metadata: {
          ...(completed.work.metadata ?? {}),
          currentResultId: workResult.id,
          workspaceImagePaths: execution.imagePaths,
          scriptPath: execution.scriptPath
        }
      })
      publishWorkUpdated(context, updatedWork ?? completed.work)
    }

    return {
      title,
      output: `plot_render_id: ${renderId}`,
      attachments: buildAttachments(execution.imageDataUris),
      metadata: {
        renderId,
        taskId: completed.task?.id ?? task?.id,
        workId: completed.work?.id ?? work?.id,
        workResultId: workResult?.id,
        imageCount: execution.imageDataUris.length,
        scriptPath: execution.scriptPath,
        workspaceImagePaths: execution.imagePaths
      }
    }
  } catch (error) {
    await persistFailureResult({
      context,
      workId: work?.id,
      taskId: task?.id,
      renderId,
      error: error instanceof Error ? error.message : String(error)
    })

    await updateTaskAndWork({
      context,
      task,
      work,
      taskPatch: {
        status: 'failed',
        metadata: {
          ...(task?.metadata ?? {}),
          ...lifecycleMetadata,
          error: error instanceof Error ? error.message : String(error)
        }
      },
      workMetadata: {
        ...lifecycleMetadata,
        error: error instanceof Error ? error.message : String(error)
      }
    })

    throw error
  }
}

async function persistWorkResult(input: {
  context: StudioRuntimeBackedToolContext
  workId?: string
  taskId?: string
  renderId: string
  code: string
  codeLanguage: 'python'
  execution: Awaited<ReturnType<typeof executeMatplotlibRender>>
}): Promise<StudioWorkResult | null> {
  if (!input.workId || !input.context.workResultStore) {
    return null
  }

  const result = await input.context.workResultStore.create(createStudioWorkResult({
    workId: input.workId,
    kind: 'render-output',
    summary: `Plot render completed with ${input.execution.imageDataUris.length} image output(s)`,
    attachments: buildAttachments(input.execution.imageDataUris),
    metadata: {
      taskId: input.taskId,
      renderId: input.renderId,
      studioKind: 'plot',
      code: input.code,
      codeLanguage: input.codeLanguage,
      imageCount: input.execution.imageDataUris.length,
      workspaceImagePaths: input.execution.imagePaths,
      scriptPath: input.execution.scriptPath,
      stdout: input.execution.stdout,
      stderr: input.execution.stderr
    }
  }))

  input.context.eventBus.publish({
    type: 'work_result_updated',
    sessionId: input.context.session.id,
    runId: input.context.run.id,
    result
  })

  return result
}

async function persistFailureResult(input: {
  context: StudioRuntimeBackedToolContext
  workId?: string
  taskId?: string
  renderId: string
  error: string
}): Promise<void> {
  if (!input.workId || !input.context.workResultStore) {
    return
  }

  const result = await input.context.workResultStore.create(createStudioWorkResult({
    workId: input.workId,
    kind: 'failure-report',
    summary: input.error,
    metadata: {
      taskId: input.taskId,
      renderId: input.renderId,
      studioKind: 'plot',
      error: input.error
    }
  }))

  input.context.eventBus.publish({
    type: 'work_result_updated',
    sessionId: input.context.session.id,
    runId: input.context.run.id,
    result
  })
}

function buildAttachments(imageDataUris: string[]): StudioFileAttachment[] {
  return imageDataUris.map((path, index) => ({
    kind: 'file',
    path,
    name: `plot_${index + 1}.png`,
    mimeType: 'image/png'
  }))
}