@opencode/ai 0.0.0-dev-1343 → 0.0.0-dev-1345

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -326,11 +326,11 @@ export const lowerTool = Effect.fnUntraced(function* (protocolName, tool) {
326
326
  };
327
327
  });
328
328
  export const lowerCustomTool = (tool, custom) => {
329
- const grammar = OpenAIFreeform.grammar(custom.format);
329
+ const grammar = OpenAIFreeform.grammar(custom);
330
330
  return {
331
331
  type: "custom",
332
332
  name: tool.name,
333
- description: tool.description,
333
+ description: OpenAIFreeform.description(tool, custom),
334
334
  format: grammar ? { type: "grammar", ...grammar } : { type: "text" },
335
335
  };
336
336
  };
@@ -370,7 +370,7 @@ const lowerToolCall = (part, providerMetadataKey, custom) => {
370
370
  ...(id === undefined ? {} : { id }),
371
371
  call_id: part.id,
372
372
  name: part.name,
373
- input: OpenAIFreeform.toRaw(custom, part.input),
373
+ input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[providerMetadataKey]?.header),
374
374
  };
375
375
  return {
376
376
  type: "function_call",
@@ -1062,19 +1062,20 @@ const onOutputItemDone = Effect.fnUntraced(function* (state, item) {
1062
1062
  return [state, NO_EVENTS];
1063
1063
  const custom = item.type === "custom_tool_call";
1064
1064
  const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom));
1065
- const final = { custom: state.custom.get(item.name), raw: rawInput(item) };
1066
- const input = custom ? OpenAIFreeform.fromRaw(final.custom, final.raw) : item.arguments;
1067
1065
  const registered = state.tools[item.id] !== undefined;
1068
- const closed = custom ? OpenAIFreeform.close(state.tools, [item.id], final) : undefined;
1069
- const tools = registered
1070
- ? (closed?.tools ?? state.tools)
1066
+ const started = registered
1067
+ ? state.tools
1071
1068
  : ToolStream.start(state.tools, item.id, {
1072
1069
  id: item.call_id,
1073
1070
  name: item.name,
1074
1071
  namespace: item.namespace,
1075
1072
  providerMetadata: metadata,
1076
1073
  });
1077
- const result = yield* ToolStream.finish(state.id, tools, item.id, input);
1074
+ // A custom call's final raw text sets its input, so it finishes without an override.
1075
+ const closed = custom
1076
+ ? OpenAIFreeform.close(started, [item.id], state.custom, state.providerMetadataKey, rawInput(item))
1077
+ : undefined;
1078
+ const result = yield* ToolStream.finish(state.id, closed?.tools ?? started, item.id, custom ? undefined : item.arguments);
1078
1079
  const events = [];
1079
1080
  const finished = [...(closed?.events ?? []), ...(result.events ?? [])];
1080
1081
  // A done-only call never streamed a start event, so open its lifecycle here.
@@ -1160,7 +1161,9 @@ const onResponseFinish = Effect.fnUntraced(function* (state, event) {
1160
1161
  events.push(...emitted);
1161
1162
  }
1162
1163
  // Some compatible providers omit output_item.done even after completing the response.
1163
- const pending = yield* ToolStream.finishAll(current.id, current.tools);
1164
+ const open = OpenAIFreeform.close(current.tools, Object.keys(current.tools).filter((key) => current.tools[key]?.providerMetadata?.[current.providerMetadataKey]?.custom === true), current.custom, current.providerMetadataKey);
1165
+ events.push(...open.events);
1166
+ const pending = yield* ToolStream.finishAll(current.id, open.tools);
1164
1167
  current = {
1165
1168
  ...current,
1166
1169
  tools: pending.tools,
@@ -264,12 +264,12 @@ const DONE = "[DONE]";
264
264
  const OpenAIChatStreamEvent = Schema.Union([Schema.Literal(DONE), Protocol.jsonEvent(OpenAIChatEvent)]);
265
265
  const lowerTool = (tool, options, supportsStrictMode, custom) => {
266
266
  if (custom) {
267
- const grammar = OpenAIFreeform.grammar(custom.format);
267
+ const grammar = OpenAIFreeform.grammar(custom);
268
268
  return {
269
269
  type: "custom",
270
270
  custom: {
271
271
  name: tool.name,
272
- description: tool.description,
272
+ description: OpenAIFreeform.description(tool, custom),
273
273
  format: grammar ? { type: "grammar", grammar } : { type: "text" },
274
274
  },
275
275
  cache_control: options.cacheControl?.(tool.cache),
@@ -301,7 +301,10 @@ const lowerToolCall = (part, options) => {
301
301
  return {
302
302
  id: options.toolCallID?.(part.id) ?? part.id,
303
303
  type: "custom",
304
- custom: { name: part.name, input: OpenAIFreeform.toRaw(custom, part.input) },
304
+ custom: {
305
+ name: part.name,
306
+ input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[options.providerMetadataKey]?.header),
307
+ },
305
308
  };
306
309
  return {
307
310
  id: options.toolCallID?.(part.id) ?? part.id,
@@ -1026,7 +1029,7 @@ const step = (state, event) => Effect.gen(function* () {
1026
1029
  !incompleteTools &&
1027
1030
  state.finishReason === undefined &&
1028
1031
  Object.keys(tools).length > 0
1029
- ? yield* finishTools(tools, customCalls)
1032
+ ? yield* finishTools(state, tools, customCalls)
1030
1033
  : undefined;
1031
1034
  return [
1032
1035
  {
@@ -1053,8 +1056,8 @@ const step = (state, event) => Effect.gen(function* () {
1053
1056
  ];
1054
1057
  });
1055
1058
  // Custom calls close their JSON fragment before every pending call finishes.
1056
- const finishTools = Effect.fnUntraced(function* (tools, customCalls) {
1057
- const closed = OpenAIFreeform.close(tools, customCalls);
1059
+ const finishTools = Effect.fnUntraced(function* (state, tools, customCalls) {
1060
+ const closed = OpenAIFreeform.close(tools, customCalls, state.custom, state.providerMetadataKey);
1058
1061
  const finished = yield* ToolStream.finishAll(ADAPTER, closed.tools);
1059
1062
  return { tools: finished.tools, events: [...closed.events, ...finished.events] };
1060
1063
  });
@@ -1069,7 +1072,7 @@ export const finishEvents = Effect.fnUntraced(function* (state) {
1069
1072
  });
1070
1073
  const events = [];
1071
1074
  const toolCallEvents = state.finishReason === undefined && Object.keys(state.tools).length > 0
1072
- ? (yield* finishTools(state.tools, state.customCalls)).events
1075
+ ? (yield* finishTools(state, state.tools, state.customCalls)).events
1073
1076
  : state.toolCallEvents;
1074
1077
  const hasToolCalls = toolCallEvents.length > 0;
1075
1078
  const reason = state.finishReason
@@ -1,34 +1,65 @@
1
- import { ToolDefinition, type Freeform, type LLMEvent, type LLMRequest, type ProviderMetadata } from "../schema/index.js";
1
+ import { JsonSchema, ToolDefinition, type Freeform, type LLMEvent, type LLMRequest, type ProviderMetadata } from "../schema/index.js";
2
2
  import { ToolStream } from "./utils/tool-stream.js";
3
3
  export interface Custom {
4
- /** The tool's one required string parameter, which the raw text fills. */
4
+ /** The tool's required string parameter, which the raw text fills. */
5
5
  readonly field: string;
6
6
  readonly format: Freeform;
7
+ /** The tool's other parameters, set on a first line. */
8
+ readonly options?: {
9
+ readonly fields: ReadonlyArray<OptionField>;
10
+ /** How to write the line, added to the custom tool's description. */
11
+ readonly description: string;
12
+ /** The grammar for the line and the raw text, when the model takes Lark. */
13
+ readonly grammar?: string;
14
+ };
7
15
  }
8
- /** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
9
- export declare const resolve: (tool: ToolDefinition) => Custom | undefined;
16
+ interface OptionField {
17
+ readonly name: string;
18
+ readonly schema: JsonSchema;
19
+ readonly required: boolean;
20
+ }
21
+ export declare const PREFIX = "// @options:";
22
+ /**
23
+ * How a tool goes out: a custom tool when it declares `freeform` in a format the model accepts (`formats`, every
24
+ * format when unset), with its required string parameter. Other parameters need a grammar for their values, and a raw
25
+ * text body when the model can't take Lark; otherwise the tool stays a JSON tool.
26
+ */
27
+ export declare const resolve: (tool: ToolDefinition, formats?: ReadonlyArray<Freeform["type"]>) => Custom | undefined;
10
28
  /** Custom tools in this request, including ones added mid-conversation, by flattened tool name. */
11
29
  export declare const tools: (request: LLMRequest) => ReadonlyMap<string, Custom>;
12
- /** The format's grammar, or `undefined` for unconstrained text. */
13
- export declare const grammar: (format: Freeform) => {
30
+ /** The grammar to send, or `undefined` for unconstrained text. */
31
+ export declare const grammar: (custom: Custom) => {
14
32
  syntax: "lark" | "regex";
15
33
  definition: string;
16
34
  } | undefined;
17
- /** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
18
- export declare const toRaw: (custom: Custom, input: unknown) => string;
19
- /** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
20
- export declare const fromRaw: (custom: Custom | undefined, raw: string) => string;
35
+ /** The custom tool's description, with how to write the line when the tool has other parameters. */
36
+ export declare const description: (tool: ToolDefinition, custom: Custom) => string;
37
+ /**
38
+ * Raw text replayed for a past call: its field after a line for the other parameters, or the whole input as JSON when
39
+ * the field is not a string. The line the model wrote, saved as `header`, replays as is while it still says the same,
40
+ * so the prompt cache holds; otherwise, as for a call another model made, a fresh line is written.
41
+ */
42
+ export declare const toRaw: (custom: Custom, input: unknown, header?: unknown) => string;
43
+ /**
44
+ * JSON arguments for a raw call, with its line as `header`. A call to an undeclared custom tool fills `input`. A line
45
+ * that isn't a JSON object stays raw text, which fails as malformed JSON; the tool's schema checks the rest.
46
+ */
47
+ export declare const parse: (custom: Custom | undefined, raw: string) => {
48
+ input: string;
49
+ header?: undefined;
50
+ } | {
51
+ input: string;
52
+ header: string;
53
+ };
21
54
  /** The opening fragment, `{"field":"`, followed by the escaped first text. */
22
55
  export declare const streamStart: (custom: Custom | undefined, raw?: string) => string;
23
56
  export declare const streamDelta: (raw: string) => string;
24
57
  /**
25
- * Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
26
- * decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
58
+ * Close the JSON fragment of each open custom call, and set its input from the raw text. With a `final` raw input
59
+ * that the streamed fragments don't decode to, the final one sets the input and the streamed one stays unclosed. A
60
+ * line the model wrote goes in the call's provider metadata as `header`, so it replays exactly.
27
61
  */
28
- export declare const close: <K extends string | number>(tools: ToolStream.State<K>, keys: Iterable<K>, final?: {
29
- readonly custom: Custom | undefined;
30
- readonly raw: string;
31
- }) => {
62
+ export declare const close: <K extends string | number>(tools: ToolStream.State<K>, keys: Iterable<K>, custom: ReadonlyMap<string, Custom>, metadataKey: string, final?: string) => {
32
63
  readonly tools: ToolStream.State<K>;
33
64
  readonly events: ReadonlyArray<LLMEvent>;
34
65
  };
@@ -1,34 +1,171 @@
1
1
  import { Option, Schema } from "effect";
2
- import { ToolDefinition, } from "../schema/index.js";
2
+ import { JsonSchema, ToolDefinition, } from "../schema/index.js";
3
3
  import { encodeJson, flattenTools, isRecord } from "./shared.js";
4
4
  import { ToolStream } from "./utils/tool-stream.js";
5
5
  import { toolsUpdate } from "../tool-updates.js";
6
- /** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
7
- export const resolve = (tool) => {
8
- const field = ToolDefinition.freeformField(tool.inputSchema);
6
+ // The other parameters go on a first line as a JSON object, `// @options: {"timeout": 5000}`, then the field's text.
7
+ // It is a JavaScript comment, so the line reads naturally before code.
8
+ export const PREFIX = "// @options:";
9
+ /**
10
+ * How a tool goes out: a custom tool when it declares `freeform` in a format the model accepts (`formats`, every
11
+ * format when unset), with its required string parameter. Other parameters need a grammar for their values, and a raw
12
+ * text body when the model can't take Lark; otherwise the tool stays a JSON tool.
13
+ */
14
+ export const resolve = (tool, formats) => {
15
+ const field = ToolDefinition.freeformField(tool.inputSchema, tool.freeform);
9
16
  if (tool.freeform === undefined || tool.native !== undefined || field === undefined)
10
17
  return undefined;
11
- return { field, format: tool.freeform };
18
+ if (formats !== undefined && !formats.includes(tool.freeform.type))
19
+ return undefined;
20
+ const lark = formats === undefined || formats.includes("lark");
21
+ const required = Array.isArray(tool.inputSchema.required) ? tool.inputSchema.required : [];
22
+ const fields = Object.entries(Schema.is(JsonSchema)(tool.inputSchema.properties) ? tool.inputSchema.properties : {})
23
+ .filter(([name]) => name !== field)
24
+ .map(([name, schema]) => ({
25
+ name,
26
+ schema: Schema.is(JsonSchema)(schema) ? schema : {},
27
+ required: required.includes(name),
28
+ }));
29
+ if (fields.length === 0)
30
+ return { field, format: tool.freeform };
31
+ const rules = fields.flatMap((item) => valueRule(item.schema) ?? []);
32
+ if (rules.length !== fields.length || (!lark && tool.freeform.type !== "text"))
33
+ return undefined;
34
+ return {
35
+ field,
36
+ format: tool.freeform,
37
+ options: {
38
+ fields,
39
+ description: describe(field, fields),
40
+ grammar: lark ? lineGrammar(fields, rules, tool.freeform) : undefined,
41
+ },
42
+ };
43
+ };
44
+ // Keys in any order, with spaces after `{`, `:` and `,` and before `}`. The tool's own schema checks the values it
45
+ // gets, as it does for a JSON call. Without required parameters a call may leave the line out, so plain raw text
46
+ // can't start with the prefix. A tool's own grammar becomes the body, its `start` renamed to `fb_start`.
47
+ const lineGrammar = (fields, rules, format) => {
48
+ const body = format.type === "text" ? "ff_body" : "fb_start";
49
+ const plain = format.type === "text" ? "ff_plain" : body;
50
+ return [
51
+ `start: ff_line ${body}${fields.some((item) => item.required) ? "" : ` | ${plain}`}`,
52
+ `ff_line: ${larkString(PREFIX)} " "* "{" " "* ff_pair (" "* "," " "* ff_pair)* " "* "}" "\\n"`,
53
+ `ff_pair: ${fields.map((item, index) => `${larkString(encodeJson(item.name))} " "* ":" " "* ${rules[index]}`).join(" | ")}`,
54
+ ...(format.type === "text"
55
+ ? ["ff_body: /[\\s\\S]+/", `ff_plain: /${notStartingWith(PREFIX)}/`]
56
+ : format.type === "regex"
57
+ ? [`fb_start: /${format.pattern.replace(/\\?\//g, "\\/")}/`]
58
+ : [format.grammar.replace(/^([ \t]*)start([ \t]*:)/m, "$1fb_start$2")]),
59
+ ].join("\n");
60
+ };
61
+ const valueRule = (schema) => {
62
+ if (Array.isArray(schema.enum))
63
+ return schema.enum.length === 0
64
+ ? undefined
65
+ : `(${schema.enum.map((item) => larkString(encodeJson(item))).join(" | ")})`;
66
+ if (schema.type === "boolean")
67
+ return '("true" | "false")';
68
+ if (schema.type === "number")
69
+ return "/-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/";
70
+ if (schema.type === "string")
71
+ return '/"(?:[^"\\\\\\x00-\\x1f]|\\\\["\\\\\\/bfnrt]|\\\\u[0-9a-fA-F]{4})*"/';
72
+ if (schema.type !== "integer")
73
+ return undefined;
74
+ const lowest = minimum(schema);
75
+ if (lowest >= 1)
76
+ return "/[1-9][0-9]*/";
77
+ return lowest >= 0 ? "/0|[1-9][0-9]*/" : "/-?(?:0|[1-9][0-9]*)/";
78
+ };
79
+ const minimum = (schema) => Math.max(typeof schema.minimum === "number" ? schema.minimum : -Infinity, typeof schema.exclusiveMinimum === "number" ? schema.exclusiveMinimum + 1 : -Infinity);
80
+ const describe = (field, fields) => {
81
+ const required = fields.filter((item) => item.required);
82
+ const example = required.length > 0 ? required : [fields.find((item) => item.schema.type === "boolean") ?? fields[0]];
83
+ return [
84
+ required.length === 0
85
+ ? `To set the parameters below, start with a \`${PREFIX}\` line holding a JSON object of them, then write \`${field}\` from the next line. Leave the line out to use the defaults.`
86
+ : `Start with a \`${PREFIX}\` line holding a JSON object of the parameters below, then write \`${field}\` from the next line.`,
87
+ ...fields.map((item) => `- \`${item.name}\` (${Array.isArray(item.schema.enum) ? `one of ${item.schema.enum.map((value) => encodeJson(value)).join(", ")}` : String(item.schema.type)}${item.required ? ", required" : ""})${typeof item.schema.description === "string" ? `: ${item.schema.description}` : ""}`),
88
+ "For example:",
89
+ `${PREFIX} {${example.map((item) => `${encodeJson(item.name)}: ${encodeJson(sample(item.schema))}`).join(", ")}}`,
90
+ `<${field}>`,
91
+ ].join("\n");
92
+ };
93
+ const sample = (schema) => {
94
+ if (Array.isArray(schema.enum))
95
+ return schema.enum[0];
96
+ if (schema.type === "boolean")
97
+ return true;
98
+ if (schema.type === "string")
99
+ return "...";
100
+ return Math.max(1, minimum(schema));
12
101
  };
102
+ const larkString = (text) => JSON.stringify(text);
103
+ // A regex for text that does not start with `prefix`: it differs from the prefix at some character, or is a shorter
104
+ // prefix of it.
105
+ const notStartingWith = (prefix) => {
106
+ const chars = [...prefix];
107
+ const head = (end) => chars.slice(0, end).map(escapeRegex).join("");
108
+ const differs = chars.map((char, index) => `${head(index)}[^${escapeClass(char)}]`);
109
+ const shorter = chars.slice(1).map((_, index) => head(index + 1));
110
+ return [`(?:${differs.join("|")})[\\s\\S]*`, ...shorter].join("|");
111
+ };
112
+ const escapeRegex = (char) => char.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
113
+ const escapeClass = (char) => char.replace(/[\\\]^\-/]/g, "\\$&");
13
114
  /** Custom tools in this request, including ones added mid-conversation, by flattened tool name. */
14
115
  export const tools = (request) => {
116
+ const formats = request.model.capabilities?.tools?.freeform;
15
117
  const added = request.messages.flatMap((message) => toolsUpdate(message)?.add ?? []);
16
118
  return new Map(flattenTools([...request.tools, ...added]).flatMap((tool) => {
17
- const custom = resolve(tool);
119
+ const custom = resolve(tool, formats);
18
120
  return custom ? [[tool.name, custom]] : [];
19
121
  }));
20
122
  };
21
- /** The format's grammar, or `undefined` for unconstrained text. */
22
- export const grammar = (format) => format.type === "text"
23
- ? undefined
24
- : { syntax: format.type, definition: format.type === "regex" ? format.pattern : format.grammar };
25
- /** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
26
- export const toRaw = (custom, input) => {
123
+ /** The grammar to send, or `undefined` for unconstrained text. */
124
+ export const grammar = (custom) => {
125
+ if (custom.options)
126
+ return custom.options.grammar === undefined
127
+ ? undefined
128
+ : { syntax: "lark", definition: custom.options.grammar };
129
+ const format = custom.format;
130
+ if (format.type === "text")
131
+ return undefined;
132
+ return { syntax: format.type, definition: format.type === "regex" ? format.pattern : format.grammar };
133
+ };
134
+ /** The custom tool's description, with how to write the line when the tool has other parameters. */
135
+ export const description = (tool, custom) => custom.options ? `${tool.description}\n\n${custom.options.description}` : tool.description;
136
+ /**
137
+ * Raw text replayed for a past call: its field after a line for the other parameters, or the whole input as JSON when
138
+ * the field is not a string. The line the model wrote, saved as `header`, replays as is while it still says the same,
139
+ * so the prompt cache holds; otherwise, as for a call another model made, a fresh line is written.
140
+ */
141
+ export const toRaw = (custom, input, header) => {
27
142
  const value = isRecord(input) ? input[custom.field] : undefined;
28
- return typeof value === "string" ? value : encodeJson(input ?? {});
143
+ if (typeof value !== "string" || !isRecord(input))
144
+ return encodeJson(input ?? {});
145
+ const fields = custom.options?.fields ?? [];
146
+ const options = encodeJson(pick(fields, input));
147
+ if (options === "{}")
148
+ return value;
149
+ const saved = typeof header === "string" ? Option.getOrUndefined(decodeLine(header)) : undefined;
150
+ const same = saved !== undefined && encodeJson(pick(fields, saved)) === options;
151
+ return `${same ? header : `${PREFIX} ${options}`}\n${value}`;
29
152
  };
30
- /** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
31
- export const fromRaw = (custom, raw) => encodeJson({ [field(custom)]: raw });
153
+ const pick = (fields, input) => Object.fromEntries(fields.flatMap((item) => (input[item.name] === undefined ? [] : [[item.name, input[item.name]]])));
154
+ /**
155
+ * JSON arguments for a raw call, with its line as `header`. A call to an undeclared custom tool fills `input`. A line
156
+ * that isn't a JSON object stays raw text, which fails as malformed JSON; the tool's schema checks the rest.
157
+ */
158
+ export const parse = (custom, raw) => {
159
+ const end = raw.indexOf("\n");
160
+ if (!custom?.options || !raw.startsWith(PREFIX) || end === -1)
161
+ return { input: encodeJson({ [field(custom)]: raw }) };
162
+ const header = raw.slice(0, end);
163
+ const options = Option.getOrUndefined(decodeLine(header));
164
+ if (options === undefined)
165
+ return { input: raw };
166
+ return { input: encodeJson({ ...options, [custom.field]: raw.slice(end + 1) }), header };
167
+ };
168
+ const decodeLine = (header) => decodeArguments(header.slice(PREFIX.length));
32
169
  const field = (custom) => custom?.field ?? "input";
33
170
  // Streamed raw text is re-encoded as JSON-argument fragments, so the tool-input events match a JSON tool's.
34
171
  /** The opening fragment, `{"field":"`, followed by the escaped first text. */
@@ -37,17 +174,44 @@ export const streamDelta = (raw) => encodeJson(raw).slice(1, -1);
37
174
  const STREAM_END = '"}';
38
175
  const decodeArguments = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)));
39
176
  /**
40
- * Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
41
- * decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
177
+ * Close the JSON fragment of each open custom call, and set its input from the raw text. With a `final` raw input
178
+ * that the streamed fragments don't decode to, the final one sets the input and the streamed one stays unclosed. A
179
+ * line the model wrote goes in the call's provider metadata as `header`, so it replays exactly.
42
180
  */
43
- export const close = (tools, keys, final) => [...keys].reduce((result, key) => {
181
+ export const close = (tools, keys, custom, metadataKey, final) => [...keys].reduce((result, key) => {
44
182
  const pending = result.tools[key];
45
- const streamed = pending && Option.getOrUndefined(decodeArguments(`${pending.input}${STREAM_END}`));
46
- if (!pending || (final !== undefined && streamed?.[field(final.custom)] !== final.raw))
183
+ if (!pending)
47
184
  return result;
185
+ const definition = custom.get(pending.name);
186
+ const streamed = Option.getOrUndefined(decodeArguments(`${pending.input}${STREAM_END}`))?.[field(definition)];
187
+ if (final !== undefined && streamed !== final)
188
+ return {
189
+ tools: { ...result.tools, [key]: settle(pending, definition, metadataKey, final) },
190
+ events: result.events,
191
+ };
48
192
  const appended = ToolStream.append(result.tools, key, STREAM_END);
49
- return appended ? { tools: appended.tools, events: [...result.events, ...appended.events] } : result;
193
+ if (!appended)
194
+ return result;
195
+ return {
196
+ tools: typeof streamed === "string"
197
+ ? { ...appended.tools, [key]: settle(appended.tool, definition, metadataKey, streamed) }
198
+ : appended.tools,
199
+ events: [...result.events, ...appended.events],
200
+ };
50
201
  }, { tools, events: [] });
202
+ const settle = (tool, custom, metadataKey, raw) => {
203
+ const parsed = parse(custom, raw);
204
+ if (parsed.header === undefined)
205
+ return { ...tool, input: parsed.input };
206
+ return {
207
+ ...tool,
208
+ input: parsed.input,
209
+ providerMetadata: {
210
+ ...tool.providerMetadata,
211
+ [metadataKey]: { ...tool.providerMetadata?.[metadataKey], header: parsed.header },
212
+ },
213
+ };
214
+ };
51
215
  /** Provider metadata marking a call that arrived as a custom tool call. */
52
216
  export const metadata = (itemId, custom) => (custom ? { itemId, custom: true } : { itemId });
53
217
  /**
@@ -758,17 +758,21 @@ export declare const Message: Schema.Union<readonly [typeof SystemMessage, typeo
758
758
  tool: (result: ToolResultPart | Parameters<typeof ToolResultPart.make>[0]) => ToolMessage;
759
759
  };
760
760
  /**
761
- * Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format
762
- * write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input.
761
+ * Raw-text wire encoding for a tool with exactly one required string parameter, or the one its `field` names among
762
+ * others. Models that accept the format write that parameter's value directly instead of JSON arguments, after a
763
+ * first line holding the others; calls still decode to the normal object input.
763
764
  */
764
765
  export declare const Freeform: Schema.Union<readonly [Schema.Struct<{
765
766
  readonly type: Schema.Literal<"text">;
767
+ readonly field: Schema.optionalKey<Schema.String>;
766
768
  }>, Schema.Struct<{
767
769
  readonly type: Schema.Literal<"regex">;
768
770
  readonly pattern: Schema.String;
771
+ readonly field: Schema.optionalKey<Schema.String>;
769
772
  }>, Schema.Struct<{
770
773
  readonly type: Schema.Literal<"lark">;
771
774
  readonly grammar: Schema.String;
775
+ readonly field: Schema.optionalKey<Schema.String>;
772
776
  }>]>;
773
777
  export type Freeform = Tool.Freeform;
774
778
  declare const toolDefinitionFields: {
@@ -778,12 +782,15 @@ declare const toolDefinitionFields: {
778
782
  outputSchema: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
779
783
  freeform: Schema.optional<Schema.Union<readonly [Schema.Struct<{
780
784
  readonly type: Schema.Literal<"text">;
785
+ readonly field: Schema.optionalKey<Schema.String>;
781
786
  }>, Schema.Struct<{
782
787
  readonly type: Schema.Literal<"regex">;
783
788
  readonly pattern: Schema.String;
789
+ readonly field: Schema.optionalKey<Schema.String>;
784
790
  }>, Schema.Struct<{
785
791
  readonly type: Schema.Literal<"lark">;
786
792
  readonly grammar: Schema.String;
793
+ readonly field: Schema.optionalKey<Schema.String>;
787
794
  }>]>>;
788
795
  cache: Schema.optional<typeof CacheHint>;
789
796
  native: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
@@ -796,12 +803,15 @@ declare const ToolDefinition_base: Schema.Class<ToolDefinition, Schema.Struct<{
796
803
  readonly outputSchema: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
797
804
  readonly freeform: Schema.optional<Schema.Union<readonly [Schema.Struct<{
798
805
  readonly type: Schema.Literal<"text">;
806
+ readonly field: Schema.optionalKey<Schema.String>;
799
807
  }>, Schema.Struct<{
800
808
  readonly type: Schema.Literal<"regex">;
801
809
  readonly pattern: Schema.String;
810
+ readonly field: Schema.optionalKey<Schema.String>;
802
811
  }>, Schema.Struct<{
803
812
  readonly type: Schema.Literal<"lark">;
804
813
  readonly grammar: Schema.String;
814
+ readonly field: Schema.optionalKey<Schema.String>;
805
815
  }>]>>;
806
816
  readonly cache: Schema.optional<typeof CacheHint>;
807
817
  readonly native: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
@@ -814,8 +824,11 @@ export declare namespace ToolDefinition {
814
824
  type Input = ToolDefinition | ToolDefinitionInput;
815
825
  /** Normalize tool definition input into the canonical `ToolDefinition` class. */
816
826
  const make: (input: Input) => ToolDefinition;
817
- /** The parameter a freeform call fills: the input schema's only property, when it is a required string. */
818
- const freeformField: (schema: JsonSchema) => string | undefined;
827
+ /**
828
+ * The parameter a freeform call fills, when it is a required string: the one the format's `field` names, otherwise
829
+ * the input schema's only property.
830
+ */
831
+ const freeformField: (schema: JsonSchema, freeform?: Freeform) => string | undefined;
819
832
  }
820
833
  export type ToolNamespace = {
821
834
  readonly type: "namespace";
@@ -262,8 +262,9 @@ const toolChanges = (input) => ({
262
262
  remove: (input.remove ?? []).map((item) => (typeof item === "string" ? item : item.name)),
263
263
  });
264
264
  /**
265
- * Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format
266
- * write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input.
265
+ * Raw-text wire encoding for a tool with exactly one required string parameter, or the one its `field` names among
266
+ * others. Models that accept the format write that parameter's value directly instead of JSON arguments, after a
267
+ * first line holding the others; calls still decode to the normal object input.
267
268
  */
268
269
  export const Freeform = Tool.Freeform;
269
270
  const toolDefinitionFields = {
@@ -286,13 +287,16 @@ export class ToolDefinition extends Schema.Class("LLM.ToolDefinition")({
286
287
  (function (ToolDefinition) {
287
288
  /** Normalize tool definition input into the canonical `ToolDefinition` class. */
288
289
  ToolDefinition.make = (input) => (input instanceof ToolDefinition ? input : new ToolDefinition(input));
289
- /** The parameter a freeform call fills: the input schema's only property, when it is a required string. */
290
- ToolDefinition.freeformField = (schema) => {
290
+ /**
291
+ * The parameter a freeform call fills, when it is a required string: the one the format's `field` names, otherwise
292
+ * the input schema's only property.
293
+ */
294
+ ToolDefinition.freeformField = (schema, freeform) => {
291
295
  const properties = Object.entries(Schema.is(JsonSchema)(schema.properties) ? schema.properties : {});
292
- if (properties.length !== 1)
296
+ if (freeform?.field === undefined && properties.length !== 1)
293
297
  return undefined;
294
- const [name, property] = properties[0];
295
- if (!Schema.is(JsonSchema)(property) || property.type !== "string")
298
+ const [name, property] = properties.find(([name]) => (freeform?.field ?? name) === name) ?? [];
299
+ if (name === undefined || !Schema.is(JsonSchema)(property) || property.type !== "string")
296
300
  return undefined;
297
301
  return Array.isArray(schema.required) && schema.required.includes(name) ? name : undefined;
298
302
  };
package/dist/tool.d.ts CHANGED
@@ -27,8 +27,18 @@ export type ToolToModelOutput<Input extends ToolInput, Success extends ToolSchem
27
27
  type FreeformField<T> = {
28
28
  [K in keyof T]-?: [Exclude<keyof T, K>] extends [never] ? {} extends Pick<T, K> ? never : T[K] extends string ? K : never : never;
29
29
  }[keyof T];
30
- /** `Freeform` for exactly one required string field or unknown ones (a JSON Schema `input`), otherwise `undefined`. */
31
- export type FreeformOption<Input extends ToolInput> = unknown extends ToolInputType<Input> ? Freeform : [FreeformField<ToolInputType<Input>>] extends [never] ? undefined : Freeform;
30
+ type RequiredStringField<T> = {
31
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : T[K] extends string ? K : never;
32
+ }[keyof T];
33
+ /**
34
+ * `Freeform` for exactly one required string field or unknown ones (a JSON Schema `input`), `Freeform` naming its
35
+ * `field` for a required string field among others, otherwise `undefined`.
36
+ */
37
+ export type FreeformOption<Input extends ToolInput> = unknown extends ToolInputType<Input> ? Freeform : [FreeformField<ToolInputType<Input>>] extends [never] ? [RequiredStringField<ToolInputType<Input>>] extends [never] ? undefined : Freeform & {
38
+ readonly field: RequiredStringField<ToolInputType<Input>>;
39
+ } : Freeform & {
40
+ readonly field?: FreeformField<ToolInputType<Input>>;
41
+ };
32
42
  /**
33
43
  * A type-safe LLM tool. Each tool bundles its own description, input
34
44
  * Schema and success Schema. The execute handler is optional: omit it when you
package/dist/tool.js CHANGED
@@ -77,8 +77,10 @@ export const emptyInputJsonSchema = (schema) => {
77
77
  return { ...rest, type: "object", properties: {}, additionalProperties: false };
78
78
  };
79
79
  const definition = (input) => {
80
- if (input.freeform !== undefined && ToolDefinition.freeformField(input.inputSchema) === undefined)
81
- throw new Error("A freeform tool needs exactly one parameter, a required string");
80
+ if (input.freeform !== undefined && ToolDefinition.freeformField(input.inputSchema, input.freeform) === undefined)
81
+ throw new Error(input.freeform.field === undefined
82
+ ? "A freeform tool needs exactly one parameter, a required string"
83
+ : `A freeform tool's \`${input.freeform.field}\` parameter must be a required string`);
82
84
  return new ToolDefinition(input);
83
85
  };
84
86
  const annotationKeywords = new Set(["title", "description", "default", "examples", "readOnly", "writeOnly"]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "0.0.0-dev-1343",
3
+ "version": "0.0.0-dev-1345",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -624,7 +624,7 @@
624
624
  "devDependencies": {
625
625
  "@clack/prompts": "1.0.0-alpha.1",
626
626
  "@effect/platform-node": "4.1.0",
627
- "@opencode/http-recorder": "0.0.0-dev-1343",
627
+ "@opencode/http-recorder": "0.0.0-dev-1345",
628
628
  "@tsconfig/bun": "1.0.9",
629
629
  "@types/bun": "1.4.3",
630
630
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -634,7 +634,7 @@
634
634
  "@aws-sdk/credential-providers": "3.1057.0",
635
635
  "@smithy/eventstream-codec": "4.2.14",
636
636
  "@smithy/util-utf8": "4.2.2",
637
- "@opencode/schema": "0.0.0-dev-1343",
637
+ "@opencode/schema": "0.0.0-dev-1345",
638
638
  "aws4fetch": "1.0.20",
639
639
  "effect": "4.1.0",
640
640
  "google-auth-library": "10.5.0"