-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.ts
More file actions
211 lines (187 loc) · 6.33 KB
/
Copy pathstrategy.ts
File metadata and controls
211 lines (187 loc) · 6.33 KB
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
import type { CopilotClient } from '~/clients'
import type { CapiRequestContext } from '~/core/capi'
import type { ExecutionStrategy, SSEStreamChunk } from '~/lib/execution-strategy'
import type { ResponsesPayload, ResponsesResult } from '~/types'
import { mkdir, readdir, unlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import consola from 'consola'
import { HTTPError } from '~/lib/error'
import { passthroughSSEChunk } from '~/lib/execution-strategy'
import { PATHS } from '~/lib/paths'
import { runtimeStore } from '~/state'
import { isAsyncIterable } from '~/util/async-iterable'
interface StreamIdState {
responseId?: string
itemIdsByOutputIndex: Map<number, string>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
function fixStreamIds(
rawData: string,
eventName: string | undefined,
state: StreamIdState,
): string {
if (!rawData) {
return rawData
}
let parsed: Record<string, unknown>
try {
parsed = JSON.parse(rawData) as Record<string, unknown>
}
catch {
return rawData
}
const response = isRecord(parsed.response) ? parsed.response : undefined
if (typeof response?.id === 'string') {
if (!state.responseId) {
state.responseId = response.id
}
else if (response.id !== state.responseId) {
response.id = state.responseId
}
}
if (eventName === 'response.output_item.added' || eventName === 'response.output_item.done') {
const outputIndex = typeof parsed.output_index === 'number' ? parsed.output_index : undefined
const item = isRecord(parsed.item) ? parsed.item : undefined
if (outputIndex !== undefined && typeof item?.id === 'string') {
const stableId = state.itemIdsByOutputIndex.get(outputIndex)
if (!stableId) {
state.itemIdsByOutputIndex.set(outputIndex, item.id)
}
else if (item.id !== stableId) {
item.id = stableId
}
}
}
if (typeof parsed.output_index === 'number' && typeof parsed.item_id === 'string') {
const stableId = state.itemIdsByOutputIndex.get(parsed.output_index)
if (stableId && parsed.item_id !== stableId) {
parsed.item_id = stableId
}
}
return JSON.stringify(parsed)
}
export function createResponsesPassthroughStrategy(
copilotClient: CopilotClient,
payload: ResponsesPayload,
options: {
vision: boolean
initiator: 'user' | 'agent'
requestContext: Partial<CapiRequestContext>
signal: AbortSignal
mapResponse?: (response: ResponsesResult) => ResponsesResult
onTerminalResponse?: (response: ResponsesResult) => void
onStreamEndWithoutTerminal?: () => void
},
): ExecutionStrategy<ResponsesResult | AsyncIterable<SSEStreamChunk>, SSEStreamChunk> {
const tracker: StreamIdState = { itemIdsByOutputIndex: new Map() }
let terminalResponseSeen = false
return {
async execute() {
try {
return await copilotClient.createResponses(payload, options) as ResponsesResult | AsyncIterable<SSEStreamChunk>
}
catch (error) {
if (runtimeStore.dumpFailedPayloads && error instanceof HTTPError && error.status === 400) {
dumpFailedPayload(payload, error).catch(() => {})
}
throw error
}
},
isStream(result): result is AsyncIterable<SSEStreamChunk> {
return Boolean(payload.stream) && isAsyncIterable(result)
},
translateResult(result) {
const response = result as ResponsesResult
const mapped = options.mapResponse ? options.mapResponse(response) : response
// The callback combines metadata observation with optional emulator
// persistence. It remains synchronous and process-local.
options.onTerminalResponse?.(mapped)
return mapped
},
translateStreamChunk(chunk) {
const fixedData = fixStreamIds(chunk.data ?? '', chunk.event, tracker)
const mappedData = options.mapResponse
? mapChunkResponse(fixedData, options.mapResponse)
: fixedData
const parsedResponse = tryExtractTerminalResponse(mappedData)
if (parsedResponse) {
terminalResponseSeen = true
options.onTerminalResponse?.(parsedResponse)
}
return passthroughSSEChunk(chunk, mappedData)
},
onStreamDone() {
if (!terminalResponseSeen)
options.onStreamEndWithoutTerminal?.()
return null
},
}
}
function mapChunkResponse(
rawData: string,
mapResponse: (response: ResponsesResult) => ResponsesResult,
): string {
if (!rawData) {
return rawData
}
try {
const parsed = JSON.parse(rawData) as Record<string, unknown>
if (isRecord(parsed.response)) {
parsed.response = mapResponse(parsed.response as unknown as ResponsesResult)
return JSON.stringify(parsed)
}
}
catch {
}
return rawData
}
function tryExtractTerminalResponse(rawData: string): ResponsesResult | undefined {
if (!rawData) {
return undefined
}
try {
const parsed = JSON.parse(rawData) as Record<string, unknown>
if (
parsed.type !== 'response.completed'
&& parsed.type !== 'response.incomplete'
&& parsed.type !== 'response.failed'
) {
return undefined
}
const response = parsed.response
if (response && typeof response === 'object') {
return response as unknown as ResponsesResult
}
}
catch {
}
return undefined
}
const MAX_DUMPS = 20
const TIMESTAMP_CHARS_RE = /[:.]/g
const DUMP_FILE_RE = /^\d{3}-/
async function dumpFailedPayload(payload: unknown, error: HTTPError): Promise<void> {
try {
const dumpDir = join(PATHS.APP_DIR, 'dumps')
await mkdir(dumpDir, { recursive: true, mode: 0o700 })
const now = new Date().toISOString()
const ts = now.replace(TIMESTAMP_CHARS_RE, '-')
const file = join(dumpDir, `${error.status}-${ts}.json`)
await writeFile(file, JSON.stringify({
timestamp: now,
error: { status: error.status, message: error.message },
payload,
}, null, 2), { mode: 0o600 })
consola.warn(`Dumped failed /responses payload → ${file}`)
const files = await readdir(dumpDir)
const dumps = files.filter(f => DUMP_FILE_RE.test(f) && f.endsWith('.json')).sort()
if (dumps.length > MAX_DUMPS) {
await Promise.all(dumps.slice(0, dumps.length - MAX_DUMPS).map(f => unlink(join(dumpDir, f)).catch(() => {})))
}
}
catch {
// Never let dump logic affect the request
}
}