Skip to content

Commit 53f2d63

Browse files
authored
feat(core): use freeform tool input on models that support it (anomalyco#61703)
1 parent 64bd35a commit 53f2d63

27 files changed

Lines changed: 279 additions & 33 deletions

File tree

‎packages/ai/src/schema/messages.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -369,12 +369,8 @@ export const Message = withStatics(messageSchema, {
369369
* Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format
370370
* write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input.
371371
*/
372-
export const Freeform = Schema.Union([
373-
Schema.Struct({ type: Schema.Literal("text") }),
374-
Schema.Struct({ type: Schema.Literal("regex"), pattern: Schema.String }),
375-
Schema.Struct({ type: Schema.Literal("lark"), grammar: Schema.String }),
376-
]).annotate({ identifier: "LLM.Freeform" })
377-
export type Freeform = Schema.Schema.Type<typeof Freeform>
372+
export const Freeform = Tool.Freeform
373+
export type Freeform = Tool.Freeform
378374

379375
const toolDefinitionFields = {
380376
name: Schema.String,

‎packages/client/src/promise/generated/types.ts‎

Lines changed: 10 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/codemode/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ only shape the model-visible signature. Without `output`, the signature uses `Pr
6161

6262
Descriptions and schemas are model-visible contracts. Authorization belongs in `execute`.
6363

64+
Set `freeform: true` on a tool whose input is one required string field to let programs pass that string directly. For
65+
`{ patchText: string }`, the catalog shows `tools.patch(patchText: string)`, and `tools.patch("*** Begin Patch...")`
66+
delivers `{ patchText: "*** Begin Patch..." }` to validation, hooks and the executor. The object form still works.
67+
6468
Nested records are the shorthand for ordinary namespaces. Use `Namespace.make` when a namespace needs a description:
6569

6670
```ts

‎packages/codemode/src/tool-runtime.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
inputTypeScript,
1111
isEmptyInput,
1212
outputTypeScript,
13+
stringParameter,
1314
} from "./tool-schema.js"
1415
import { isNamespace, type Namespace } from "./namespace.js"
1516
import { type Durable, type Idempotent, isTool, type Tool, type ToolContext } from "./tool.js"
@@ -186,7 +187,8 @@ const describeTool = <R>(visible: VisibleTool<R>): ToolDescription => {
186187
// Joining the final fragments avoids retaining the rendering's intermediate string ropes in JSC.
187188
return (signature ??= [
188189
toolExpression(visible.path),
189-
isEmptyInput(visible.tool) ? "()" : `(${inputTypeScript(visible.tool, true)})`,
190+
stringParameter(visible.tool)?.signature ??
191+
(isEmptyInput(visible.tool) ? "()" : `(${inputTypeScript(visible.tool, true)})`),
190192
`: Promise<${outputTypeScript(visible.tool, true)}>`,
191193
].join(""))
192194
},
@@ -451,8 +453,10 @@ export const make = <R>(
451453
const normalized = args.length === 0 ? [{}] : args
452454
if (normalized.length !== 1)
453455
throw new ToolRuntimeError("InvalidToolInput", `Tool '${name}' expects at most one input object.`)
456+
const input = normalized[0]
457+
const field = typeof input === "string" ? stringParameter(tool)?.name : undefined
454458
return yield* Effect.try({
455-
try: () => decodeToolInput(tool, normalized[0]),
459+
try: () => decodeToolInput(tool, field === undefined ? input : { [field]: input }),
456460
catch: (cause) =>
457461
new ToolRuntimeError(
458462
"InvalidToolInput",

‎packages/codemode/src/tool-schema.ts‎

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -252,24 +252,9 @@ export type InputProperty = {
252252

253253
export const inputProperties = <R>(tool: Tool<R>): Array<InputProperty> => {
254254
try {
255-
const document = isEffectSchema(tool.input)
256-
? (Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" }) as {
257-
readonly schema: JsonSchema
258-
readonly definitions: Readonly<Record<string, JsonSchema>>
259-
})
260-
: {
261-
schema: tool.input,
262-
definitions: { ...(tool.input.definitions ?? {}), ...(tool.input.$defs ?? {}) },
263-
}
264-
let schema = document.schema
265-
if (schema.$ref !== undefined) {
266-
const name = definitionName(schema.$ref)
267-
const resolved = name === undefined ? undefined : document.definitions[name]
268-
if (resolved === undefined) return []
269-
schema = resolved
270-
}
271-
const required = new Set(schema.required ?? [])
272-
return Object.entries(schema.properties ?? {}).map(([name, value]) => ({
255+
const schema = inputDocument(tool)?.schema
256+
const required = new Set(schema?.required ?? [])
257+
return Object.entries(schema?.properties ?? {}).map(([name, value]) => ({
273258
name,
274259
description: typeof value.description === "string" ? value.description : undefined,
275260
required: required.has(name),
@@ -279,6 +264,39 @@ export const inputProperties = <R>(tool: Tool<R>): Array<InputProperty> => {
279264
}
280265
}
281266

267+
/** A freeform tool whose input is one required string field takes that string directly: `tools.patch(patchText: string)`. */
268+
export const stringParameter = <R>(tool: Tool<R>) => {
269+
if (!tool.freeform) return undefined
270+
try {
271+
const document = inputDocument(tool)
272+
const fields = Object.entries(document?.schema.properties ?? {})
273+
if (document === undefined || fields.length !== 1) return undefined
274+
const [name, field] = fields[0]!
275+
if (field.type !== "string" || !document.schema.required?.includes(name)) return undefined
276+
const label = identifierSegment.test(name) ? name : "input"
277+
const type = renderSchema(field, { definitions: document.definitions, pretty: false })
278+
return { name, signature: `(${jsdoc(field, "").replace(/\n$/, " ")}${label}: ${type})` }
279+
} catch {
280+
return undefined
281+
}
282+
}
283+
284+
const inputDocument = <R>(tool: Tool<R>) => {
285+
const document = isEffectSchema(tool.input)
286+
? (Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" }) as {
287+
readonly schema: JsonSchema
288+
readonly definitions: Readonly<Record<string, JsonSchema>>
289+
})
290+
: {
291+
schema: tool.input,
292+
definitions: { ...(tool.input.definitions ?? {}), ...(tool.input.$defs ?? {}) },
293+
}
294+
if (document.schema.$ref === undefined) return document
295+
const name = definitionName(document.schema.$ref)
296+
const schema = name === undefined ? undefined : document.definitions[name]
297+
return schema && { schema, definitions: document.definitions }
298+
}
299+
282300
export const inputTypeScript = <R>(tool: Tool<R>, pretty = false): string =>
283301
isEffectSchema(tool.input) ? toTypeScript(tool.input, false, pretty) : jsonSchemaToTypeScript(tool.input, pretty)
284302

‎packages/codemode/src/tool.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ export type Tool<R = never> = {
9696
readonly _tag: "CodeModeTool"
9797
readonly description: string
9898
readonly input: SchemaType
99+
readonly freeform?: boolean
99100
readonly output: SchemaType | undefined
100101
readonly execute: (input: unknown, context?: ToolContext) => Effect.Effect<unknown, unknown, R>
101102
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
109110
export type Options<I extends SchemaType, O extends SchemaType | undefined, R = never> = {
110111
readonly description: string
111112
readonly input: I
113+
/**
114+
* The tool's input is one required string field that programs pass directly, as in `tools.patch("...")`.
115+
* The object form still works, and the executor receives the object either way.
116+
*/
117+
readonly freeform?: boolean
112118
readonly output?: O
113119
readonly execute:
114120
| ExecuteFn<InputType<I>, ResultType<O>, R>
@@ -172,6 +178,7 @@ export const make = <I extends SchemaType, const O extends SchemaType | undefine
172178
_tag: "CodeModeTool",
173179
description: options.description,
174180
input: options.input,
181+
...(options.freeform && { freeform: true }),
175182
output: options.output,
176183
...(mode === undefined ? {} : { mode }),
177184
execute: (input, context = { key: crypto.randomUUID() }) => spec(input as InputType<I>, context),

‎packages/codemode/test/codemode.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,34 @@ describe("CodeMode public contract", () => {
789789
}
790790
})
791791

792+
test("a freeform tool takes its one string field directly and still accepts the object", async () => {
793+
const input = Schema.Struct({ url: Schema.String.annotate({ description: "Page URL" }) })
794+
const fetchPage = Tool.make({
795+
description: "Fetch a page",
796+
input,
797+
freeform: true,
798+
output: Schema.String,
799+
execute: ({ url }) => Effect.succeed(url),
800+
})
801+
const plain = Tool.make({
802+
description: "Fetch a page",
803+
input,
804+
output: Schema.String,
805+
execute: ({ url }) => Effect.succeed(url),
806+
})
807+
const runtime = CodeMode.make({ tools: { fetchPage, plain } })
808+
expect(runtime.catalog.map((tool) => tool.signature)).toEqual([
809+
"tools.fetchPage(/** Page URL */ url: string): Promise<string>",
810+
"tools.plain({\n /** Page URL */\n url: string,\n}): Promise<string>",
811+
])
812+
expect(
813+
await Effect.runPromise(
814+
runtime.execute('return [await tools.fetchPage("a"), await tools.fetchPage({ url: "b" })]'),
815+
),
816+
).toMatchObject({ ok: true, value: ["a", "b"] })
817+
expect(await Effect.runPromise(runtime.execute('return await tools.plain("a")'))).toMatchObject({ ok: false })
818+
})
819+
792820
test("renders equivalent catalogs identically regardless of tool insertion order", () => {
793821
const alpha = Tool.make({
794822
description: "Alpha tool",

‎packages/core/src/codemode/tool.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ export const create = (
9292
name: "execute",
9393
description,
9494
input: CodeMode.Input,
95+
freeform: { type: "text" },
9596
output: ExecuteOutput,
9697
execute: ({ code }, context) =>
9798
Effect.gen(function* () {
@@ -324,6 +325,7 @@ function inventoryTools(inventory: Inventory) {
324325
getNode(root, qualifiedName(registration)).tool = Tool.make({
325326
description: child.description,
326327
input: child.inputSchema,
328+
freeform: registration.freeform !== undefined,
327329
output: child.outputSchema ?? Schema.NullOr(Schema.String),
328330
execute: (input) => Run.use((run) => run.executeTool(name, registration, input)),
329331
})

‎packages/core/src/model.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export const mergeCapabilities = (config: Partial<Capabilities>, base: Capabilit
3333
const fallback = base ?? Capabilities.default()
3434
return {
3535
tools: config.tools ?? fallback.tools,
36+
freeform: (config.freeform ?? base?.freeform)?.slice(),
3637
input: [...(config.input ?? fallback.input)],
3738
output: [...(config.output ?? fallback.output)],
3839
temperature: config.temperature ?? base?.temperature,

‎packages/core/src/models-dev.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ConfigProvider } from "@opencode/schema/config/provider"
44
import { MaxTokensField, MediaInput } from "@opencode/schema/model-compatibility"
55
import { ModelsDev } from "@opencode/schema/models-dev"
66
import { Money } from "@opencode/schema/money"
7+
import { FreeformFormat } from "@opencode/schema/tool"
78
import { App } from "./app.js"
89
import { Hash } from "@opencode/util/hash"
910
import { FSUtil } from "@opencode/util/fs-util"
@@ -69,6 +70,12 @@ type SourceCost = typeof SourceCost.Type
6970
// entry this version doesn't understand is skipped instead of failing the model.
7071
const SourceApi = Schema.Struct({
7172
base_url: Schema.optional(Schema.String),
73+
capabilities: Schema.optional(
74+
Schema.Struct({
75+
// Format names this version doesn't know are skipped when the route is built.
76+
tools: Schema.optional(Schema.Struct({ freeform: Schema.optional(Schema.Array(Schema.String)) })),
77+
}),
78+
),
7279
sdk: Schema.optional(
7380
Schema.Struct({ aisdk: Schema.optional(Schema.String), opencodeai: Schema.optional(Schema.String) }),
7481
),
@@ -136,6 +143,7 @@ const decodeProvider = Schema.decodeUnknownOption(SourceProvider)
136143
const decodeContext = Schema.decodeUnknownOption(ContextCondition)
137144
const decodeMaxTokensField = Schema.decodeUnknownOption(MaxTokensField)
138145
const decodeMediaInput = Schema.decodeUnknownOption(MediaInput)
146+
const knownFreeformFormat = Schema.is(FreeformFormat)
139147
const decodeStatus = Schema.decodeUnknownOption(Schema.Literals(["alpha", "beta", "deprecated"]))
140148

141149
export type Snapshot = {
@@ -146,6 +154,7 @@ export type Snapshot = {
146154

147155
type Route = {
148156
readonly package: string
157+
readonly freeform?: Model.Capabilities["freeform"]
149158
readonly baseURL?: string
150159
readonly compatibility?: Model.Compatibility
151160
}
@@ -272,6 +281,7 @@ function route(providerID: Provider.ID, model: SourceModel, unknown: Set<string>
272281
}
273282
return {
274283
package: packageName,
284+
freeform: api.capabilities?.tools?.freeform?.filter(knownFreeformFormat),
275285
// An empty base_url is how models.dev says it has no URL for the API.
276286
...(BUILDS_OWN_URL.has(packageName) || !api.base_url ? {} : { baseURL: api.base_url }),
277287
...(Object.keys(compatibility).length > 0 ? { compatibility } : {}),
@@ -441,6 +451,7 @@ function modelInfo(
441451
settings: Object.keys(settings).length === 0 ? undefined : settings,
442452
capabilities: {
443453
tools: model.capabilities.tools.supported,
454+
...(source.route.freeform && { freeform: source.route.freeform }),
444455
input: modalities(model.modalities.input),
445456
output: modalities(model.modalities.output),
446457
temperature: model.capabilities.temperature,

0 commit comments

Comments
 (0)