mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(core): use freeform tool input on models that support it (#61703)
This commit is contained in:
parent
64bd35afa9
commit
53f2d631df
27 changed files with 279 additions and 33 deletions
|
|
@ -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<typeof Freeform>
|
||||
export const Freeform = Tool.Freeform
|
||||
export type Freeform = Tool.Freeform
|
||||
|
||||
const toolDefinitionFields = {
|
||||
name: Schema.String,
|
||||
|
|
|
|||
11
packages/client/src/promise/generated/types.ts
generated
11
packages/client/src/promise/generated/types.ts
generated
|
|
@ -186,7 +186,7 @@ export type ModelCacheFormat = "anthropic" | "alibaba"
|
|||
|
||||
export type ModelMediaInput = "assets" | "state" | "root"
|
||||
|
||||
export type ModelCapabilities = { tools: boolean; input: Array<string>; output: Array<string>; 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<ToolFreeformFormat>
|
||||
input: Array<string>
|
||||
output: Array<string>
|
||||
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<ToolFreeformFormat>
|
||||
input?: Array<string>
|
||||
output?: Array<string>
|
||||
temperature?: boolean
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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)),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ export const mergeCapabilities = (config: Partial<Capabilities>, 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,
|
||||
|
|
|
|||
|
|
@ -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<string>
|
|||
}
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
19
packages/core/src/tool/patch-grammar.txt
Normal file
19
packages/core/src/tool/patch-grammar.txt
Normal file
|
|
@ -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
|
||||
|
|
@ -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<typeof Applied.Type> = []
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ export const definition = (tool: Tool.Info<any, any>): ToolDefinition => ({
|
|||
name: effectiveName(tool),
|
||||
description: tool.description,
|
||||
inputSchema: inputJsonSchema(tool.input),
|
||||
...(tool.freeform && { freeform: tool.freeform }),
|
||||
...(tool.output === undefined ? {} : { outputSchema: outputJsonSchema(tool.output) }),
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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<typeof model.capabilities.freeform> = [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
|
||||
|
|
|
|||
|
|
@ -44,6 +44,32 @@ const vmFlag = (codemode_vm: boolean): Flag.Interface => {
|
|||
const createCodeMode = (tools: ReadonlyMap<string, Info>, 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<typeof input, typeof Schema.String>
|
||||
const tools = new Map<string, Info>([
|
||||
["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<string>",
|
||||
"tools.send(/** @minLength 1 */ text: string): Promise<string>",
|
||||
])
|
||||
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(
|
||||
[
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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<Info["execute"]>[0], context: Tool.Context) =>
|
||||
executePromiseTool(value, input, context),
|
||||
|
|
|
|||
16
packages/protocol/openapi.json
generated
16
packages/protocol/openapi.json
generated
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@ class ModelConfig extends Schema.Class<ModelConfig>("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,
|
||||
|
|
|
|||
|
|
@ -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<typeof Capabilities> {}
|
||||
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. */
|
||||
|
|
|
|||
|
|
@ -8,6 +8,18 @@ import type { SessionMessage } from "./session-message.js"
|
|||
|
||||
export type Metadata = Readonly<Record<string, any>>
|
||||
|
||||
/** 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<Input>, context: Context) => Effect.Effect<Result<Output>, Error>
|
||||
readonly output?: Output
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue