From 53f2d631dfd220bba3aaf587b35f080be28659cd Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:15:25 -0600 Subject: [PATCH] feat(core): use freeform tool input on models that support it (#61703) --- packages/ai/src/schema/messages.ts | 8 +-- .../client/src/promise/generated/types.ts | 11 +++- packages/codemode/README.md | 4 ++ packages/codemode/src/tool-runtime.ts | 8 ++- packages/codemode/src/tool-schema.ts | 54 ++++++++++++------- packages/codemode/src/tool.ts | 7 +++ packages/codemode/test/codemode.test.ts | 28 ++++++++++ packages/core/src/codemode/tool.ts | 2 + packages/core/src/model.ts | 1 + packages/core/src/models-dev.ts | 11 ++++ packages/core/src/session/model-request.ts | 6 ++- packages/core/src/tool/patch-grammar.txt | 19 +++++++ packages/core/src/tool/plugin/patch.ts | 2 + packages/core/src/tool/runtime.ts | 1 + packages/core/test/config/provider.test.ts | 3 +- packages/core/test/models.test.ts | 18 ++++++- .../test/session-model-request-hooks.test.ts | 36 +++++++++++++ packages/core/test/tool-execute.test.ts | 26 +++++++++ packages/core/test/tool-patch.test.ts | 7 ++- packages/plugin/src/promise/adapter.ts | 1 + packages/protocol/openapi.json | 16 ++++++ packages/schema/src/config/provider.ts | 1 + packages/schema/src/model.ts | 3 ++ packages/schema/src/tool.ts | 13 +++++ .../src/docs/content/build/plugins/effect.mdx | 2 + .../src/docs/content/build/plugins/server.mdx | 19 +++++++ services/site/src/docs/content/models.mdx | 5 +- 27 files changed, 279 insertions(+), 33 deletions(-) create mode 100644 packages/core/src/tool/patch-grammar.txt diff --git a/packages/ai/src/schema/messages.ts b/packages/ai/src/schema/messages.ts index 30dc991403f..2e7007c08a9 100644 --- a/packages/ai/src/schema/messages.ts +++ b/packages/ai/src/schema/messages.ts @@ -369,12 +369,8 @@ export const Message = withStatics(messageSchema, { * Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format * write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input. */ -export const Freeform = Schema.Union([ - Schema.Struct({ type: Schema.Literal("text") }), - Schema.Struct({ type: Schema.Literal("regex"), pattern: Schema.String }), - Schema.Struct({ type: Schema.Literal("lark"), grammar: Schema.String }), -]).annotate({ identifier: "LLM.Freeform" }) -export type Freeform = Schema.Schema.Type +export const Freeform = Tool.Freeform +export type Freeform = Tool.Freeform const toolDefinitionFields = { name: Schema.String, diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index d2a2b2d4a19..ec9d1dad0fe 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -186,7 +186,7 @@ export type ModelCacheFormat = "anthropic" | "alibaba" export type ModelMediaInput = "assets" | "state" | "root" -export type ModelCapabilities = { tools: boolean; input: Array; output: Array; temperature?: boolean } +export type ToolFreeformFormat = "text" | "regex" | "lark" export type MoneyUSDPerMillionTokens = number @@ -713,6 +713,14 @@ export type ProviderCompatibility = { mediaInput?: ModelMediaInput } +export type ModelCapabilities = { + tools: boolean + freeform?: Array + input: Array + output: Array + temperature?: boolean +} + export type ModelCost = { tier?: { type: "context"; size: number } input: MoneyUSDPerMillionTokens @@ -983,6 +991,7 @@ export type UsageLimitsGo = { rolling: UsageLimitsMeter; weekly: UsageLimitsMete export type ConfigModelCapabilities = { tools?: boolean + freeform?: Array input?: Array output?: Array temperature?: boolean diff --git a/packages/codemode/README.md b/packages/codemode/README.md index fec1a09c457..7d663d559d2 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -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 diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts index ed4b09c4f00..ee914c94dfb 100644 --- a/packages/codemode/src/tool-runtime.ts +++ b/packages/codemode/src/tool-runtime.ts @@ -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 = (visible: VisibleTool): 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 = ( 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", diff --git a/packages/codemode/src/tool-schema.ts b/packages/codemode/src/tool-schema.ts index 04e8bb5e1ed..d55cc0d6c51 100644 --- a/packages/codemode/src/tool-schema.ts +++ b/packages/codemode/src/tool-schema.ts @@ -252,24 +252,9 @@ export type InputProperty = { export const inputProperties = (tool: Tool): Array => { try { - const document = isEffectSchema(tool.input) - ? (Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" }) as { - readonly schema: JsonSchema - readonly definitions: Readonly> - }) - : { - 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 = (tool: Tool): Array => { } } +/** A freeform tool whose input is one required string field takes that string directly: `tools.patch(patchText: string)`. */ +export const stringParameter = (tool: Tool) => { + 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 = (tool: Tool) => { + const document = isEffectSchema(tool.input) + ? (Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" }) as { + readonly schema: JsonSchema + readonly definitions: Readonly> + }) + : { + 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 = (tool: Tool, pretty = false): string => isEffectSchema(tool.input) ? toTypeScript(tool.input, false, pretty) : jsonSchemaToTypeScript(tool.input, pretty) diff --git a/packages/codemode/src/tool.ts b/packages/codemode/src/tool.ts index 108bfe25565..1703d5d64cc 100644 --- a/packages/codemode/src/tool.ts +++ b/packages/codemode/src/tool.ts @@ -96,6 +96,7 @@ export type Tool = { readonly _tag: "CodeModeTool" readonly description: string readonly input: SchemaType + readonly freeform?: boolean readonly output: SchemaType | undefined readonly execute: (input: unknown, context?: ToolContext) => Effect.Effect readonly mode?: Idempotent | Durable | undefined @@ -109,6 +110,11 @@ type ResultType = S extends undefined ? void : S extends Schema.Decoder = { 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, ResultType, R> @@ -172,6 +178,7 @@ export const make = spec(input as InputType, context), diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts index 86469953740..121fba9d2bb 100644 --- a/packages/codemode/test/codemode.test.ts +++ b/packages/codemode/test/codemode.test.ts @@ -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", + "tools.plain({\n /** Page URL */\n url: string,\n}): Promise", + ]) + 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", diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 067ec60abd2..d741e9853a5 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -92,6 +92,7 @@ export const create = ( name: "execute", description, input: CodeMode.Input, + freeform: { type: "text" }, output: ExecuteOutput, execute: ({ code }, context) => Effect.gen(function* () { @@ -324,6 +325,7 @@ function inventoryTools(inventory: Inventory) { getNode(root, qualifiedName(registration)).tool = Tool.make({ description: child.description, input: child.inputSchema, + freeform: registration.freeform !== undefined, output: child.outputSchema ?? Schema.NullOr(Schema.String), execute: (input) => Run.use((run) => run.executeTool(name, registration, input)), }) diff --git a/packages/core/src/model.ts b/packages/core/src/model.ts index 88b73711c5e..f3715b4e6df 100644 --- a/packages/core/src/model.ts +++ b/packages/core/src/model.ts @@ -33,6 +33,7 @@ export const mergeCapabilities = (config: Partial, base: Capabilit const fallback = base ?? Capabilities.default() return { tools: config.tools ?? fallback.tools, + freeform: (config.freeform ?? base?.freeform)?.slice(), input: [...(config.input ?? fallback.input)], output: [...(config.output ?? fallback.output)], temperature: config.temperature ?? base?.temperature, diff --git a/packages/core/src/models-dev.ts b/packages/core/src/models-dev.ts index 56886854cab..7d35d783cee 100644 --- a/packages/core/src/models-dev.ts +++ b/packages/core/src/models-dev.ts @@ -4,6 +4,7 @@ import { ConfigProvider } from "@opencode/schema/config/provider" import { MaxTokensField, MediaInput } from "@opencode/schema/model-compatibility" import { ModelsDev } from "@opencode/schema/models-dev" import { Money } from "@opencode/schema/money" +import { FreeformFormat } from "@opencode/schema/tool" import { App } from "./app.js" import { Hash } from "@opencode/util/hash" import { FSUtil } from "@opencode/util/fs-util" @@ -69,6 +70,12 @@ type SourceCost = typeof SourceCost.Type // entry this version doesn't understand is skipped instead of failing the model. const SourceApi = Schema.Struct({ base_url: Schema.optional(Schema.String), + capabilities: Schema.optional( + Schema.Struct({ + // Format names this version doesn't know are skipped when the route is built. + tools: Schema.optional(Schema.Struct({ freeform: Schema.optional(Schema.Array(Schema.String)) })), + }), + ), sdk: Schema.optional( Schema.Struct({ aisdk: Schema.optional(Schema.String), opencodeai: Schema.optional(Schema.String) }), ), @@ -136,6 +143,7 @@ const decodeProvider = Schema.decodeUnknownOption(SourceProvider) const decodeContext = Schema.decodeUnknownOption(ContextCondition) const decodeMaxTokensField = Schema.decodeUnknownOption(MaxTokensField) const decodeMediaInput = Schema.decodeUnknownOption(MediaInput) +const knownFreeformFormat = Schema.is(FreeformFormat) const decodeStatus = Schema.decodeUnknownOption(Schema.Literals(["alpha", "beta", "deprecated"])) export type Snapshot = { @@ -146,6 +154,7 @@ export type Snapshot = { type Route = { readonly package: string + readonly freeform?: Model.Capabilities["freeform"] readonly baseURL?: string readonly compatibility?: Model.Compatibility } @@ -272,6 +281,7 @@ function route(providerID: Provider.ID, model: SourceModel, unknown: Set } return { package: packageName, + freeform: api.capabilities?.tools?.freeform?.filter(knownFreeformFormat), // An empty base_url is how models.dev says it has no URL for the API. ...(BUILDS_OWN_URL.has(packageName) || !api.base_url ? {} : { baseURL: api.base_url }), ...(Object.keys(compatibility).length > 0 ? { compatibility } : {}), @@ -441,6 +451,7 @@ function modelInfo( settings: Object.keys(settings).length === 0 ? undefined : settings, capabilities: { tools: model.capabilities.tools.supported, + ...(source.route.freeform && { freeform: source.route.freeform }), input: modalities(model.modalities.input), output: modalities(model.modalities.output), temperature: model.capabilities.temperature, diff --git a/packages/core/src/session/model-request.ts b/packages/core/src/session/model-request.ts index 01288817932..60c73d068be 100644 --- a/packages/core/src/session/model-request.ts +++ b/packages/core/src/session/model-request.ts @@ -328,7 +328,11 @@ export const layer = Layer.effect( cache: model.cache?.ttl === undefined ? undefined : { ttl: model.cache.ttl }, system: shaped.system, messages: boundImages(unsupportedParts(shaped.messages, model.capabilities, model.model.provider)), - tools: Array.from(hooked, ([name, t]) => ({ ...t, name })), + tools: Array.from(hooked, ([name, t]) => ({ + ...t, + name, + freeform: t.freeform && model.capabilities.freeform?.includes(t.freeform.type) ? t.freeform : undefined, + })), toolChoice: input.toolChoice, ...generation, providerOptions: Object.keys(providerOptions).length === 0 ? undefined : providerOptions, diff --git a/packages/core/src/tool/patch-grammar.txt b/packages/core/src/tool/patch-grammar.txt new file mode 100644 index 00000000000..5aa41b0af79 --- /dev/null +++ b/packages/core/src/tool/patch-grammar.txt @@ -0,0 +1,19 @@ +start: begin_patch hunk+ end_patch +begin_patch: "*** Begin Patch" LF +end_patch: "*** End Patch" LF? + +hunk: add_hunk | delete_hunk | update_hunk +add_hunk: "*** Add File: " filename LF add_line+ +delete_hunk: "*** Delete File: " filename LF +update_hunk: "*** Update File: " filename LF change_move? change? + +filename: /(.+)/ +add_line: "+" /(.*)/ LF -> line + +change_move: "*** Move to: " filename LF +change: (change_context | change_line)+ eof_line? +change_context: ("@@" | "@@ " /(.+)/) LF +change_line: ("+" | "-" | " ") /(.*)/ LF +eof_line: "*** End of File" LF + +%import common.LF diff --git a/packages/core/src/tool/plugin/patch.ts b/packages/core/src/tool/plugin/patch.ts index ab4045e1874..58225b37b17 100644 --- a/packages/core/src/tool/plugin/patch.ts +++ b/packages/core/src/tool/plugin/patch.ts @@ -15,6 +15,7 @@ import { FileAccess } from "../../file-access.js" import { Patch } from "@opencode/util/patch" import { Permission } from "../../permission.js" import DESCRIPTION from "../patch.txt" +import GRAMMAR from "../patch-grammar.txt" import { fileDiff } from "./file-diff.js" export const name = "patch" @@ -82,6 +83,7 @@ export const Plugin = { options: { codemode: false, permission: "edit" }, description: DESCRIPTION, input: Input, + freeform: { type: "lark", grammar: GRAMMAR }, output: Output, execute: (input, context) => { const applied: Array = [] diff --git a/packages/core/src/tool/runtime.ts b/packages/core/src/tool/runtime.ts index 194ce35dcd9..5e41681abca 100644 --- a/packages/core/src/tool/runtime.ts +++ b/packages/core/src/tool/runtime.ts @@ -24,6 +24,7 @@ export const definition = (tool: Tool.Info): ToolDefinition => ({ name: effectiveName(tool), description: tool.description, inputSchema: inputJsonSchema(tool.input), + ...(tool.freeform && { freeform: tool.freeform }), ...(tool.output === undefined ? {} : { outputSchema: outputJsonSchema(tool.output) }), }) diff --git a/packages/core/test/config/provider.test.ts b/packages/core/test/config/provider.test.ts index f68654c6956..6fb9b6e19d5 100644 --- a/packages/core/test/config/provider.test.ts +++ b/packages/core/test/config/provider.test.ts @@ -1067,7 +1067,7 @@ describe("ConfigProviderPlugin.Plugin", () => { models: { reasoner: { releaseDate: "2026-02-03", - capabilities: { temperature: false }, + capabilities: { temperature: false, freeform: ["text", "regex"] }, compatibility: { reasoningField: "reasoning_content" }, }, }, @@ -1080,6 +1080,7 @@ describe("ConfigProviderPlugin.Plugin", () => { const model = required(yield* models.get(Provider.ID.make("custom"), Model.ID.make("reasoner"))) expect(model.time.released).toBe(Date.UTC(2026, 1, 3)) expect(model.capabilities.temperature).toBe(false) + expect(model.capabilities.freeform).toEqual(["text", "regex"]) expect(model.compatibility?.reasoningField).toBe("reasoning_content") }), ) diff --git a/packages/core/test/models.test.ts b/packages/core/test/models.test.ts index 933c1b8c19e..31897029c7d 100644 --- a/packages/core/test/models.test.ts +++ b/packages/core/test/models.test.ts @@ -278,12 +278,23 @@ describe("ModelsDev Service", () => { responses: { base_url: "https://api.acme.test/v1", sdk: { aisdk: "@ai-sdk/openai", opencodeai: "@opencode/ai/providers/openai/responses" }, + capabilities: { tools: { freeform: ["text", "future-grammar", "lark"] } }, + }, + "chat-completions": { + base_url: "https://other.acme.test/v1", + sdk: { aisdk: "@ai-sdk/openai" }, + capabilities: { tools: { freeform: ["regex"] } }, }, - "chat-completions": { base_url: "https://other.acme.test/v1", sdk: { aisdk: "@ai-sdk/openai" } }, }, }), "acme-fallback": sourceModel("acme-fallback", { - api: { messages: { base_url: "https://claude.acme.test/v1", sdk: { aisdk: "@ai-sdk/anthropic" } } }, + api: { + messages: { + base_url: "https://claude.acme.test/v1", + sdk: { aisdk: "@ai-sdk/anthropic" }, + capabilities: { tools: { freeform: ["future-grammar"] } }, + }, + }, }), }, }, @@ -316,8 +327,11 @@ describe("ModelsDev Service", () => { const acmeModel = (id: string) => acme?.models.find((model) => model.id === id) expect(acmeModel("acme-responses")?.package).toBe("@opencode/ai/providers/openai/responses") expect(acmeModel("acme-responses")?.settings).toBeUndefined() + expect(acmeModel("acme-responses")?.capabilities.freeform).toEqual(["text", "lark"]) + expect(acmeModel("acme-1")?.capabilities.freeform).toBeUndefined() // Without an opencode package, the AI SDK package maps to the native one as before. expect(acmeModel("acme-fallback")?.package).toBe("@opencode/ai/providers/anthropic") + expect(acmeModel("acme-fallback")?.capabilities.freeform).toEqual([]) expect(acmeModel("acme-fallback")?.settings).toEqual({ baseURL: "https://claude.acme.test/v1" }) const azureModel = (id: string) => azure?.models.find((model) => model.id === id) diff --git a/packages/core/test/session-model-request-hooks.test.ts b/packages/core/test/session-model-request-hooks.test.ts index 32b6eab685c..94d7ec16360 100644 --- a/packages/core/test/session-model-request-hooks.test.ts +++ b/packages/core/test/session-model-request-hooks.test.ts @@ -41,6 +41,42 @@ const transport = SessionModelTransport.Service.of({ }) describe("SessionModelRequest HTTP hooks", () => { + it.effect( + "advertises only supported freeform formats without removing tools or changing the shared definitions", + () => + Effect.gen(function* () { + const inputSchema = { type: "object", properties: { value: { type: "string" } }, required: ["value"] } + const formats = [ + { type: "text" }, + { type: "regex", pattern: "[0-9]+" }, + { type: "lark", grammar: 'start: "x"' }, + ] as const + const tools = { + definitions: formats.map( + (freeform) => new ToolDefinition({ name: freeform.type, description: "", inputSchema, freeform }), + ), + execute: () => Effect.die("unused tool execution"), + } + const requests = yield* SessionModelRequest.Service.pipe(Effect.provide(SessionModelRequest.layer)) + const cases: Array = [undefined, [], ["text", "lark"], ["regex"]] + for (const supported of cases) { + const prepared = yield* requests.primary({ + session, + agent: Agent.ID.make("build"), + model: { ...model, capabilities: { ...model.capabilities, freeform: supported } }, + system: [], + messages: [], + tools, + }) + expect( + prepared.request.tools.map((tool) => tool.type === "tool" && [tool.name, tool.inputSchema, tool.freeform]), + ).toEqual( + formats.map((format) => [format.type, inputSchema, supported?.includes(format.type) ? format : undefined]), + ) + } + }).pipe(Effect.provideService(SessionModelTransport.Service, transport)), + ) + it.effect("tags every Session request kind on http.request and http.response", () => Effect.gen(function* () { const hooks = yield* PluginHooks.Service diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index c4cf56ccf2b..03d4b4683ad 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -44,6 +44,32 @@ const vmFlag = (codemode_vm: boolean): Flag.Interface => { const createCodeMode = (tools: ReadonlyMap, permission = allowAll, flag = vmFlag(false)) => CodeModeTool.create({ tools }, (_, tool, input, context) => execute(tool, input, context), permission, flag) +test("execute takes raw code as freeform text, and Code Mode calls freeform tools with a string", async () => { + const input = Schema.Struct({ text: Schema.NonEmptyString }) + const send = { + name: "send", + description: "Send text", + input, + output: Schema.String, + execute: ({ text }) => Effect.succeed({ output: text }), + } satisfies Info + const tools = new Map([ + ["echo", { ...send, name: "echo" }], + ["send", { ...send, freeform: { type: "text" } }], + ]) + const codeMode = createCodeMode(tools) + expect(codeMode.freeform).toEqual({ type: "text" }) + expect(CodeModeTool.catalog({ tools }).tools.map((tool) => "signature" in tool && tool.signature)).toEqual([ + "tools.echo({\n /** @minLength 1 */\n text: string,\n}): Promise", + "tools.send(/** @minLength 1 */ text: string): Promise", + ]) + const calls = await Effect.runPromise( + codeMode.execute({ code: 'return [await tools.send("first"), await tools.send({text: "second"})]' }, context), + ) + expect(JSON.parse(calls.output.output)).toEqual(["first", "second"]) + expect(calls.output.toolCalls.map((call) => call.input)).toEqual([{ text: "first" }, { text: "second" }]) +}) + test("execute describes invariant Code Mode behavior", () => { expect(createCodeMode(new Map()).description).toBe( [ diff --git a/packages/core/test/tool-patch.test.ts b/packages/core/test/tool-patch.test.ts index 3a571d2de2b..9a0531880c0 100644 --- a/packages/core/test/tool-patch.test.ts +++ b/packages/core/test/tool-patch.test.ts @@ -202,7 +202,12 @@ describe("PatchTool", () => { Effect.andThen( withTool(tmp.path, (registry) => Effect.gen(function* () { - expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["patch", "execute"]) + const definitions = yield* toolDefinitions(registry) + expect(definitions.map((tool) => tool.name)).toEqual(["patch", "execute"]) + expect(definitions[0]?.freeform).toEqual({ + type: "lark", + grammar: expect.stringContaining('"*** Begin Patch"'), + }) const settled = yield* executeTool( registry, call( diff --git a/packages/plugin/src/promise/adapter.ts b/packages/plugin/src/promise/adapter.ts index a45c2fc5909..304fc2e46d5 100644 --- a/packages/plugin/src/promise/adapter.ts +++ b/packages/plugin/src/promise/adapter.ts @@ -535,6 +535,7 @@ export function fromPromise(plugin: Plugin) { update(value) Object.assign(tool, value, { output: value.output, + freeform: value.freeform, options: value.options, execute: (input: Parameters[0], context: Tool.Context) => executePromiseTool(value, input, context), diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 85e5c6e33a0..b6f67e57f74 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -16804,6 +16804,12 @@ "tools": { "type": "boolean" }, + "freeform": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Tool.FreeformFormat" + } + }, "input": { "type": "array", "items": { @@ -20512,6 +20518,12 @@ "tools": { "type": "boolean" }, + "freeform": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Tool.FreeformFormat" + } + }, "input": { "type": "array", "items": { @@ -25084,6 +25096,10 @@ "required": ["type", "uri", "mime"], "additionalProperties": false }, + "Tool.FreeformFormat": { + "type": "string", + "enum": ["text", "regex", "lark"] + }, "Tool.TextContent": { "type": "object", "properties": { diff --git a/packages/schema/src/config/provider.ts b/packages/schema/src/config/provider.ts index e0c1f8d4fdb..55c5b5893af 100644 --- a/packages/schema/src/config/provider.ts +++ b/packages/schema/src/config/provider.ts @@ -86,6 +86,7 @@ class ModelConfig extends Schema.Class("Config.Model")({ // Partial: unset fields fall back to the base model's capabilities, then the defaults. capabilities: Capabilities.mapFields((fields) => ({ tools: optional(fields.tools), + freeform: fields.freeform, input: optional(fields.input), output: optional(fields.output), temperature: fields.temperature, diff --git a/packages/schema/src/model.ts b/packages/schema/src/model.ts index 8d198338b1f..f3e464197d2 100644 --- a/packages/schema/src/model.ts +++ b/packages/schema/src/model.ts @@ -5,6 +5,7 @@ import { optional, statics } from "./schema.js" import { Provider } from "./provider.js" import { Compatibility, MaxTokensField, MediaInput, ReasoningField } from "./model-compatibility.js" import { Money } from "./money.js" +import { FreeformFormat } from "./tool.js" import { ephemeral, inventory } from "./event.js" export const ID = Schema.String.pipe(Schema.brand("Model.ID")) @@ -77,6 +78,8 @@ export const Overlays = { export interface Capabilities extends Schema.Schema.Type {} export const Capabilities = Schema.Struct({ tools: Schema.Boolean, + /** Freeform tool input formats advertised by the selected API. Absent or empty means JSON tools only. */ + freeform: Schema.Array(FreeformFormat).pipe(optional), input: Schema.Array(Schema.String), output: Schema.Array(Schema.String), /** Whether the model accepts a sampling temperature. Unknown when unset. */ diff --git a/packages/schema/src/tool.ts b/packages/schema/src/tool.ts index e271ed22a5f..c2f9f017d29 100644 --- a/packages/schema/src/tool.ts +++ b/packages/schema/src/tool.ts @@ -8,6 +8,18 @@ import type { SessionMessage } from "./session-message.js" export type Metadata = Readonly> +/** Optional wire encoding of a tool's single required string field. Execution still receives the object. */ +export const Freeform = Schema.Union([ + Schema.Struct({ type: Schema.Literal("text") }), + Schema.Struct({ type: Schema.Literal("regex"), pattern: Schema.String }), + Schema.Struct({ type: Schema.Literal("lark"), grammar: Schema.String }), +]).annotate({ identifier: "Tool.Freeform" }) +export type Freeform = typeof Freeform.Type + +export const FreeformFormat = Schema.Literals(Freeform.members.map((member) => member.fields.type.literal)).annotate({ + identifier: "Tool.FreeformFormat", +}) + export const CallID = Schema.String.pipe(Schema.brand("Tool.CallID")) export type CallID = typeof CallID.Type @@ -100,6 +112,7 @@ export type Info< > = { readonly name: string readonly input: Input + readonly freeform?: Freeform readonly description: string readonly execute: (input: InputValue, context: Context) => Effect.Effect, Error> readonly output?: Output diff --git a/services/site/src/docs/content/build/plugins/effect.mdx b/services/site/src/docs/content/build/plugins/effect.mdx index da5b1652579..efa318a7215 100644 --- a/services/site/src/docs/content/build/plugins/effect.mdx +++ b/services/site/src/docs/content/build/plugins/effect.mdx @@ -1033,6 +1033,8 @@ effect: (ctx) => Call `yield* ctx.tool.reload()` after changing source data captured by the callback. Reload replays active transforms without changing their order; it does not rerun the plugin effect. +Effect tools accept the same [freeform input declaration](/build/plugins/server#freeform-tool-input) as Promise tools. If the model does not advertise that format, the tool keeps its normal object input. + Tools have an `id` containing their effective name, and `get()` returns `undefined` when that ID is not present. Use `update` and `remove` with the effective tool name, including its namespace (`acme_greeting` above). Dots in namespaces and unsupported characters in tool names become `_`. Missing names are ignored; creating a tool requires diff --git a/services/site/src/docs/content/build/plugins/server.mdx b/services/site/src/docs/content/build/plugins/server.mdx index 29d747ba2f4..665a3c7eecb 100644 --- a/services/site/src/docs/content/build/plugins/server.mdx +++ b/services/site/src/docs/content/build/plugins/server.mdx @@ -1013,6 +1013,25 @@ execute: async ({ url }, context) => { } ``` +#### Freeform tool input + +A direct tool with exactly one required string field can let the model write that string without a JSON wrapper. Set `freeform` to `{ type: "text" }`, `{ type: "regex", pattern }`, or `{ type: "lark", grammar }`. + +```ts +editor.add({ + name: "ticket", + description: "Look up a ticket by ID", + options: { codemode: false }, + input: Schema.Struct({ id: Schema.String }), + freeform: { type: "regex", pattern: "OPS-[0-9]+" }, + execute: async ({ id }) => ({ content: await lookup(id) }), +}) +``` + +If the selected model's API lists `regex` in models.dev, the model can write `OPS-42` directly. Otherwise Core omits **only** `freeform`: the model still has the `ticket` tool and calls it with `{"id":"OPS-42"}`. Missing or empty format lists mean no freeform support. The executor receives `{ id }` either way. + +Inside Code Mode (`codemode: true`), a freeform tool takes its string directly, as in `await tools.ticket("OPS-42")`. `await tools.ticket({ id: "OPS-42" })` also works. + Call `reload()` after changing source data captured by the callback. Reload replays the active transforms without changing their order; it does not rerun plugin setup. diff --git a/services/site/src/docs/content/models.mdx b/services/site/src/docs/content/models.mdx index f65262b2fc1..73f21d027e3 100644 --- a/services/site/src/docs/content/models.mdx +++ b/services/site/src/docs/content/models.mdx @@ -212,6 +212,7 @@ Use `modelID` to give an API model a friendlier catalog ID: "name": "Coding default", "capabilities": { "tools": true, + "freeform": ["text", "lark"], "input": ["text", "image"], "output": ["text"], }, @@ -229,10 +230,12 @@ Use `modelID` to give an API model a friendlier catalog ID: Here, `openai/coding-default` is the selectable reference and `gpt-6.1-sol` is sent to the provider. For a model that is not already in the catalog, OpenCode assumes: -- Tool support, text and image input, and text output. +- JSON tool support, text and image input, and text output. No freeform tool input unless `capabilities.freeform` lists the format. - A 200,000-token context limit and 32,000-token output limit. - An unspecified input limit. +OpenCode recognizes `text`, `regex`, and `lark`. Other format names from models.dev are ignored without dropping the model or its tools. If a proxy in front of a catalog model rejects freeform tools, set `capabilities.freeform` to `[]` on that model. + These are fallback assumptions, not detected capabilities. Set accurate `capabilities` and `limit` values when known; explicit values replace the fallbacks. Add `disabled: true` to hide a model from the available catalog: