/** Checking a call's arguments against the tool definition before anything runs. */ import type { ToolResponse } from '../answer-json.js'; import { nearest } from '../nearest.js'; import { isRecord } from '../records.js'; import type { GodotServer } from '../server.js'; import { SERVER_VERSION } from '../server-version.js'; import { type OperationParams, readString } from '../tool-args.js'; import { argumentsOf, opTakes, requiredSetsSaid, type ToolSpec } from '../tool-definitions.js'; import { argumentShape } from '../tool-reference.js'; /** Whether [args] gives [field] as one of an op's `requiresOneOf` sets asks. Blank and null are missing. */ function givenInASet(args: OperationParams, field: string): boolean { const value = Object.hasOwn(args, field) ? args[field] : undefined; return value !== undefined && value !== null && !(typeof value === 'string' && value.trim() === ''); } /** Whether [param value] is the [param kind] a schema asked for. An unknown kind asks nothing. */ function isOfType(value: unknown, kind: unknown): boolean { switch (kind) { case 'string': return typeof value === 'string'; case 'number': return typeof value === 'number' && Number.isFinite(value); case 'integer': return Number.isInteger(value); case 'boolean': return typeof value === 'boolean'; case 'array': return Array.isArray(value); case 'object': return isRecord(value); default: return true; } } /** What arrived, in the words the refusal uses, so a caller can see the two side by side. */ const VALUE_NAMES: Readonly> = { string: 'a string', boolean: 'a boolean', object: 'an object', }; export function describeValue(value: unknown): string { if (Array.isArray(value)) { return 'a list'; } // The number itself, since the one refusal a number meets is being the wrong kind of number: // "depth as integer, not a number" names the type it has in common with what was wanted. if (typeof value === 'number') { return String(value); } if (value === null) { return 'null'; } return VALUE_NAMES[typeof value] ?? typeof value; } /** * Which arguments are not the type their schema declares. * * An argument a tool does not name is refused already, and one it names but cannot use is the * same mistake wearing the right word: `includeProperties` given the list of properties to * include was taken, ignored, and answered as though it had been read, which is exactly the shape * a refusal exists to prevent. * * A schema naming no type asks nothing, because some arguments genuinely have none: a value being * fitted to a property is whatever that property holds, and that is the engine's business. * * The walk follows the schema into the elements of a list and the fields of an object, as * `unlistedValues` does, because that is where the same mistake hides: a modification's `params` * sent as a list was written into the script as `signal changed([])`. A field a closed object does * not name is refused there too, as an argument the tool does not name is at the top, since a * misspelt `vartype` was otherwise dropped and the variable written as a Variant. */ function wrongTypes(spec: ToolSpec, args: OperationParams): string[] { const op = opNamed(spec, args); return Object.entries(args).flatMap(([name, value]) => misshapen( spec.parameters[name], value, name, op === null || (op !== undefined && opTakes(spec, op, name)), ), ); } /** The op [param args] name or the tool's default, null for a tool with no ops, undefined for an op it lacks. */ function opNamed(spec: ToolSpec, args: OperationParams): string | null | undefined { if (!spec.operations) { return null; } const requested = args['op'] ?? spec.defaultOperation; return typeof requested === 'string' && Object.hasOwn(spec.operations, requested) ? requested : undefined; } /** * What [param schema] refuses in the type and fields of [param value]. * * [param whole] is false for an argument the call's op does not take, or whose op is unknown. Such * a value is not asked for the fields it lacks, since the caller who added them would next be told * the op takes no such argument. */ export function misshapen(schema: unknown, value: unknown, path: string, whole = true): string[] { if (!isRecord(schema) || value === undefined || value === null) { return []; } const declared = schema['type']; const wanted = typeof declared === 'string' ? [declared] : Array.isArray(declared) ? declared.filter((kind): kind is string => typeof kind === 'string') : []; if (wanted.length > 0 && !wanted.some((kind) => isOfType(value, kind))) { return [`${path} as ${wanted.join(' or ')}, not ${describeValue(value)}`]; } if (Array.isArray(value)) { return value.flatMap((element, index) => misshapen(schema['items'], element, `${path}[${index}]`, whole)); } if (!isRecord(value)) { return []; } const lacking = whole ? lacked(schema, value, path) : []; const properties = schema['properties']; if (!isRecord(properties)) { return lacking; } const unfit = Object.entries(value).flatMap(([field, held]) => { if (Object.hasOwn(properties, field)) { return misshapen(properties[field], held, `${path}.${field}`, whole); } if (schema['additionalProperties'] !== false) { return []; } const fields = Object.keys(properties); const close = nearest(field, fields); return [ `${path} with only the fields ${fields.join(', ')}, and ${field} is none of them${close.length === 0 ? '' : ` (the nearest is ${close[0]})`}`, ]; }); return [...lacking, ...unfit]; } /** * The fields [param schema] requires of an object and [param value] lacks, as one complaint. * * A field left out reached a reader that took its default or refused it only after an engine had * started, for a call the schema already rules out. */ function lacked(schema: Record, value: Record, path: string): string[] { const required = schema['required']; const missing = Array.isArray(required) ? required.filter( (field): field is string => typeof field === 'string' && (!Object.hasOwn(value, field) || (value[field] ?? null) === null), ) : []; if (missing.length === 0) { return []; } // A field that takes one of a few values is named with them, as its own reader names them. const properties = schema['properties']; const said = missing.map((field) => { const listed = isRecord(properties) && isRecord(properties[field]) ? properties[field]['enum'] : undefined; return Array.isArray(listed) ? `${field} (one of ${listed.join(', ')})` : field; }); return [`${path} with its ${said.join(', ')}, which ${missing.length === 1 ? 'is' : 'are'} missing`]; } /** * Which values are not one of the ones their schema lists, named by where they sit. * * A wrong type is at least visibly wrong. A value outside the listed set is the quieter fault: the * argument is spelled right and holds a string, so it survives every check above and then reaches * code that does not recognise it and takes the default. `direction: "reversed"` answers with what * the resource depends on, which is the opposite question, and nothing in the answer says so. * * Only strings, and only against a set the schema actually lists, because that is where a typo * costs something a caller cannot see. The walk follows the schema rather than the value, so a set * listed on an element of a list or on a field of an object is checked exactly as a top-level one * is, and a schema that lists nothing asks nothing. */ function unlistedValues(schema: unknown, value: unknown, path: string): string[] { if (!isRecord(schema)) { return []; } const fields: Readonly> = schema; const listed = fields['enum']; if (Array.isArray(listed) && typeof value === 'string') { if (listed.includes(value)) { return []; } return [ listed.length === 1 ? `${path} only as ${String(listed[0])}, not ${JSON.stringify(value)}` : `${path} as one of ${listed.join(', ')}, not ${JSON.stringify(value)}`, ]; } if (Array.isArray(value)) { return value.flatMap((element, index) => unlistedValues(fields['items'], element, `${path}[${index}]`)); } const properties = fields['properties']; if (isRecord(properties) && isRecord(value)) { return Object.entries(value).flatMap(([field, held]) => Object.hasOwn(properties, field) ? unlistedValues(properties[field], held, `${path}.${field}`) : [], ); } return []; } function outsideTheirLists(spec: ToolSpec, args: OperationParams): string[] { return Object.entries(args).flatMap(([name, value]) => unlistedValues(spec.parameters[name], value, name)); } /** * Which numbers fall outside the range their schema declares, and which lists hold more or fewer * items than it allows, named by where they sit. * * The quiet fault a range stops is the same one a list does: a number the call cannot mean reaches * a reader that takes it as absent and applies the default. A tree asked for at depth 0 answered * three levels, four megabytes over a router node, and `before: 0` carried three lines anyway. * Refused here, where the schema that says what a number may be is also what the client is shown. * * The walk follows the schema into the elements of a list and the fields of an object, as * `unlistedValues` does, so a bound on either is read as a top-level one is. */ export function outOfBounds(schema: unknown, value: unknown, path: string): string[] { if (!isRecord(schema)) { return []; } if (typeof value === 'number') { // A schema that names a number type refuses an infinity or a NaN as no number, which says all a // range would. One that names none leaves the range as the only rule to hold it. const refusedByType = !Number.isFinite(value) && (schema['type'] === 'number' || schema['type'] === 'integer'); const range = refusedByType ? undefined : outsideRange(schema, value); return range === undefined ? [] : [`${path} ${range}, not ${value}`]; } if (Array.isArray(value)) { const count = outsideCount(schema, value.length); return [ ...(count === undefined ? [] : [`${path} with ${count}, not ${value.length}`]), ...value.flatMap((element, index) => outOfBounds(schema['items'], element, `${path}[${index}]`)), ]; } const properties = schema['properties']; if (isRecord(properties) && isRecord(value)) { return Object.entries(value).flatMap(([field, held]) => Object.hasOwn(properties, field) ? outOfBounds(properties[field], held, `${path}.${field}`) : [], ); } return []; } function outsideTheirBounds(spec: ToolSpec, args: OperationParams): string[] { return Object.entries(args).flatMap(([name, value]) => outOfBounds(spec.parameters[name], value, name)); } /** What the schemas of [param spec] refuse in the values of [param args], each named by where it sits. */ export function unfitValues(spec: ToolSpec, args: OperationParams): string[] { return [...wrongTypes(spec, args), ...outsideTheirLists(spec, args), ...outsideTheirBounds(spec, args)]; } /** How many items [param schema] lets a list hold, worded for a refusal, when it holds [param count]. */ function outsideCount(schema: Record, count: number): string | undefined { const fewest = typeof schema['minItems'] === 'number' ? schema['minItems'] : undefined; const most = typeof schema['maxItems'] === 'number' ? schema['maxItems'] : undefined; if (!((fewest !== undefined && count < fewest) || (most !== undefined && count > most))) { return undefined; } const items = (held: number | undefined): string => (held === 1 ? '1 item' : `${held} items`); if (fewest !== undefined && most !== undefined) { return fewest === most ? items(fewest) : `${fewest} to ${most} items`; } return fewest !== undefined ? `${items(fewest)} or more` : `${items(most)} or fewer`; } /** The range [param schema] declares, worded for a refusal, when [param value] falls outside it. */ function outsideRange(schema: Record, value: number): string | undefined { const above = schema['exclusiveMinimum']; if (typeof above === 'number' && value <= above) { return `above ${above}`; } const least = typeof schema['minimum'] === 'number' ? schema['minimum'] : undefined; const most = typeof schema['maximum'] === 'number' ? schema['maximum'] : undefined; if (!((least !== undefined && value < least) || (most !== undefined && value > most))) { return undefined; } return least !== undefined && most !== undefined ? `from ${least} to ${most}` : least !== undefined ? `of ${least} or more` : `of ${most} or less`; } /** * Ops callers reach for on one tool that another answers, by the tool and op that do. * * Two downstream sessions read back a value they had just set with runtime_invoke, one as op "get" * and one as "property" three times over, and each was told only the ops runtime_invoke has, which * left them a round trip to find that reads live in runtime_inspect. */ const OPS_ELSEWHERE: Readonly>>> = { runtime_invoke: { get: 'runtime_inspect property', property: 'runtime_inspect property' }, }; /** Where an op a tool has not got is answered, as a sentence to add to the refusal, or "". */ function opElsewhere(tool: string, requested: unknown): string { const ops = Object.hasOwn(OPS_ELSEWHERE, tool) ? OPS_ELSEWHERE[tool] : undefined; const where = ops !== undefined && typeof requested === 'string' && Object.hasOwn(ops, requested) ? ops[requested] : undefined; return where === undefined ? '' : ` A value is read with ${where}.`; } /** * The arguments of a call checked against the tool's spec: nothing the schema does not name, * each one of the type it is declared as, an op from the enum, and every argument the tool and * its op require. Returns the op to dispatch on, or the refusal to send back. Own properties * only: a required argument satisfied by something inherited from Object.prototype is not * supplied. */ export function validateArguments( server: GodotServer, spec: ToolSpec, args: OperationParams, ): { ok: true; op: string | null } | { ok: false; response: ToolResponse } { const known = new Set([...Object.keys(spec.parameters), ...(spec.operations ? ['op'] : [])]); const unknown = Object.keys(args).filter((key) => !known.has(key)); if (unknown.length > 0) { // A tool that takes nothing read "It takes: ." and left the caller to work out whether the // list was missing or empty. editor_status is one of them, and it is the tool a session calls // first, so it is the first refusal anybody sees. // // Named for the op when one was asked for, because a tool's whole argument list answers a // question nobody asked: a caller who wrote `get` wants to know what `get` takes, not the // twenty arguments the other ten ops between them accept. const asked = readString(args, 'op'); const knownOp = asked !== undefined && spec.operations !== undefined && Object.hasOwn(spec.operations, asked) ? asked : null; const wanted = knownOp === null ? [...known] : [...argumentsOf(spec, knownOp), 'op']; // Each with what it takes, because the name alone hides the second form: a session that // guessed `suites` for a list of suite files was told `path` and not that path takes one. const shaped = wanted.map((name) => { const schema = spec.parameters[name]; if (schema !== undefined) { return `${name} (${argumentShape(schema)})`; } return name === 'op' && knownOp === null && spec.operations !== undefined ? `op (${Object.keys(spec.operations).join(', ')})` : name; }); const takes = wanted.length === 0 ? 'It takes no arguments.' : `It takes: ${shaped.join(', ')}.`; // And the version, because "this tool has no such argument" and "the server you are talking // to does not have it yet" are the same sentence, and a server left running through an // upgrade says the second while sounding like the first. Without it the caller spends two // more calls working out which, and the answer only arrives when something else mentions the // version in passing. const where = knownOp === null ? spec.name : `${spec.name} ${knownOp}`; const spelled = unknown.flatMap((key) => { const camel = key.replace(/_([a-zA-Z0-9])/g, (_, letter: string) => letter.toUpperCase()); return camel !== key && known.has(camel) ? [`${key} is spelled ${camel}`] : []; }); return { ok: false, response: server.createErrorResponse( `${where} does not take ${unknown.join(', ')}.${spelled.length === 0 ? '' : ` ${spelled.join(', ')}.`} ${takes} This is gdharness ${SERVER_VERSION}, which is what decides whether an argument exists.`, ), }; } return validateValues(server, spec, args); } /** The values of a call's arguments checked against their schemas, then the op and what it requires. */ function validateValues( server: GodotServer, spec: ToolSpec, args: OperationParams, ): { ok: true; op: string | null } | { ok: false; response: ToolResponse } { const wrong = unfitValues(spec, args); if (wrong.length > 0) { return { ok: false, response: server.createErrorResponse(`${spec.name} takes ${wrong.join('; ')}.`) }; } return validateOp(server, spec, args); } /** The op a call asked for, or the tool's default, checked against the tool's ops. */ function validateOp( server: GodotServer, spec: ToolSpec, args: OperationParams, ): { ok: true; op: string | null } | { ok: false; response: ToolResponse } { let op: string | null = null; if (spec.operations) { const valid = Object.keys(spec.operations); const requested = args['op']; if (requested === undefined) { if (!spec.defaultOperation) { return { ok: false, response: server.createErrorResponse(`${spec.name} needs op, one of: ${valid.join(', ')}.`), }; } op = spec.defaultOperation; } else if (typeof requested === 'string' && Object.hasOwn(spec.operations, requested)) { op = requested; } else { return { ok: false, response: server.createErrorResponse( `${spec.name} has no op ${JSON.stringify(requested)}. Valid ops: ${valid.join(', ')}.${opElsewhere(spec.name, requested)}`, ), }; } } return validateOpArguments(server, spec, args, op); } /** The arguments of a call checked against what its op takes, then against what the op requires. */ function validateOpArguments( server: GodotServer, spec: ToolSpec, args: OperationParams, op: string | null, ): { ok: true; op: string | null } | { ok: false; response: ToolResponse } { // An argument named for a different op. The tool-level check above passes it, because the tool // does take it, and then the op reads nothing of the sort and answers as though it had: a limit // on a screen read, a property list on a find. That is the same fault as an argument nothing // names, and it is worse, because the caller has read the schema and believes they got it right. if (op !== null) { const elsewhere = Object.keys(args).filter((key) => key !== 'op' && !opTakes(spec, op, key)); if (elsewhere.length > 0) { // An op that takes nothing said "takes: ." and left the caller deciding whether that was // the whole list or a sentence that had lost its end. The same fix the tool-level refusal // already had, which is where this wording came from. const takes = argumentsOf(spec, op); return { ok: false, response: server.createErrorResponse( `${spec.name} ${op} does not take ${elsewhere.join(', ')}. ${takes.length === 0 ? `${op} takes no arguments.` : `${op} takes: ${takes.join(', ')}.`}`, ), }; } } return validateRequired(server, spec, args, op); } /** The arguments the tool and its op require, each checked as present and not blank. */ function validateRequired( server: GodotServer, spec: ToolSpec, args: OperationParams, op: string | null, ): { ok: true; op: string | null } | { ok: false; response: ToolResponse } { const required = [...spec.requires, ...(op !== null ? (spec.operations?.[op]?.requires ?? []) : [])]; const missing = required.filter((field) => { const value = Object.hasOwn(args, field) ? args[field] : undefined; if (value === undefined || value === null) { return true; } // Blank is an argument somebody meant to fill in, everywhere but the few that carry content // rather than name something: emptying a field and writing "" to a property are both calls a // caller means, and refusing them as missing tells them they forgot what they deliberately // sent. See `blank` in tool-definitions. const blank = typeof value === 'string' && value.trim() === ''; return blank && spec.parameters[field]?.blank !== true; }); if (missing.length > 0) { const where = op !== null ? `${spec.name} ${op}` : spec.name; // Said apart, since "needs actionName" to a caller who sent one reads as a field the server // did not see, when what it refused was the empty value. const blank = missing.filter((field) => typeof args[field] === 'string'); const fields = missing.map((field) => blank.includes(field) ? `${field}, which was given empty` : field, ); const joined = fields.join(blank.length > 0 ? '; ' : ', '); return { ok: false, response: server.createErrorResponse(`${where} needs ${joined}.`) }; } const operation = op === null ? undefined : spec.operations?.[op]; const sets = operation?.requiresOneOf; if ( op !== null && sets !== undefined && !sets.some((set) => set.every((field) => givenInASet(args, field))) ) { const said = operation?.unmet?.said ?? `${spec.name} ${op} needs ${requiredSetsSaid(sets)}.`; return { ok: false, response: server.createErrorResponse(said, [...(operation?.unmet?.next ?? [])]), }; } return { ok: true, op }; }