|
| 1 | +/** |
| 2 | + * Convert an object-shaped tool input into positional arguments. |
| 3 | + * |
| 4 | + * Tool schemas expose positional parameters as `arg0`, `arg1`, and so on. |
| 5 | + * Arrays pass through for callers that already provide positional arguments. |
| 6 | + */ |
| 7 | +function collectPositionalArgs(input: unknown, argumentCount: number | undefined): unknown[] | undefined { |
| 8 | + if (Array.isArray(input)) |
| 9 | + return input |
| 10 | + if (input === undefined || input === null) |
| 11 | + return [] |
| 12 | + if (typeof input !== 'object') |
| 13 | + return undefined |
| 14 | + |
| 15 | + const record = input as Record<string, unknown> |
| 16 | + if (argumentCount != null) |
| 17 | + return Array.from({ length: argumentCount }, (_, index) => record[`arg${index}`]) |
| 18 | + if ('arg0' in record) { |
| 19 | + const positional: unknown[] = [] |
| 20 | + while (`arg${positional.length}` in record) |
| 21 | + positional.push(record[`arg${positional.length}`]) |
| 22 | + return positional |
| 23 | + } |
| 24 | + return Object.keys(record).length === 0 ? [] : undefined |
| 25 | +} |
| 26 | + |
| 27 | +/** Convert tool input for an RPC, preserving an untyped payload as arg 0. */ |
| 28 | +export function toolInputToRpcArgs(input: unknown, argumentCount?: number): unknown[] { |
| 29 | + return collectPositionalArgs(input, argumentCount) ?? [input] |
| 30 | +} |
| 31 | + |
| 32 | +/** Convert tool input for a command, whose arguments must be declared. */ |
| 33 | +export function toolInputToCommandArgs(input: unknown, argumentCount?: number): unknown[] { |
| 34 | + return collectPositionalArgs(input, argumentCount) ?? [] |
| 35 | +} |
| 36 | + |
| 37 | +/** @deprecated Use {@link toolInputToRpcArgs} or {@link toolInputToCommandArgs}. */ |
| 38 | +export type AgentArgsFallback = 'wrap' | 'drop' |
| 39 | + |
| 40 | +/** @deprecated Use {@link toolInputToRpcArgs} or {@link toolInputToCommandArgs}. */ |
| 41 | +export function coerceAgentPositionalArgs( |
| 42 | + input: unknown, |
| 43 | + schemas: readonly unknown[] | undefined, |
| 44 | + fallback: AgentArgsFallback = 'wrap', |
| 45 | +): unknown[] { |
| 46 | + const argumentCount = schemas?.length |
| 47 | + return fallback === 'drop' |
| 48 | + ? toolInputToCommandArgs(input, argumentCount) |
| 49 | + : toolInputToRpcArgs(input, argumentCount) |
| 50 | +} |
0 commit comments