@kubohiroya/turbowarp-named-functions 0.1.0 → 0.1.1

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.
package/README.ja.md CHANGED
@@ -35,7 +35,7 @@ JSONの引数を受け取りJSONの結果を返す「名前を持つ関数」を
35
35
  npm packageとして使う場合は、検証済みのversionをexact pinします。
36
36
 
37
37
  ```bash
38
- pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.1.0
38
+ pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.1.1
39
39
  ```
40
40
 
41
41
  ## クイックスタート
@@ -54,9 +54,9 @@ say (call function [add] with [{"a":1,"b":2}])
54
54
 
55
55
  <!-- BEGIN GENERATED BLOCKS -->
56
56
 
57
- ### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] export as [EXPORT]`
57
+ ### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]`
58
58
 
59
- 名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。export asをtoolにすると、AIのツール呼び出しなどの利用側に公開する印になります。
59
+ 名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。RETURNSには任意の戻り値JSON Schemaを指定でき、空欄なら戻り値を検証しません。
60
60
 
61
61
  | 項目 | 値 |
62
62
  |---|---|
@@ -65,6 +65,7 @@ say (call function [add] with [{"a":1,"b":2}])
65
65
  | `NAME` | 文字列, 既定値: `add` |
66
66
  | `DESCRIPTION` | 文字列, 既定値: `Adds two numbers.` |
67
67
  | `SCHEMA` | 文字列, 既定値: `{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}` |
68
+ | `RETURNS` | 文字列, 既定値: `` |
68
69
  | `EXPORT` | 文字列, 既定値: `none`, 選択肢: `none`, `tool` |
69
70
 
70
71
  ### `function argument [PATH]`
@@ -179,11 +180,23 @@ Promiseへの参照のJSON配列をすべて待ち、結果のJSON配列を返
179
180
  | 関数が直接または別の関数を経由して自分自身を呼んだ | `Reentrant call: a -> b -> a`というエラーで失敗する。再帰には独自ブロックを使う |
180
181
  | 引数がスキーマに合わない | スクリプトを起動する前に失敗する。どの項目が合わないかは`last function error`でわかる |
181
182
  | スクリプトが`return`なしで終わった | 結果は空(`null`)になる |
183
+ | 戻り値がreturns schemaに合わない | 呼び出しが失敗し、`last function error`に期待型とJSON pathが表示される。`return`なしの終了も`null`として検証される |
182
184
  | 関数が30秒以内に終わらない | タイムアウトで失敗する |
183
185
  | `start function`で同時に9個以上開始した | 空きが出るまで待つ(同時に実行するのは8個まで) |
184
186
  | プロジェクトの停止 | 実行中の呼び出しは失敗し、Promiseへの参照は消去される |
185
187
  | `define function`ハットが不正(文字列の直書きでない、スキーマが不正、名前の重複) | 関数は定義されない。`function [NAME] defined?`はfalseを返す |
186
188
 
189
+ 初回は既存のJSON文字列入力を維持します。視覚Schemaビルダーは、`define schema`ハットの下に宣言的なpropertyブロックを並べる形を提案します。
190
+
191
+ ```text
192
+ define schema [Player] version [1.0.0]
193
+ property [name] type [string] required
194
+ property [score] type [number] required minimum (0)
195
+ property [tags] type [array of string] optional
196
+ ```
197
+
198
+ ネストしたobjectやarrayのpropertyは別の名前付きSchemaを参照できるようにし、同じSchemaを関数の引数・戻り値・名前付きデータに選べるようにします。ブロック列は`validateAgainstSchema`が扱うcanonical JSON Schemaへ変換し、別の検証形式を作らず、既存のJSON文字列プロジェクトもそのまま使います。これはブロック仕様案であり、まだ実装されていません。実装境界はSchema定義と変換層です。リテラルのブロック項目を読み、重複・不正な定義を報告してcanonical schemaを生成します。Schema読み込み時に任意のブロックを実行しません。ブロックのmutation UIやネストSchemaの編集体験は別の実装作業です。
199
+
187
200
  ## Composition API
188
201
 
189
202
  Composition APIをimportしても、単独のTurboWarp機能拡張は登録されません。利用する側の拡張が自分のブロックと`define function`ハットのopcodeを持ち、ハットの条件判定と、引数・戻り値のブロックの処理をこのAPIに渡します。使い方は[英語版README](README.md#composition-api)を参照してください。
@@ -207,3 +220,15 @@ SCRATCH_VM_PATH=/path/to/TurboWarp/scratch-vm pnpm test
207
220
  ## ライセンス
208
221
 
209
222
  [Mozilla Public License 2.0](LICENSE) (SPDX: `MPL-2.0`).
223
+
224
+ ## 固定引数の編集フォーム(S3-4)
225
+
226
+ 共通エディターの起動時フラグ `blockEditorFixedInputs` とDialogsがONのGUIでは、`defineFunction` の `EXPORT` だけを固定フォームとして登録します。旧GUI・フラグOFFでは追加登録を行いません。Schemaの正本は `schemas/block-editor-fixed-inputs.schema.json#/$defs/defineFunction/properties/EXPORT`、codecと登録は `src/fixed-input-editors.ts` です。既存raw値・未変更alias・未知enumは無操作保存で書き換えず、reporterを評価しません。明示変更だけを検査し、他の引数やブロック宣言、保存形式を変更しません。
227
+
228
+ HATの直付けEXPORT dropdownはnone/toolを保存値として使用します。NAME/DESCRIPTION/SCHEMA/RETURNSを編集・実行せず、関数探索・HAT開始・tool公開はフォームの検査から呼びません。
229
+
230
+ 登録はoptional API(apiVersion:1)に限定し、RUNTIME_DISPOSED/明示disposeで解除します。起動フラグOFF+再読込で従来経路へ切り戻せます。依存を戻す場合はmanifest/lock/実解決を一組で復旧します。npm公開や後続段階の動的候補は含みません。
231
+
232
+ Schemaが記述する契約の根拠は実getInfoの宣言と既存の純粋なruntime変換です。SchemaBundleのretrievalUriはこのローカル文書の識別子であり、URL配信済み・HTTP取得によるref解決を意味しません。Schemaは同梱文書だけでcompileします。
233
+
234
+ 登録は拡張インスタンスの構築時に存在する任意の editor API を使用します。後からの API 追加や差し替えには自動追従しません。起動設定を変更した場合は GUI を再読み込みし、拡張インスタンスを再構築してください。
package/README.md CHANGED
@@ -11,6 +11,7 @@ A TurboWarp extension for defining named functions that take JSON arguments and
11
11
  - Defines functions with a `define function` hat: a name, a description, and a JSON Schema for the arguments.
12
12
  - Calls a function by name and waits for its result (`call function`), or starts it and awaits it later (`start function`, `await`, `await all`).
13
13
  - Checks arguments against the schema before the function runs, without generating code.
14
+ - Optionally checks returned values against the same JSON Schema subset.
14
15
  - Detects reentrant calls (a function that calls itself directly or indirectly) and reports an error instead of waiting forever.
15
16
  - Provides a Composition API so other extensions can bundle the same capability with their own blocks.
16
17
 
@@ -22,7 +23,7 @@ A TurboWarp extension for defining named functions that take JSON arguments and
22
23
  > This extension must run unsandboxed because it starts `define function` scripts through the VM runtime.
23
24
  > Load extensions only from sources you trust.
24
25
 
25
- - NAME, DESCRIPTION, and SCHEMA in `define function` must be literal text. The hat is read before any script runs.
26
+ - NAME, DESCRIPTION, SCHEMA, and a non-empty RETURNS value in `define function` must be literal text. The hat is read before any script runs.
26
27
  - A function exported as a tool may be called with arguments chosen by another program, such as an AI model. Treat arguments as untrusted input even though they match the schema.
27
28
 
28
29
  ## Installation
@@ -37,7 +38,7 @@ A TurboWarp extension for defining named functions that take JSON arguments and
37
38
  ### npm package
38
39
 
39
40
  ```bash
40
- pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.1.0
41
+ pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.1.1
41
42
  ```
42
43
 
43
44
  Standalone bundle:
@@ -64,9 +65,9 @@ generated section manually.
64
65
 
65
66
  <!-- BEGIN GENERATED BLOCKS -->
66
67
 
67
- ### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] export as [EXPORT]`
68
+ ### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]`
68
69
 
69
- Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. export as tool marks it for consumers such as AI tool calling.
70
+ Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. RETURNS is an optional JSON Schema for the return value; leave it blank to disable return validation.
70
71
 
71
72
  | Property | Value |
72
73
  |---|---|
@@ -75,6 +76,7 @@ Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. ex
75
76
  | `NAME` | String, default: `add` |
76
77
  | `DESCRIPTION` | String, default: `Adds two numbers.` |
77
78
  | `SCHEMA` | String, default: `{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}` |
79
+ | `RETURNS` | String, default: `` |
78
80
  | `EXPORT` | String, default: `none`, choices: `none`, `tool` |
79
81
 
80
82
  ### `function argument [PATH]`
@@ -188,12 +190,32 @@ Reports the most recent function error, or an empty string.
188
190
  | Several calls to the same function | They run one at a time in order. Different functions run concurrently. |
189
191
  | A function calls itself, directly or through other functions | The call fails with `Reentrant call: a -> b -> a`. Use a custom block for recursion. |
190
192
  | Arguments do not match the schema | The call fails before the script starts; `last function error` explains which field. |
193
+ | A return value does not match RETURNS | The call fails; `last function error` reports the expected type and JSON path. Ending without `return` is checked as `null`. |
191
194
  | The script ends without `return` | The result is empty (`null`). |
192
195
  | A function takes longer than 30 seconds | The call fails with a timeout. |
193
196
  | More than 8 started calls at once | Further `start function` calls wait for a free slot. |
194
197
  | Project stop | Running calls fail and promise references are cleared. |
195
198
  | Invalid `define function` hats (non-literal inputs, invalid schema, duplicate names) | The function is not defined; `function [NAME] defined?` reports false. |
196
199
 
200
+ The first version keeps schema authoring as literal JSON text. The visual builder should use a
201
+ `define schema` hat followed by declarative property blocks. For example:
202
+
203
+ ```text
204
+ define schema [Player] version [1.0.0]
205
+ property [name] type [string] required
206
+ property [score] type [number] required minimum (0)
207
+ property [tags] type [array of string] optional
208
+ ```
209
+
210
+ Nested object and array properties should reference another named schema, so the same schema can
211
+ be selected for function arguments, return values, and named data. The block sequence must lower
212
+ to the canonical JSON Schema object consumed by `validateAgainstSchema`; it must not create a
213
+ second validation format or change existing JSON-text projects. This is a proposed block contract,
214
+ not an implemented feature. The implementation boundary is the schema definition and conversion
215
+ layer: it reads literal block fields, reports duplicate/invalid definitions, and produces the
216
+ canonical schema. It does not execute arbitrary blocks while loading a schema. Editor block
217
+ mutation and nested-schema UX remain separate implementation work.
218
+
197
219
  ## Composition API
198
220
 
199
221
  Importing the Composition API does not register the standalone TurboWarp extension. The consumer
@@ -256,3 +278,15 @@ SCRATCH_VM_PATH=/path/to/TurboWarp/scratch-vm pnpm test
256
278
  ## License
257
279
 
258
280
  [Mozilla Public License 2.0](LICENSE) (SPDX: `MPL-2.0`).
281
+
282
+ ## 固定引数の編集フォーム(S3-4)
283
+
284
+ 共通エディターの起動時フラグ `blockEditorFixedInputs` とDialogsがONのGUIでは、`defineFunction` の `EXPORT` だけを固定フォームとして登録します。旧GUI・フラグOFFでは追加登録を行いません。Schemaの正本は `schemas/block-editor-fixed-inputs.schema.json#/$defs/defineFunction/properties/EXPORT`、codecと登録は `src/fixed-input-editors.ts` です。既存raw値・未変更alias・未知enumは無操作保存で書き換えず、reporterを評価しません。明示変更だけを検査し、他の引数やブロック宣言、保存形式を変更しません。
285
+
286
+ HATの直付けEXPORT dropdownはnone/toolを保存値として使用します。NAME/DESCRIPTION/SCHEMA/RETURNSを編集・実行せず、関数探索・HAT開始・tool公開はフォームの検査から呼びません。
287
+
288
+ 登録はoptional API(apiVersion:1)に限定し、RUNTIME_DISPOSED/明示disposeで解除します。起動フラグOFF+再読込で従来経路へ切り戻せます。依存を戻す場合はmanifest/lock/実解決を一組で復旧します。npm公開や後続段階の動的候補は含みません。
289
+
290
+ Schemaが記述する契約の根拠は実getInfoの宣言と既存の純粋なruntime変換です。SchemaBundleのretrievalUriはこのローカル文書の識別子であり、URL配信済み・HTTP取得によるref解決を意味しません。Schemaは同梱文書だけでcompileします。
291
+
292
+ Registration uses the optional editor API available when the extension instance is constructed. Adding or replacing that API later is not followed automatically; reload the GUI and reconstruct the extension instance after changing the startup configuration.
@@ -1,3 +1,120 @@
1
+ //#region src/schema-validator.ts
2
+ /**
3
+ * A small JSON Schema validator for function arguments and returns. It interprets the schema at run time and
4
+ * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
5
+ *
6
+ * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
7
+ * const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
8
+ * description and title, are ignored.
9
+ */
10
+ function validateAgainstSchema(value, schema, path = "$") {
11
+ const rule = asRecord(schema);
12
+ if (!rule) throw new Error(`${path} must be a JSON Schema object`);
13
+ assertSchemaNode(rule, path);
14
+ return validateValue(value, rule, path);
15
+ }
16
+ /** Reject malformed schemas before a function definition or call can use them. */
17
+ function validateSchemaDefinition(schema, label = "schema") {
18
+ const rule = asRecord(schema);
19
+ if (!rule) throw new Error(`${label} must be a JSON object`);
20
+ assertSchemaNode(rule, label);
21
+ }
22
+ function validateValue(value, rule, path) {
23
+ const errors = [];
24
+ if (rule.type !== void 0) {
25
+ const types = Array.isArray(rule.type) ? rule.type : [rule.type];
26
+ if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
27
+ }
28
+ if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => deepEqual(candidate, value))) errors.push(`${path} must be one of ${rule.enum.map((item) => JSON.stringify(item)).join(", ")}`);
29
+ if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
30
+ if (typeof value === "number") {
31
+ if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
32
+ if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
33
+ }
34
+ if (typeof value === "string") {
35
+ const length = [...value].length;
36
+ if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
37
+ if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
38
+ }
39
+ if (Array.isArray(value)) {
40
+ if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
41
+ if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
42
+ if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateValue(item, rule.items, `${path}[${index}]`)));
43
+ }
44
+ const object = asRecord(value);
45
+ if (object) {
46
+ const properties = asRecord(rule.properties) ?? {};
47
+ if (Array.isArray(rule.required)) {
48
+ for (const name of rule.required) if (typeof name === "string" && !Object.hasOwn(object, name)) errors.push(`${path}.${name} is required`);
49
+ }
50
+ for (const [name, child] of Object.entries(object)) if (Object.hasOwn(properties, name)) errors.push(...validateValue(child, properties[name], `${path}.${name}`));
51
+ else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
52
+ }
53
+ return errors;
54
+ }
55
+ function assertSchemaNode(rule, path) {
56
+ const validTypes = /* @__PURE__ */ new Set([
57
+ "object",
58
+ "array",
59
+ "string",
60
+ "number",
61
+ "integer",
62
+ "boolean",
63
+ "null"
64
+ ]);
65
+ if (rule.type !== void 0) {
66
+ const types = Array.isArray(rule.type) ? rule.type : [rule.type];
67
+ if (types.length === 0 || types.some((type) => typeof type !== "string" || !validTypes.has(type))) throw new Error(`${path}.type must be a supported JSON Schema type or non-empty type array`);
68
+ }
69
+ if (rule.properties !== void 0) {
70
+ const properties = asRecord(rule.properties);
71
+ if (!properties) throw new Error(`${path}.properties must be an object`);
72
+ for (const [name, child] of Object.entries(properties)) {
73
+ const childRule = asRecord(child);
74
+ if (!childRule) throw new Error(`${path}.properties.${name} must be a JSON Schema object`);
75
+ assertSchemaNode(childRule, `${path}.properties.${name}`);
76
+ }
77
+ }
78
+ if (rule.required !== void 0 && (!Array.isArray(rule.required) || rule.required.some((name) => typeof name !== "string"))) throw new Error(`${path}.required must be an array of strings`);
79
+ if (rule.additionalProperties !== void 0 && typeof rule.additionalProperties !== "boolean") throw new Error(`${path}.additionalProperties must be a boolean`);
80
+ if (rule.items !== void 0) {
81
+ const items = asRecord(rule.items);
82
+ if (!items) throw new Error(`${path}.items must be a JSON Schema object`);
83
+ assertSchemaNode(items, `${path}.items`);
84
+ }
85
+ if (rule.enum !== void 0 && (!Array.isArray(rule.enum) || rule.enum.length === 0)) throw new Error(`${path}.enum must be a non-empty array`);
86
+ for (const keyword of ["minimum", "maximum"]) if (rule[keyword] !== void 0 && (typeof rule[keyword] !== "number" || !Number.isFinite(rule[keyword]))) throw new Error(`${path}.${keyword} must be a finite number`);
87
+ for (const keyword of [
88
+ "minLength",
89
+ "maxLength",
90
+ "minItems",
91
+ "maxItems"
92
+ ]) {
93
+ const value = rule[keyword];
94
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 0)) throw new Error(`${path}.${keyword} must be a non-negative integer`);
95
+ }
96
+ if (typeof rule.minimum === "number" && typeof rule.maximum === "number" && rule.minimum > rule.maximum) throw new Error(`${path}.minimum cannot exceed maximum`);
97
+ if (typeof rule.minLength === "number" && typeof rule.maxLength === "number" && rule.minLength > rule.maxLength) throw new Error(`${path}.minLength cannot exceed maxLength`);
98
+ if (typeof rule.minItems === "number" && typeof rule.maxItems === "number" && rule.minItems > rule.maxItems) throw new Error(`${path}.minItems cannot exceed maxItems`);
99
+ }
100
+ function matchesType(value, type) {
101
+ switch (type) {
102
+ case "object": return asRecord(value) !== null;
103
+ case "array": return Array.isArray(value);
104
+ case "string": return typeof value === "string";
105
+ case "number": return typeof value === "number" && Number.isFinite(value);
106
+ case "integer": return typeof value === "number" && Number.isInteger(value);
107
+ case "boolean": return typeof value === "boolean";
108
+ case "null": return value === null;
109
+ default: return false;
110
+ }
111
+ }
112
+ function deepEqual(left, right) {
113
+ return JSON.stringify(left) === JSON.stringify(right);
114
+ }
115
+ function asRecord(value) {
116
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
117
+ }
1
118
  var FunctionDispatcher = class {
2
119
  constructor(runtime, options) {
3
120
  this.runtime = runtime;
@@ -19,7 +136,7 @@ var FunctionDispatcher = class {
19
136
  * Starts a named function. `caller` is the thread of the block making the call, if any; it is used
20
137
  * to detect reentrant calls.
21
138
  */
22
- invoke(name, args, caller) {
139
+ invoke(name, args, caller, returnSchema) {
23
140
  if (!this.options.knownNames().has(name)) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${name}`));
24
141
  const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
25
142
  if (parentChain.includes(name)) return Promise.reject(/* @__PURE__ */ new Error(`Reentrant call: ${[...parentChain, name].join(" -> ")}. Use a custom block for recursion.`));
@@ -27,6 +144,7 @@ var FunctionDispatcher = class {
27
144
  const invocation = {
28
145
  name,
29
146
  args,
147
+ ...returnSchema === void 0 ? {} : { returnSchema },
30
148
  chain: [...parentChain, name],
31
149
  resolve,
32
150
  reject,
@@ -57,7 +175,7 @@ var FunctionDispatcher = class {
57
175
  returnFrom(thread, value) {
58
176
  const invocation = thread ? this.byThread.get(thread) : void 0;
59
177
  if (!invocation) throw new Error("return can only be used inside a running function.");
60
- this.settle(invocation, null, value);
178
+ this.settleWithValue(invocation, value);
61
179
  }
62
180
  cancelAll(reason) {
63
181
  for (const invocation of [...this.queue, ...this.running.values()]) this.settle(invocation, new Error(reason));
@@ -86,7 +204,7 @@ var FunctionDispatcher = class {
86
204
  this.step += 1;
87
205
  const starting = this.starting;
88
206
  if (starting && this.step - starting.startedAtStep > 2) this.settle(starting, /* @__PURE__ */ new Error(`Function ${starting.name} did not start. Is its script already running?`));
89
- for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settle(invocation, null, null);
207
+ for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
90
208
  this.pump();
91
209
  }
92
210
  settle(invocation, error, value) {
@@ -101,6 +219,16 @@ var FunctionDispatcher = class {
101
219
  if (error) invocation.reject(error);
102
220
  else invocation.resolve(value);
103
221
  }
222
+ settleWithValue(invocation, value) {
223
+ if (invocation.returnSchema !== void 0) {
224
+ const errors = validateAgainstSchema(value, invocation.returnSchema);
225
+ if (errors.length > 0) {
226
+ this.settle(invocation, /* @__PURE__ */ new Error(`Invalid return value for ${invocation.name}: ${errors.join("; ")}`));
227
+ return;
228
+ }
229
+ }
230
+ this.settle(invocation, null, value);
231
+ }
104
232
  };
105
233
  /** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
106
234
  function readArgumentPath(args, path) {
@@ -178,18 +306,25 @@ function readDefinition(block, blocks, targetName) {
178
306
  if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
179
307
  const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
180
308
  if (description.length > 1024) throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
181
- const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"));
309
+ const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"), "args schema", true);
310
+ const returnsText = readOptionalLiteralInput(block, blocks, "RETURNS");
311
+ const returns = returnsText === void 0 || returnsText.trim() === "" ? void 0 : parseSchema(returnsText, "returns schema", false);
182
312
  const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
183
313
  if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
184
314
  return {
185
315
  name,
186
316
  description,
187
317
  parameters,
318
+ ...returns ? { returns } : {},
188
319
  exportAs,
189
320
  targetName,
190
321
  blockId: block.id
191
322
  };
192
323
  }
324
+ function readOptionalLiteralInput(block, blocks, inputName) {
325
+ if (!block.inputs?.[inputName]) return void 0;
326
+ return readLiteralInput(block, blocks, inputName);
327
+ }
193
328
  function readLiteralInput(block, blocks, inputName) {
194
329
  const input = block.inputs?.[inputName];
195
330
  if (!input) throw new Error(`${inputName} is missing`);
@@ -200,82 +335,20 @@ function readLiteralInput(block, blocks, inputName) {
200
335
  if (!field) throw new Error(`${inputName} is missing`);
201
336
  return String(field.value ?? "");
202
337
  }
203
- function parseSchema(text) {
338
+ function parseSchema(text, label, requireObjectType) {
204
339
  let value;
205
340
  try {
206
341
  value = JSON.parse(text);
207
342
  } catch {
208
- throw new Error("args schema must be valid JSON");
343
+ throw new Error(`${label} must be valid JSON`);
209
344
  }
210
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("args schema must be a JSON object");
345
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} must be a JSON object`);
211
346
  const schema = value;
212
- if (schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
347
+ if (requireObjectType && schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
348
+ validateSchemaDefinition(schema, label);
213
349
  return schema;
214
350
  }
215
351
  //#endregion
216
- //#region src/schema-validator.ts
217
- /**
218
- * A small JSON Schema validator for function arguments. It interprets the schema at run time and
219
- * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
220
- *
221
- * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
222
- * const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
223
- * description and title, are ignored.
224
- */
225
- function validateAgainstSchema(value, schema, path = "$") {
226
- const rule = asRecord(schema);
227
- if (!rule) return [];
228
- const errors = [];
229
- if (rule.type !== void 0) {
230
- const types = Array.isArray(rule.type) ? rule.type : [rule.type];
231
- if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
232
- }
233
- if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => deepEqual(candidate, value))) errors.push(`${path} must be one of ${rule.enum.map((item) => JSON.stringify(item)).join(", ")}`);
234
- if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
235
- if (typeof value === "number") {
236
- if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
237
- if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
238
- }
239
- if (typeof value === "string") {
240
- const length = [...value].length;
241
- if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
242
- if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
243
- }
244
- if (Array.isArray(value)) {
245
- if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
246
- if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
247
- if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateAgainstSchema(item, rule.items, `${path}[${index}]`)));
248
- }
249
- const object = asRecord(value);
250
- if (object) {
251
- const properties = asRecord(rule.properties) ?? {};
252
- if (Array.isArray(rule.required)) {
253
- for (const name of rule.required) if (typeof name === "string" && !(name in object)) errors.push(`${path}.${name} is required`);
254
- }
255
- for (const [name, child] of Object.entries(object)) if (name in properties) errors.push(...validateAgainstSchema(child, properties[name], `${path}.${name}`));
256
- else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
257
- }
258
- return errors;
259
- }
260
- function matchesType(value, type) {
261
- switch (type) {
262
- case "object": return asRecord(value) !== null;
263
- case "array": return Array.isArray(value);
264
- case "string": return typeof value === "string";
265
- case "number": return typeof value === "number" && Number.isFinite(value);
266
- case "integer": return typeof value === "number" && Number.isInteger(value);
267
- case "boolean": return typeof value === "boolean";
268
- case "null": return value === null;
269
- default: return false;
270
- }
271
- }
272
- function deepEqual(left, right) {
273
- return JSON.stringify(left) === JSON.stringify(right);
274
- }
275
- function asRecord(value) {
276
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
277
- }
278
- //#endregion
279
352
  //#region src/composition.ts
280
353
  /**
281
354
  * Composition API: named functions without TurboWarp block definitions.
@@ -324,7 +397,7 @@ var NamedFunctionsImpl = class {
324
397
  if (options.exportedOnly && definition.exportAs !== "tool") return Promise.reject(/* @__PURE__ */ new Error(`Function ${trimmed} is not exported as a tool.`));
325
398
  const errors = validateAgainstSchema(args, definition.parameters);
326
399
  if (errors.length > 0) return Promise.reject(/* @__PURE__ */ new Error(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`));
327
- return this.dispatcher.invoke(trimmed, args, options.caller);
400
+ return this.dispatcher.invoke(trimmed, args, options.caller, definition.returns);
328
401
  }
329
402
  start(name, args, options = {}) {
330
403
  const id = `p_${this.nextPromiseId++}`;
@@ -395,4 +468,4 @@ function messageOf(error) {
395
468
  return error instanceof Error ? error.message : String(error);
396
469
  }
397
470
  //#endregion
398
- export { FUNCTION_NAME_PATTERN, createNamedFunctions, parseJsonOrText, readArgumentPath, scanFunctionDefinitions, toFunctionTools, toScratchValue, validateAgainstSchema };
471
+ export { FUNCTION_NAME_PATTERN, createNamedFunctions, parseJsonOrText, readArgumentPath, scanFunctionDefinitions, toFunctionTools, toScratchValue, validateAgainstSchema, validateSchemaDefinition };
@@ -53,6 +53,10 @@
53
53
  "id": "NAME",
54
54
  "type": "STRING"
55
55
  },
56
+ {
57
+ "id": "RETURNS",
58
+ "type": "STRING"
59
+ },
56
60
  {
57
61
  "id": "SCHEMA",
58
62
  "type": "STRING"