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

shell-tool.ts

81 lines2.6 KB

1import {
2 getOpenAIProviderToolMetadata,
3 openAIProviderTool,
4} from './openai-provider-tool'
5import type { FunctionShellTool as ShellToolConfig } from 'openai/resources/responses/responses'
6import type { Tool } from '@tanstack/ai'
7​
8export type { ShellToolConfig }
9​
10/**
11 * Config accepted by {@link shellTool}. `environment` mirrors the OpenAI
12 * Responses API shell tool environment (e.g. `container_auto` + `skills`).
13 * Typed via indexed access so it tracks the installed SDK without naming the
14 * union members directly.
15 */
16export interface ShellToolFactoryConfig {
17 environment?: NonNullable<ShellToolConfig['environment']>
19​
20/**
21 * Validate skill references carried by a shell `environment`. Previously the
22 * factory validated nothing, so a malformed `skill_id` surfaced as an unframed
23 * provider 400. Only `skill_reference` entries carry a `skill_id`; inline and
24 * local skills are shaped differently and left untouched.
25 *
26 * ponytail: OpenAI documents no client-checkable count cap for shell skills
27 * (unlike Anthropic's 8), so we validate `skill_id` format only and do not
28 * fabricate a `SkillLimitError` count limit. Add one here if OpenAI publishes a cap.
29 */
30function validateShellEnvironment(
31 environment: ShellToolFactoryConfig['environment'],
32): void {
33 const skills =
34 environment && 'skills' in environment ? environment.skills : undefined
35 if (!skills) return
36 for (const skill of skills) {
37 if ('skill_id' in skill) {
38 const id = skill.skill_id
39 if (id.length < 1 || id.length > 64) {
40 throw new Error('skill_id must be between 1 and 64 characters.')
41 }
42 }
43 }
45​
46/**
47 * Converts a standard Tool to OpenAI ShellTool format, preserving any
48 * `environment` (container config + skills) stored in metadata.
49 */
50export function convertShellToolToAdapterFormat(tool: Tool): ShellToolConfig {
51 const metadata = (getOpenAIProviderToolMetadata(tool) ??
52 {}) as ShellToolFactoryConfig
53 return {
54 type: 'shell',
55 ...(metadata.environment !== undefined && {
56 environment: metadata.environment,
57 }),
58 }
60​
61/**
62 * Creates a standard Tool from ShellTool parameters.
63 *
64 * Base (non-branded) factory. Providers that need branded return types should
65 * re-wrap this in their own package.
66 */
67export function shellTool(config: ShellToolFactoryConfig = {}): Tool {
68 validateShellEnvironment(config.environment)
69 return openAIProviderTool(
70 {
71 name: 'shell',
72 description: 'Execute shell commands',
73 metadata: {
74 ...(config.environment !== undefined && {
75 environment: config.environment,
76 }),
77 },
78 },
79 'shell',
80 )