Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

responses-user-tools.ts

478 lines13.9 KB

1import type {
2 ComputerActionList,
3 ResponseComputerToolCall,
4 ResponseComputerToolCallOutputScreenshot,
5 ResponseInputItem,
6} from 'openai/resources/responses/responses'
7​
8/**
9 * OpenAI Responses tools the app must run.
10 * A container `shell` runs on the provider. `apply_patch`, `local_shell`,
11 * `computer`, `computer_use_preview`, and `shell` with
12 * `environment.type: "local"` (or no environment) do not.
13 */
14export type OpenAIUserToolName =
15 | 'shell'
16 | 'apply_patch'
17 | 'local_shell'
18 | OpenAIComputerToolName
19​
20/** The names of the computer tool: its two tool types. */
21export type OpenAIComputerToolName = 'computer' | 'computer_use_preview'
22​
23export interface OpenAIUserExecutedCall {
24 name: OpenAIUserToolName
25 callId: string
26 itemId?: string
27 input: Record<string, unknown>
28 maxOutputLength?: number | null
30​
31interface ToolCallLike {
32 id: string
33 function: { name: string; arguments: string }
34 metadata?: unknown
36​
37function isRecord(value: unknown): value is Record<string, unknown> {
38 return typeof value === 'object' && value !== null && !Array.isArray(value)
40​
41function stringList(value: unknown): Array<string> | null {
42 if (
43 !Array.isArray(value) ||
44 !value.every((entry) => typeof entry === 'string')
45 ) {
46 return null
47 }
48 return value
50​
51function stringEnv(value: unknown): Record<string, string> {
52 if (!isRecord(value)) return {}
53 const env: Record<string, string> = {}
54 for (const [key, entry] of Object.entries(value)) {
55 if (typeof entry === 'string') env[key] = entry
56 }
57 return env
59​
60function nullableNumber(value: unknown): number | null {
61 return typeof value === 'number' || value === null ? value : null
63​
64/**
65 * Hosted shell calls already include a `shell_call_output` in the same
66 * response. Those call ids must not pause the app for another run.
67 */
68export function hostedShellCallIds(
69 output: ReadonlyArray<unknown>,
70): Set<string> {
71 const ids = new Set<string>()
72 for (const item of output) {
73 if (
74 isRecord(item) &&
75 item.type === 'shell_call_output' &&
76 typeof item.call_id === 'string'
77 ) {
78 ids.add(item.call_id)
79 }
80 }
81 return ids
83​
84export function readUserToolName(metadata: unknown): OpenAIUserToolName | null {
85 if (!isRecord(metadata)) return null
86 const name = metadata.openaiUserTool
87 if (
88 name === 'shell' ||
89 name === 'apply_patch' ||
90 name === 'local_shell' ||
91 name === 'computer' ||
92 name === 'computer_use_preview'
93 ) {
94 return name
95 }
96 return null
98​
99/**
100 * A computer action. It goes back to the API as the model sent it, so only
101 * its `type` is checked.
102 */
103function isComputerAction(
104 value: unknown,
105): value is NonNullable<ResponseComputerToolCall['action']> {
106 return isRecord(value) && typeof value.type === 'string'
108​
109/** The batched actions of a computer call. */
110function isComputerActionList(value: unknown): value is ComputerActionList {
111 return (
112 Array.isArray(value) &&
113 value.every((action) => isRecord(action) && typeof action.type === 'string')
114 )
116​
117/**
118 * The safety checks of a computer call, with only their known fields.
119 *
120 * - No list (`undefined` or `null` input): returns `[]`. There are no checks.
121 * - A list that does not parse: returns `null`. Do not turn that into `[]`.
122 * An unreadable check must stay visible so the tool can refuse it.
123 */
124function safetyChecks(
125 value: unknown,
126): Array<ResponseComputerToolCall.PendingSafetyCheck> | null {
127 if (value == null) return []
128 if (!Array.isArray(value)) return null
129 const checks: Array<ResponseComputerToolCall.PendingSafetyCheck> = []
130 for (const check of value) {
131 if (!isRecord(check) || typeof check.id !== 'string') return null
132 checks.push({
133 id: check.id,
134 ...(typeof check.code === 'string' ? { code: check.code } : {}),
135 ...(typeof check.message === 'string' ? { message: check.message } : {}),
136 })
137 }
138 return checks
140​
141function readItemId(metadata: unknown): string | undefined {
142 if (!isRecord(metadata)) return undefined
143 return typeof metadata.itemId === 'string' && metadata.itemId.length > 0
144 ? metadata.itemId
145 : undefined
147​
148function readMaxOutputLength(metadata: unknown): number | null | undefined {
149 if (!isRecord(metadata)) return undefined
150 const value = metadata.maxOutputLength
151 return typeof value === 'number' || value === null ? value : undefined
153​
154function applyPatchOperation(
155 value: unknown,
156):
157 | { type: 'create_file'; path: string; diff: string }
158 | { type: 'update_file'; path: string; diff: string }
159 | { type: 'delete_file'; path: string }
160 | null {
161 if (!isRecord(value) || typeof value.path !== 'string') return null
162 if (value.type === 'delete_file') {
163 return { type: 'delete_file', path: value.path }
164 }
165 if (
166 (value.type === 'create_file' || value.type === 'update_file') &&
167 typeof value.diff === 'string'
168 ) {
169 return { type: value.type, path: value.path, diff: value.diff }
170 }
171 return null
173​
174/**
175 * Read a user-run Responses output item.
176 * `bareShell` is true only once the full response is known. A shell call
177 * with no environment waits for that pass, so a hosted call that later
178 * carries `shell_call_output` is not asked of the app.
179 * `computerTool` is the name of the computer tool of the request. A
180 * `computer_call` is a call to it.
181 */
182export function readUserExecutedCall(
183 item: unknown,
184 options: { bareShell: boolean; computerTool?: OpenAIComputerToolName },
185): OpenAIUserExecutedCall | null {
186 if (!isRecord(item) || typeof item.type !== 'string') return null
187 const callId = typeof item.call_id === 'string' ? item.call_id : ''
188 const itemId = typeof item.id === 'string' ? item.id : undefined
189​
190 if (item.type === 'apply_patch_call') {
191 const operation = applyPatchOperation(item.operation)
192 if (!callId || !operation) return null
193 return {
194 name: 'apply_patch',
195 callId,
196 ...(itemId ? { itemId } : {}),
197 input: { operation },
198 }
199 }
200​
201 if (item.type === 'computer_call') {
202 const { action, actions } = item
203 const hasAction = isComputerAction(action)
204 const hasActions = isComputerActionList(actions)
205 if (!callId || (!hasAction && !hasActions)) return null
206 const checks = safetyChecks(item.pending_safety_checks)
207 return {
208 name: options.computerTool ?? 'computer_use_preview',
209 callId,
210 ...(itemId ? { itemId } : {}),
211 input: {
212 ...(hasAction ? { action } : {}),
213 ...(hasActions ? { actions } : {}),
214 // Keep a list that did not parse. The computer tool refuses it.
215 pending_safety_checks: checks ?? item.pending_safety_checks,
216 },
217 }
218 }
219​
220 if (item.type === 'local_shell_call') {
221 if (!isRecord(item.action)) return null
222 const command = stringList(item.action.command)
223 if (!callId || !command || command.length === 0) return null
224 return {
225 name: 'local_shell',
226 callId,
227 ...(itemId ? { itemId } : {}),
228 input: item.action,
229 }
230 }
231​
232 if (item.type !== 'shell_call') return null
233 const environment = item.environment
234 if (isRecord(environment)) {
235 if (environment.type !== 'local') return null
236 } else if (!options.bareShell) {
237 return null
238 }
239 if (!callId || !isRecord(item.action)) return null
240 const commands = stringList(item.action.commands)
241 if (!commands || commands.length === 0) return null
242 const maxOutputLength = nullableNumber(item.action.max_output_length)
243 return {
244 name: 'shell',
245 callId,
246 ...(itemId ? { itemId } : {}),
247 input: {
248 commands,
249 max_output_length: maxOutputLength,
250 timeout_ms: nullableNumber(item.action.timeout_ms),
251 },
252 maxOutputLength,
253 }
255​
256function parseArguments(argumentsString: string): Record<string, unknown> {
257 try {
258 const parsed: unknown = JSON.parse(argumentsString)
259 return isRecord(parsed) ? parsed : {}
260 } catch {
261 return {}
262 }
264​
265function parseContent(content: unknown): unknown {
266 if (typeof content !== 'string') return content
267 try {
268 return JSON.parse(content) as unknown
269 } catch {
270 return content
271 }
273​
274/** Replay a user-run tool call as the Responses input item OpenAI expects. */
275export function userToolRequestItem(
276 toolCall: ToolCallLike,
277): ResponseInputItem | null {
278 const name = readUserToolName(toolCall.metadata)
279 if (!name) return null
280 const args = parseArguments(toolCall.function.arguments)
281 const itemId = readItemId(toolCall.metadata)
282​
283 if (name === 'apply_patch') {
284 const operation = applyPatchOperation(args.operation)
285 if (!operation) return null
286 return {
287 type: 'apply_patch_call',
288 call_id: toolCall.id,
289 status: 'completed',
290 operation,
291 ...(itemId ? { id: itemId } : {}),
292 }
293 }
294​
295 if (name === 'local_shell') {
296 const command = stringList(args.command)
297 if (!command) return null
298 return {
299 type: 'local_shell_call',
300 id: itemId ?? toolCall.id,
301 call_id: toolCall.id,
302 status: 'completed',
303 action: {
304 type: 'exec',
305 command,
306 env: stringEnv(args.env),
307 timeout_ms: nullableNumber(args.timeout_ms),
308 ...(typeof args.user === 'string' || args.user === null
309 ? { user: args.user }
310 : {}),
311 ...(typeof args.working_directory === 'string' ||
312 args.working_directory === null
313 ? { working_directory: args.working_directory }
314 : {}),
315 },
316 }
317 }
318​
319 if (name === 'computer' || name === 'computer_use_preview') {
320 const { action, actions } = args
321 const hasAction = isComputerAction(action)
322 const hasActions = isComputerActionList(actions)
323 if (!hasAction && !hasActions) return null
324 return {
325 type: 'computer_call',
326 id: itemId ?? toolCall.id,
327 call_id: toolCall.id,
328 status: 'completed',
329 ...(hasAction ? { action } : {}),
330 ...(hasActions ? { actions } : {}),
331 pending_safety_checks: safetyChecks(args.pending_safety_checks) ?? [],
332 }
333 }
334​
335 const commands = stringList(args.commands)
336 if (!commands) return null
337 return {
338 type: 'shell_call',
339 call_id: toolCall.id,
340 status: 'completed',
341 action: {
342 commands,
343 max_output_length: nullableNumber(args.max_output_length),
344 timeout_ms: nullableNumber(args.timeout_ms),
345 },
346 ...(itemId ? { id: itemId } : {}),
347 }
349​
350type ShellOutcome = { type: 'exit'; exit_code: number } | { type: 'timeout' }
351​
352function shellOutcome(value: unknown): ShellOutcome {
353 if (isRecord(value) && value.type === 'timeout') return { type: 'timeout' }
354 const exitCode =
355 isRecord(value) && typeof value.exit_code === 'number' ? value.exit_code : 0
356 return { type: 'exit', exit_code: exitCode }
358​
359function shellEntry(value: unknown): {
360 stdout: string
361 stderr: string
362 outcome: ShellOutcome
363} {
364 if (typeof value === 'string') {
365 return {
366 stdout: value,
367 stderr: '',
368 outcome: { type: 'exit', exit_code: 0 },
369 }
370 }
371 const record = isRecord(value) ? value : {}
372 return {
373 stdout: typeof record.stdout === 'string' ? record.stdout : '',
374 stderr: typeof record.stderr === 'string' ? record.stderr : '',
375 outcome: shellOutcome(record.outcome),
376 }
378​
379function shellOutputList(content: unknown): Array<{
380 stdout: string
381 stderr: string
382 outcome: ShellOutcome
383}> {
384 const parsed = parseContent(content)
385 if (isRecord(parsed) && Array.isArray(parsed.output)) {
386 return parsed.output.map((entry) => shellEntry(entry))
387 }
388 if (isRecord(parsed) && ('stdout' in parsed || 'outcome' in parsed)) {
389 return [shellEntry(parsed)]
390 }
391 if (typeof parsed === 'string') return [shellEntry(parsed)]
392 return [shellEntry(JSON.stringify(parsed ?? ''))]
394​
395/**
396 * Replay the app's tool result as the matching Responses output item.
397 * `computer` is what a computer tool result needs: the screenshot, and
398 * whether the call failed. Only a computer result reads the screenshot.
399 * The output of a call that did not fail acknowledges the safety checks of
400 * the call.
401 */
402export function userToolResultItem(
403 toolCall: ToolCallLike,
404 content: unknown,
405 computer: {
406 screenshot: () => ResponseComputerToolCallOutputScreenshot
407 failed: boolean
408 },
409): ResponseInputItem | null {
410 const name = readUserToolName(toolCall.metadata)
411 if (!name) return null
412​
413 if (name === 'computer' || name === 'computer_use_preview') {
414 const checks = computer.failed
415 ? []
416 : (safetyChecks(
417 parseArguments(toolCall.function.arguments).pending_safety_checks,
418 ) ?? [])
419 return {
420 type: 'computer_call_output',
421 call_id: toolCall.id,
422 output: computer.screenshot(),
423 ...(checks.length > 0 ? { acknowledged_safety_checks: checks } : {}),
424 }
425 }
426​
427 const parsed = parseContent(content)
428​
429 if (name === 'apply_patch') {
430 const record = isRecord(parsed) ? parsed : {}
431 const failed =
432 record.status === 'failed' ||
433 (record.status !== 'completed' && typeof record.error === 'string')
434 const output =
435 typeof record.output === 'string'
436 ? record.output
437 : typeof record.error === 'string'
438 ? record.error
439 : typeof parsed === 'string'
440 ? parsed
441 : undefined
442 return {
443 type: 'apply_patch_call_output',
444 call_id: toolCall.id,
445 status: failed ? 'failed' : 'completed',
446 ...(output !== undefined ? { output } : {}),
447 }
448 }
449​
450 if (name === 'local_shell') {
451 const output =
452 typeof parsed === 'string'
453 ? parsed
454 : isRecord(parsed) && typeof parsed.output === 'string'
455 ? parsed.output
456 : JSON.stringify(parsed ?? '')
457 return {
458 type: 'local_shell_call_output',
459 id: toolCall.id,
460 output,
461 status: 'completed',
462 }
463 }
464​
465 const record = isRecord(parsed) ? parsed : {}
466 const fromResult = nullableNumber(record.max_output_length)
467 const fromCall = readMaxOutputLength(toolCall.metadata)
468 const maxOutputLength =
469 record.max_output_length !== undefined ? fromResult : fromCall
470 return {
471 type: 'shell_call_output',
472 call_id: toolCall.id,
473 output: shellOutputList(content),
474 ...(maxOutputLength !== undefined
475 ? { max_output_length: maxOutputLength }
476 : {}),
477 }