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

shell-tool.ts

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