Skip to content

feat(ai): let freeform tools set other parameters on an order-free first line - #65849

Merged
rekram1-node merged 6 commits into
devfrom
freeform-options
Nov 24, 2026
Merged

rekram1-node merged 6 commits into
devfrom
freeform-options

Conversation

@rekram1-node

@rekram1-node rekram1-node commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

With full_codemode, GPT can now set execute's timeout and background while still writing the code as raw text. The model puts them on an optional first line, // @options: {"timeout": 5000, "background": true}. Keys can come in any order and spaces are allowed. Any freeform tool can do the same by naming its raw-text field:

 // packages/core/src/codemode/tool.ts
-    freeform: { type: "text" },
+    freeform: { type: "text", field: "code" },

How it works

Tool.Freeform keeps its three formats (text, regex, lark). Each one gets an optional field. If field is left out, nothing changes: the tool still needs exactly one required string parameter. If it is set, that parameter must be a required string, and the tool's other parameters go on the first line. packages/ai owns everything about the line:

resolve(tool, model takes lark?)
  other parameters = input schema minus field
  none                          -> custom tool exactly as before
  a value type it can't write   -> JSON tool, as before
  no lark and body isn't text   -> JSON tool
  otherwise                     -> custom tool
      description += how to write the line, built from the schema (names, types, descriptions)
      grammar      = line + body when the model takes lark, none when it only takes text

line grammar
  // @options: { "key": value, ... }\n   spaces allowed after { : , and before }
  keys in any order: one rule, ff_pair = "key" : value | ...
  required keys    -> the line is mandatory
  no required keys -> the call can skip the line; then the text can't start with "// @options:"
  values: boolean, integer (respects minimum / exclusiveMinimum), number, JSON string, non-empty enum
  body: text -> any text; regex -> the pattern; lark -> the tool's grammar with its start renamed to fb_start

parse(raw)                       (Responses and Chat, streamed or done-only)
  no line, or no newline after it -> { field: raw }
  line holding a JSON object      -> { ...options, field: rest }, line saved as providerMetadata[key].header
                                     the tool's own schema checks the keys and values, as for a JSON call
  line that isn't a JSON object   -> raw text, which fails through the existing malformed-JSON path

toRaw(input, header)             (replay)
  saved header parses to the same values as input -> header verbatim + "\n" + field
  otherwise (another model's call, a hook edited the input) -> "// @options: " + JSON + "\n" + field

Core changes stay small:

  • execute declares { type: "text", field: "code" } in both modes.
  • model-resolver.ts passes the catalog's freeform formats into the AI model's capabilities.tools.freeform. That is how packages/ai knows whether it may send a Lark grammar. Models that only take text get the line description and the parser, but no grammar.

Two smaller fixes in the same code:

  • Responses no longer parses a custom call twice when it finishes.
  • When response.completed finishes custom calls that never got output_item.done, it now closes them first. Before, their JSON fragment stayed unclosed and they failed as malformed.

Trade-offs

  • Replay is exact without a canonical form. Saving the line (usually 30–60 bytes, only on calls that have one) means the grammar doesn't have to force one spelling. The model can write keys in any order with natural spacing, and numbers aren't restricted. Replays still match byte for byte, so the prompt cache and WebSocket continuation keep working.
  • No new error plumbing. A bad line fails like any bad tool input: values the tool's schema rejects get the normal tool error, and a line that isn't JSON gets the existing malformed-input error. The grammar lets a key repeat (JSON takes the last one) rather than growing a rule per key subset; the saved line still replays exactly.
  • Body grammars must not accept text starting with // @options:. If a lark or regex body could, a call without the line would be read as having one. patch's grammar can't.
  • Tool name and wire shape don't change. The tool is still named execute and goes out as a custom tool, as on dev, so the gateway's tool checks see the same thing.
  • The schema change is additive: field is optional. It isn't part of the server HttpApi, so the generated client doesn't change.

Checks

  • bun test in packages/ai: 2303 pass. Tests cover any key order, spaces, CRLF, exact replay of a spaced out-of-order line, a fresh line when the input changed, number/string/enum values, required keys, a composed body grammar, a text-only model (no grammar, still parsed), a non-JSON line failing as malformed, a missing newline, Chat, and the response.completed fallback.

  • packages/core: tool-execute, session-runner and session-model-request-hooks pass.

  • bun typecheck in ai and core, typecheck:tsc in ai, bun run check at the root.

  • Live with OPENCODE_FLAGS=full_codemode on openai/gpt-6.2-sol, OpenAI accepted the grammar on every request, including steps that replayed earlier calls:

    call the model wrote stored input
    plain return 1+1; { code }
    timeout // @options: {"timeout": 5000} { timeout: 5000, code }
    both, timeout first // @options: {"timeout":7000,"background":true} { timeout: 7000, background: true, code }, ran as a background job
    background // @options: {"background": true} { background: true, code }, ran as a background job

Added by the opencode bot (AI-generated).

Public API: adds optional field to every Tool.Freeform form (backwards compatible)

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The approach looks sound: the options line, grammar generation and parsing all stay in packages/ai, and core only declares the line on execute. With timeout and background the canonical-JSON round trip holds. I couldn't check the live OpenAI flow (no credentials). Unit and provider tests pass in packages/ai and packages/core, and tsc is clean in ai, core and schema.

Public API: Tool.Freeform (in @opencode/schema/tool, and so the plugin and @opencode/ai tool definitions) gains a lark form with field, options: { prefix, description } and an optional grammar. This is additive and backwards compatible: existing text, regex and lark definitions and FreeformFormat are unchanged.

One generic edge case is worth fixing: the number rules let the model write values whose replay doesn't match what it wrote (see inline comment).

if (Array.isArray(schema.enum)) return `(${schema.enum.map((item) => larkString(encodeJson(item))).join(" | ")})`
if (schema.type === "boolean") return '("true" | "false")'
if (schema.type === "string") return '/"(?:[^"\\\\\\x00-\\x1f]|\\\\["\\\\bfnrt])*"/'
if (schema.type === "number") return "/-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "exact replay" guarantee doesn't hold for number fields: this rule allows 1.0, 1e2 and -0, but toRaw writes them back as 1, 100 and 0. The integer rule on line 93 has the same problem with -0. Replay and WebSocket continuation would then see text the model didn't write. This doesn't affect execute (timeout is a positive integer), but the feature is generic. Could you restrict these regexes to the forms JSON.stringify produces (no trailing-zero fractions, no exponents, no -0), or leave number out of the supported types so such tools fall back to JSON?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: number fields are no longer supported, so such tools fall back to JSON, and the integer rule no longer allows -0. Every remaining rule only accepts the form JSON.stringify writes back.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: in a81158349, valueRule now has no number branch, so a number option makes resolve return undefined and the tool falls back to JSON. The integer rule is now /0|-?[1-9][0-9]*/, so it no longer accepts -0. The string rule only allows the escapes JSON.stringify writes: \", \\, \b, \f, \n, \r, \t. Booleans and enums were already canonical.

One small gap is left. A large integer like 12345678901234567890 parses to 12345678901234567000, so replay changes the text. For timeout that's a huge number of milliseconds, so it's very unlikely to matter. Capping the regex at 15 digits (/[1-9][0-9]{0,14}/ and similar) would rule it out; it's fine to skip.

I ran test/openai-freeform.test.ts at pr/head in a temporary worktree: 10 tests pass, including the new number fallback case. I didn't change anything in repo/. The bun.lock modification there was already present and I left it alone.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: integer rules now stop at 15 digits, so parsing can't round them.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cap works. In 3cf5e3fd1, all three integer rules are bounded: /[1-9][0-9]{0,14}/, /0|[1-9][0-9]{0,14}/ and /0|-?[1-9][0-9]{0,14}/ (openai-freeform.ts:94-95). The largest value they accept is 999,999,999,999,999, which is below 2^53 (about 9.007e15). Every accepted integer is exact as a double, and JSON.stringify writes it back unchanged. With this, every value rule the grammar accepts replays exactly. Bounded {m,n} repetition is ordinary regex syntax in Lark/llguidance, but I haven't sent the new grammar to OpenAI.

What I ran, in a temporary worktree at pr/head (since removed):

  • packages/ai, test/openai-freeform.test.ts: 10 tests pass.
  • packages/core, test/tool-execute.test.ts: 43 pass and 1 fails, and the failure comes from my setup, not the PR. My symlinked node_modules pointed @opencode/ai at the old packages/ai source in repo/, which still has [0-9]*. The failing assertion is the one your commit updated to {0,14}, so it should pass in a proper install.

I didn't change anything in repo/. The bun.lock modification there was already present and I left it alone.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new commits fix the earlier replay point. number fields now fall back to a JSON tool, and the integer rules no longer allow -0 and stop at 15 digits, so option values the model writes replay exactly. I re-ran the freeform tests in packages/ai and tool-execute in packages/core; both pass, and tsc is clean in packages/ai. I still couldn't check the live OpenAI flow (no credentials). The public API impact is unchanged: the additive Tool.Freeform options form stays backwards compatible. No new concerns.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new commit sorts option keys by name instead of schema order. The grammar and toRaw both use the same sorted fields, so a line the model writes still replays exactly. The earlier number and integer fixes are still in place. I re-ran the freeform tests in packages/ai and tool-execute in packages/core, and tsc is clean in packages/ai. I still couldn't check the live OpenAI flow (no credentials). The public API impact is unchanged: the additive Tool.Freeform options form stays backwards compatible. No new concerns.

@rekram1-node rekram1-node changed the title feat(ai): let freeform tools set optional fields on a grammar-checked options line feat(ai): let freeform tools set other parameters on an order-free first line Nov 23, 2026

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The redesign looks sound. Saving the model's line as header makes replay exact without a canonical spelling, which covers my earlier point about numbers. I checked it by running parse and toRaw on out-of-order, spaced, CRLF and 1.0/-0 lines (all replay byte for byte), on a line with nothing after it (error) and on plain text. I also read the Responses close paths for done-only calls and response.completed, plus the Chat close path. The full packages/ai suite and the related packages/core tests pass, and tsc is clean in ai, schema and core. I couldn't check the live OpenAI flow (no credentials).

Public API, all additive and backwards compatible: Tool.Freeform (text, regex, lark) gains an optional field, and ToolInputError in @opencode/ai gains an optional message. The server HTTP API is unchanged. No new concerns.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This push is a rebase onto dev: git range-diff shows the PR's five commits unchanged. The freeform tests in packages/ai and tool-execute / session-runner in packages/core still pass on the new head. I still couldn't check the live OpenAI flow (no credentials). The public API impact is unchanged: an optional field on Tool.Freeform and an optional message on the AI ToolInputError event, both backwards compatible. No new concerns.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The simplification looks sound. Keys now share one grammar rule, a tool's own grammar only has its start renamed, and a bad line fails through the existing malformed-input path. The saved line still replays byte for byte, including when a key repeats. The full packages/ai suite and the related packages/core tests pass, and tsc is clean in ai and core. I couldn't check the live OpenAI flow (no credentials). Public API: the only change left is an optional field on every Tool.Freeform form, which is backwards compatible (ToolInputError.message is no longer added). No new concerns.

@rekram1-node
rekram1-node merged commit e33e872 into dev Nov 24, 2026
14 checks passed
@rekram1-node
rekram1-node deleted the freeform-options branch November 24, 2026 00:11
beyondChang pushed a commit to beyondChang/opencode that referenced this pull request Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant