feat(core): use freeform tool input on models that support it (#61703)

This commit is contained in:
Aiden Cline
2026-11-10 15:15:25 -06:00
committed by GitHub
Unverified
parent 64bd35afa9
commit 53f2d631df
27 changed files with 279 additions and 33 deletions
+4
View File
@@ -61,6 +61,10 @@ only shape the model-visible signature. Without `output`, the signature uses `Pr
Descriptions and schemas are model-visible contracts. Authorization belongs in `execute`.
Set `freeform: true` on a tool whose input is one required string field to let programs pass that string directly. For
`{ patchText: string }`, the catalog shows `tools.patch(patchText: string)`, and `tools.patch("*** Begin Patch...")`
delivers `{ patchText: "*** Begin Patch..." }` to validation, hooks and the executor. The object form still works.
Nested records are the shorthand for ordinary namespaces. Use `Namespace.make` when a namespace needs a description:
```ts
+6 -2
View File
@@ -10,6 +10,7 @@ import {
inputTypeScript,
isEmptyInput,
outputTypeScript,
stringParameter,
} from "./tool-schema.js"
import { isNamespace, type Namespace } from "./namespace.js"
import { type Durable, type Idempotent, isTool, type Tool, type ToolContext } from "./tool.js"
@@ -186,7 +187,8 @@ const describeTool = <R>(visible: VisibleTool<R>): ToolDescription => {
// Joining the final fragments avoids retaining the rendering's intermediate string ropes in JSC.
return (signature ??= [
toolExpression(visible.path),
isEmptyInput(visible.tool) ? "()" : `(${inputTypeScript(visible.tool, true)})`,
stringParameter(visible.tool)?.signature ??
(isEmptyInput(visible.tool) ? "()" : `(${inputTypeScript(visible.tool, true)})`),
`: Promise<${outputTypeScript(visible.tool, true)}>`,
].join(""))
},
@@ -451,8 +453,10 @@ export const make = <R>(
const normalized = args.length === 0 ? [{}] : args
if (normalized.length !== 1)
throw new ToolRuntimeError("InvalidToolInput", `Tool '${name}' expects at most one input object.`)
const input = normalized[0]
const field = typeof input === "string" ? stringParameter(tool)?.name : undefined
return yield* Effect.try({
try: () => decodeToolInput(tool, normalized[0]),
try: () => decodeToolInput(tool, field === undefined ? input : { [field]: input }),
catch: (cause) =>
new ToolRuntimeError(
"InvalidToolInput",
+36 -18
View File
@@ -252,24 +252,9 @@ export type InputProperty = {
export const inputProperties = <R>(tool: Tool<R>): Array<InputProperty> => {
try {
const document = isEffectSchema(tool.input)
? (Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" }) as {
readonly schema: JsonSchema
readonly definitions: Readonly<Record<string, JsonSchema>>
})
: {
schema: tool.input,
definitions: { ...(tool.input.definitions ?? {}), ...(tool.input.$defs ?? {}) },
}
let schema = document.schema
if (schema.$ref !== undefined) {
const name = definitionName(schema.$ref)
const resolved = name === undefined ? undefined : document.definitions[name]
if (resolved === undefined) return []
schema = resolved
}
const required = new Set(schema.required ?? [])
return Object.entries(schema.properties ?? {}).map(([name, value]) => ({
const schema = inputDocument(tool)?.schema
const required = new Set(schema?.required ?? [])
return Object.entries(schema?.properties ?? {}).map(([name, value]) => ({
name,
description: typeof value.description === "string" ? value.description : undefined,
required: required.has(name),
@@ -279,6 +264,39 @@ export const inputProperties = <R>(tool: Tool<R>): Array<InputProperty> => {
}
}
/** A freeform tool whose input is one required string field takes that string directly: `tools.patch(patchText: string)`. */
export const stringParameter = <R>(tool: Tool<R>) => {
if (!tool.freeform) return undefined
try {
const document = inputDocument(tool)
const fields = Object.entries(document?.schema.properties ?? {})
if (document === undefined || fields.length !== 1) return undefined
const [name, field] = fields[0]!
if (field.type !== "string" || !document.schema.required?.includes(name)) return undefined
const label = identifierSegment.test(name) ? name : "input"
const type = renderSchema(field, { definitions: document.definitions, pretty: false })
return { name, signature: `(${jsdoc(field, "").replace(/\n$/, " ")}${label}: ${type})` }
} catch {
return undefined
}
}
const inputDocument = <R>(tool: Tool<R>) => {
const document = isEffectSchema(tool.input)
? (Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" }) as {
readonly schema: JsonSchema
readonly definitions: Readonly<Record<string, JsonSchema>>
})
: {
schema: tool.input,
definitions: { ...(tool.input.definitions ?? {}), ...(tool.input.$defs ?? {}) },
}
if (document.schema.$ref === undefined) return document
const name = definitionName(document.schema.$ref)
const schema = name === undefined ? undefined : document.definitions[name]
return schema && { schema, definitions: document.definitions }
}
export const inputTypeScript = <R>(tool: Tool<R>, pretty = false): string =>
isEffectSchema(tool.input) ? toTypeScript(tool.input, false, pretty) : jsonSchemaToTypeScript(tool.input, pretty)
+7
View File
@@ -96,6 +96,7 @@ export type Tool<R = never> = {
readonly _tag: "CodeModeTool"
readonly description: string
readonly input: SchemaType
readonly freeform?: boolean
readonly output: SchemaType | undefined
readonly execute: (input: unknown, context?: ToolContext) => Effect.Effect<unknown, unknown, R>
readonly mode?: Idempotent<unknown, unknown, R> | Durable<unknown, unknown, R> | undefined
@@ -109,6 +110,11 @@ type ResultType<S> = S extends undefined ? void : S extends Schema.Decoder<unkno
export type Options<I extends SchemaType, O extends SchemaType | undefined, R = never> = {
readonly description: string
readonly input: I
/**
* The tool's input is one required string field that programs pass directly, as in `tools.patch("...")`.
* The object form still works, and the executor receives the object either way.
*/
readonly freeform?: boolean
readonly output?: O
readonly execute:
| ExecuteFn<InputType<I>, ResultType<O>, R>
@@ -172,6 +178,7 @@ export const make = <I extends SchemaType, const O extends SchemaType | undefine
_tag: "CodeModeTool",
description: options.description,
input: options.input,
...(options.freeform && { freeform: true }),
output: options.output,
...(mode === undefined ? {} : { mode }),
execute: (input, context = { key: crypto.randomUUID() }) => spec(input as InputType<I>, context),
+28
View File
@@ -789,6 +789,34 @@ describe("CodeMode public contract", () => {
}
})
test("a freeform tool takes its one string field directly and still accepts the object", async () => {
const input = Schema.Struct({ url: Schema.String.annotate({ description: "Page URL" }) })
const fetchPage = Tool.make({
description: "Fetch a page",
input,
freeform: true,
output: Schema.String,
execute: ({ url }) => Effect.succeed(url),
})
const plain = Tool.make({
description: "Fetch a page",
input,
output: Schema.String,
execute: ({ url }) => Effect.succeed(url),
})
const runtime = CodeMode.make({ tools: { fetchPage, plain } })
expect(runtime.catalog.map((tool) => tool.signature)).toEqual([
"tools.fetchPage(/** Page URL */ url: string): Promise<string>",
"tools.plain({\n /** Page URL */\n url: string,\n}): Promise<string>",
])
expect(
await Effect.runPromise(
runtime.execute('return [await tools.fetchPage("a"), await tools.fetchPage({ url: "b" })]'),
),
).toMatchObject({ ok: true, value: ["a", "b"] })
expect(await Effect.runPromise(runtime.execute('return await tools.plain("a")'))).toMatchObject({ ok: false })
})
test("renders equivalent catalogs identically regardless of tool insertion order", () => {
const alpha = Tool.make({
description: "Alpha tool",