File size: 6,755 Bytes
af37c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type {
  AgentId,
  DemoRunResult,
  DemoScenarioCatalog,
  DemoStreamDoneEvent,
  DemoStreamMetaEvent,
  SimResult,
  CompareResult,
  TaskInfo,
  SimStep,
  StreamDoneEvent,
  StreamMetaEvent,
  StreamStageEvent,
} from '../types'

const PROD = import.meta.env.PROD
const devEnvBase = import.meta.env.VITE_API_URL?.trim()
const normalizedDevEnvBase = devEnvBase ? devEnvBase.replace(/\/+$/, '') : ''
const BASE = PROD ? '/api' : normalizedDevEnvBase || 'http://localhost:8001'

export class ApiError extends Error {
  status: number
  body: string
  url: string

  constructor(status: number, body: string, url: string, message: string) {
    super(message)
    this.name = 'ApiError'
    this.status = status
    this.body = body
    this.url = url
  }
}

function buildUrl(path: string): string {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return `${BASE}${normalizedPath}`
}

async function request<T>(path: string, options?: RequestInit): Promise<T> {
  const url = buildUrl(path)

  try {
    const res = await fetch(url, options)
    if (!res.ok) {
      const err = await res.text()
      throw new ApiError(res.status, err, url, `API error ${res.status}: ${err}`)
    }
    return res.json() as Promise<T>
  } catch (error) {
    if (error instanceof ApiError) {
      throw error
    }
    const message = error instanceof Error ? error.message : String(error)
    throw new ApiError(0, message, url, `Network error: ${message}`)
  }
}

export function getApiInfo() {
  return {
    base: BASE,
    mode: PROD ? 'proxy' : normalizedDevEnvBase ? 'direct' : 'local',
    env: PROD ? '(disabled in production)' : normalizedDevEnvBase || '(not set)',
  } as const
}

export async function fetchTasks(): Promise<TaskInfo[]> {
  const data = await request<{ tasks: TaskInfo[] }>('/tasks')
  return data.tasks
}

export async function simulate(
  taskId: string,
  agent: AgentId = 'greedy',
): Promise<SimResult> {
  return request<SimResult>(`/simulate/${taskId}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ agent }),
  })
}

export async function compare(taskId: string): Promise<CompareResult> {
  return request<CompareResult>(`/compare/${taskId}`, { method: 'POST' })
}

export async function analyzeScenario(scenario: string): Promise<{strategy: string}> {
  return request<{strategy: string}>('/analyze_scenario', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ scenario }),
  })
}

type StreamCallbacks = {
  onMeta: (event: StreamMetaEvent) => void
  onStage: (event: StreamStageEvent) => void
  onStep: (step: SimStep) => void
  onDone: (event: StreamDoneEvent) => void
  onError: (message: string) => void
}

function buildEventSourceUrl(path: string): string {
  if (BASE.startsWith('http://') || BASE.startsWith('https://')) {
    return `${BASE}${path}`
  }
  if (typeof window !== 'undefined') {
    return `${window.location.origin}${BASE}${path}`
  }
  return `${BASE}${path}`
}

export function buildSseUrl(taskId: string, agent: AgentId): string {
  const streamPath = `/simulate/stream/${taskId}?agent=${encodeURIComponent(agent)}`
  return buildEventSourceUrl(streamPath)
}

export async function fetchDemoScenarios(): Promise<DemoScenarioCatalog> {
  return request<DemoScenarioCatalog>('/demo/scenarios')
}

export async function runDemoScenario(
  scenarioId: string,
  agent: AgentId = 'ai_4stage',
): Promise<DemoRunResult> {
  return request<DemoRunResult>(`/demo/run/${scenarioId}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ agent }),
  })
}

type DemoStreamCallbacks = {
  onMeta: (event: DemoStreamMetaEvent) => void
  onStage: (event: StreamStageEvent) => void
  onStep: (step: DemoRunResult['steps'][number]) => void
  onDone: (event: DemoStreamDoneEvent) => void
  onError: (message: string) => void
}

export function buildDemoSseUrl(scenarioId: string, agent: AgentId): string {
  const streamPath = `/demo/stream/${scenarioId}?agent=${encodeURIComponent(agent)}`
  return buildEventSourceUrl(streamPath)
}

export function streamDemoScenario(
  scenarioId: string,
  agent: AgentId,
  callbacks: DemoStreamCallbacks,
): () => void {
  const url = buildDemoSseUrl(scenarioId, agent)
  const source = new EventSource(url)

  source.addEventListener('meta', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as DemoStreamMetaEvent
    callbacks.onMeta(data)
  })

  source.addEventListener('stage', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as StreamStageEvent
    callbacks.onStage(data)
  })

  source.addEventListener('step', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as DemoRunResult['steps'][number]
    callbacks.onStep(data)
  })

  source.addEventListener('done', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as DemoStreamDoneEvent
    callbacks.onDone(data)
    source.close()
  })

  source.addEventListener('error', (event) => {
    const payload = (event as MessageEvent).data
    if (payload) {
      try {
        const parsed = JSON.parse(payload) as { detail?: string }
        callbacks.onError(parsed.detail || payload)
      } catch {
        callbacks.onError(payload)
      }
    } else {
      callbacks.onError(`SSE stream failed (${url})`)
    }
    source.close()
  })

  return () => source.close()
}

export function streamSimulation(
  taskId: string,
  agent: AgentId,
  callbacks: StreamCallbacks,
): () => void {
  const url = buildSseUrl(taskId, agent)
  const source = new EventSource(url)
 
  source.addEventListener('meta', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as StreamMetaEvent
    callbacks.onMeta(data)
  })
 
  source.addEventListener('stage', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as StreamStageEvent
    callbacks.onStage(data)
  })
 
  source.addEventListener('step', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as SimStep
    callbacks.onStep(data)
  })
 
  source.addEventListener('done', (event) => {
    const data = JSON.parse((event as MessageEvent).data) as StreamDoneEvent
    callbacks.onDone(data)
    source.close()
  })
 
  source.addEventListener('error', (event) => {
    const payload = (event as MessageEvent).data
    if (payload) {
      try {
        const parsed = JSON.parse(payload) as { detail?: string }
        callbacks.onError(parsed.detail || payload)
      } catch {
        callbacks.onError(payload)
      }
    } else {
      callbacks.onError(`SSE stream failed (${url})`)
    }
    source.close()
  })
 
  return () => source.close()
}