@kubohiroya/turbowarp-named-functions 0.1.0
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/LICENSE +373 -0
- package/README.ja.md +209 -0
- package/README.md +258 -0
- package/dist/composition.js +398 -0
- package/dist/extension-manifest.json +133 -0
- package/dist/turbowarp-named-functions.js +701 -0
- package/dist/types/composition.d.ts +49 -0
- package/dist/types/config.d.ts +11 -0
- package/dist/types/extension-manifest.d.ts +30 -0
- package/dist/types/extension.d.ts +29 -0
- package/dist/types/function-dispatcher.d.ts +60 -0
- package/dist/types/function-registry.d.ts +28 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/runtime-types.d.ts +37 -0
- package/dist/types/schema-validator.d.ts +9 -0
- package/package.json +75 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/block-definitions.json +168 -0
- package/src/composition.ts +220 -0
- package/src/config.ts +12 -0
- package/src/extension-manifest.ts +149 -0
- package/src/extension.ts +200 -0
- package/src/function-dispatcher.ts +208 -0
- package/src/function-registry.ts +124 -0
- package/src/globals.d.ts +26 -0
- package/src/index.ts +14 -0
- package/src/runtime-types.ts +42 -0
- package/src/schema-validator.ts +101 -0
package/README.md
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
# TurboWarp-Named-Functions
|
|
2
|
+
|
|
3
|
+
[English](README.md) | [日本語](README.ja.md)
|
|
4
|
+
|
|
5
|
+
A TurboWarp extension for defining named functions that take JSON arguments and return JSON results. Scripts can call them by name, wait for the result, or start several calls and await them later. Functions can be marked for export as tools so that other extensions, such as AI tool calling, can use them.
|
|
6
|
+
|
|
7
|
+
**User guide:** [English](https://kubohiroya.github.io/turbowarp-named-functions/)
|
|
8
|
+
|
|
9
|
+
## What it does
|
|
10
|
+
|
|
11
|
+
- Defines functions with a `define function` hat: a name, a description, and a JSON Schema for the arguments.
|
|
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
|
+
- Checks arguments against the schema before the function runs, without generating code.
|
|
14
|
+
- Detects reentrant calls (a function that calls itself directly or indirectly) and reports an error instead of waiting forever.
|
|
15
|
+
- Provides a Composition API so other extensions can bundle the same capability with their own blocks.
|
|
16
|
+
|
|
17
|
+
## Requirements and safety
|
|
18
|
+
|
|
19
|
+
- TurboWarp Desktop or TurboWarp Web with custom extensions enabled.
|
|
20
|
+
|
|
21
|
+
> [!IMPORTANT]
|
|
22
|
+
> This extension must run unsandboxed because it starts `define function` scripts through the VM runtime.
|
|
23
|
+
> Load extensions only from sources you trust.
|
|
24
|
+
|
|
25
|
+
- NAME, DESCRIPTION, and SCHEMA in `define function` must be literal text. The hat is read before any script runs.
|
|
26
|
+
- 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
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
### Built JavaScript
|
|
31
|
+
|
|
32
|
+
1. Download [`dist/turbowarp-named-functions.js`](dist/turbowarp-named-functions.js?raw=1).
|
|
33
|
+
2. Open **Extensions** in TurboWarp.
|
|
34
|
+
3. Choose **Custom Extension** and load the file.
|
|
35
|
+
4. Enable **Run without sandbox**.
|
|
36
|
+
|
|
37
|
+
### npm package
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.1.0
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Standalone bundle:
|
|
44
|
+
|
|
45
|
+
```text
|
|
46
|
+
node_modules/@kubohiroya/turbowarp-named-functions/dist/turbowarp-named-functions.js
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quick start
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
define function [add] description [Adds two numbers.] args schema [{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}] export as [none]
|
|
53
|
+
return ((function argument [a]) + (function argument [b]))
|
|
54
|
+
|
|
55
|
+
when green flag clicked
|
|
56
|
+
say (call function [add] with [{"a":1,"b":2}])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Block reference
|
|
60
|
+
|
|
61
|
+
The block reference is generated from
|
|
62
|
+
[`src/block-definitions.json`](src/block-definitions.json). Do not edit the
|
|
63
|
+
generated section manually.
|
|
64
|
+
|
|
65
|
+
<!-- BEGIN GENERATED BLOCKS -->
|
|
66
|
+
|
|
67
|
+
### `define function [NAME] description [DESCRIPTION] args schema [SCHEMA] export as [EXPORT]`
|
|
68
|
+
|
|
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
|
+
|
|
71
|
+
| Property | Value |
|
|
72
|
+
|---|---|
|
|
73
|
+
| Type | Hat |
|
|
74
|
+
| Opcode | `defineFunction` |
|
|
75
|
+
| `NAME` | String, default: `add` |
|
|
76
|
+
| `DESCRIPTION` | String, default: `Adds two numbers.` |
|
|
77
|
+
| `SCHEMA` | String, default: `{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}` |
|
|
78
|
+
| `EXPORT` | String, default: `none`, choices: `none`, `tool` |
|
|
79
|
+
|
|
80
|
+
### `function argument [PATH]`
|
|
81
|
+
|
|
82
|
+
Inside a function, reports the argument at a dotted path such as a or items.0.name.
|
|
83
|
+
|
|
84
|
+
| Property | Value |
|
|
85
|
+
|---|---|
|
|
86
|
+
| Type | Reporter |
|
|
87
|
+
| Opcode | `functionArgument` |
|
|
88
|
+
| `PATH` | String, default: `a` |
|
|
89
|
+
|
|
90
|
+
### `function arguments JSON`
|
|
91
|
+
|
|
92
|
+
Inside a function, reports all arguments as JSON text.
|
|
93
|
+
|
|
94
|
+
| Property | Value |
|
|
95
|
+
|---|---|
|
|
96
|
+
| Type | Reporter |
|
|
97
|
+
| Opcode | `functionArgumentsJson` |
|
|
98
|
+
|
|
99
|
+
### `return [VALUE]`
|
|
100
|
+
|
|
101
|
+
Inside a function, returns a value and ends the script. JSON text is returned as JSON; other text is returned as a string.
|
|
102
|
+
|
|
103
|
+
| Property | Value |
|
|
104
|
+
|---|---|
|
|
105
|
+
| Type | Command |
|
|
106
|
+
| Opcode | `returnValue` |
|
|
107
|
+
| `VALUE` | String, default: `0` |
|
|
108
|
+
|
|
109
|
+
### `call function [NAME] with [ARGS]`
|
|
110
|
+
|
|
111
|
+
Calls a function and waits for its result. ARGS is JSON text and is checked against the args schema. Takes at least one frame.
|
|
112
|
+
|
|
113
|
+
| Property | Value |
|
|
114
|
+
|---|---|
|
|
115
|
+
| Type | Reporter |
|
|
116
|
+
| Opcode | `callFunction` |
|
|
117
|
+
| `NAME` | String, default: `add` |
|
|
118
|
+
| `ARGS` | String, default: `{"a":1,"b":2}` |
|
|
119
|
+
|
|
120
|
+
### `start function [NAME] with [ARGS]`
|
|
121
|
+
|
|
122
|
+
Starts a function without waiting and reports a promise reference as JSON text.
|
|
123
|
+
|
|
124
|
+
| Property | Value |
|
|
125
|
+
|---|---|
|
|
126
|
+
| Type | Reporter |
|
|
127
|
+
| Opcode | `startFunction` |
|
|
128
|
+
| `NAME` | String, default: `add` |
|
|
129
|
+
| `ARGS` | String, default: `{"a":1,"b":2}` |
|
|
130
|
+
|
|
131
|
+
### `await [PROMISE]`
|
|
132
|
+
|
|
133
|
+
Waits for a promise reference from start function and reports its result.
|
|
134
|
+
|
|
135
|
+
| Property | Value |
|
|
136
|
+
|---|---|
|
|
137
|
+
| Type | Reporter |
|
|
138
|
+
| Opcode | `awaitResult` |
|
|
139
|
+
| `PROMISE` | String, default: `{"$promise":"p_1"}` |
|
|
140
|
+
|
|
141
|
+
### `await all [PROMISES]`
|
|
142
|
+
|
|
143
|
+
Waits for a JSON array of promise references and reports a JSON array of results. Failed calls become {"$error": message}.
|
|
144
|
+
|
|
145
|
+
| Property | Value |
|
|
146
|
+
|---|---|
|
|
147
|
+
| Type | Reporter |
|
|
148
|
+
| Opcode | `awaitAll` |
|
|
149
|
+
| `PROMISES` | String, default: `[]` |
|
|
150
|
+
|
|
151
|
+
### `[PROMISE] settled?`
|
|
152
|
+
|
|
153
|
+
Reports whether a started function has finished, without waiting.
|
|
154
|
+
|
|
155
|
+
| Property | Value |
|
|
156
|
+
|---|---|
|
|
157
|
+
| Type | Boolean |
|
|
158
|
+
| Opcode | `isSettled` |
|
|
159
|
+
| `PROMISE` | String, default: `{"$promise":"p_1"}` |
|
|
160
|
+
|
|
161
|
+
### `function [NAME] defined?`
|
|
162
|
+
|
|
163
|
+
Reports whether a valid define function hat with this name exists.
|
|
164
|
+
|
|
165
|
+
| Property | Value |
|
|
166
|
+
|---|---|
|
|
167
|
+
| Type | Boolean |
|
|
168
|
+
| Opcode | `isDefined` |
|
|
169
|
+
| `NAME` | String, default: `add` |
|
|
170
|
+
|
|
171
|
+
### `last function error`
|
|
172
|
+
|
|
173
|
+
Reports the most recent function error, or an empty string.
|
|
174
|
+
|
|
175
|
+
| Property | Value |
|
|
176
|
+
|---|---|
|
|
177
|
+
| Type | Reporter |
|
|
178
|
+
| Opcode | `lastError` |
|
|
179
|
+
|
|
180
|
+
<!-- END GENERATED BLOCKS -->
|
|
181
|
+
|
|
182
|
+
## Important behavior
|
|
183
|
+
|
|
184
|
+
| Situation | Behavior |
|
|
185
|
+
|---|---|
|
|
186
|
+
| A call starts | Every `define function` hat is started; only the one whose NAME matches continues. |
|
|
187
|
+
| Timing | Each call takes at least one frame, because the function runs as its own script. Use custom blocks for tight loops and recursion. |
|
|
188
|
+
| Several calls to the same function | They run one at a time in order. Different functions run concurrently. |
|
|
189
|
+
| 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
|
+
| Arguments do not match the schema | The call fails before the script starts; `last function error` explains which field. |
|
|
191
|
+
| The script ends without `return` | The result is empty (`null`). |
|
|
192
|
+
| A function takes longer than 30 seconds | The call fails with a timeout. |
|
|
193
|
+
| More than 8 started calls at once | Further `start function` calls wait for a free slot. |
|
|
194
|
+
| Project stop | Running calls fail and promise references are cleared. |
|
|
195
|
+
| Invalid `define function` hats (non-literal inputs, invalid schema, duplicate names) | The function is not defined; `function [NAME] defined?` reports false. |
|
|
196
|
+
|
|
197
|
+
## Composition API
|
|
198
|
+
|
|
199
|
+
Importing the Composition API does not register the standalone TurboWarp extension. The consumer
|
|
200
|
+
owns its blocks and its `define function` hat opcode, and forwards the hat predicate and the
|
|
201
|
+
argument/return blocks.
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
import {createNamedFunctions} from '@kubohiroya/turbowarp-named-functions/composition';
|
|
205
|
+
|
|
206
|
+
const functions = createNamedFunctions({
|
|
207
|
+
runtime: Scratch.vm.runtime,
|
|
208
|
+
functionHatOpcode: 'myextension_defineFunction'
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// In the consumer's blocks:
|
|
212
|
+
// defineFunction(args, util) -> functions.matchHat(args.NAME, util.thread)
|
|
213
|
+
// functionArgument(args, util) -> functions.argumentsFor(util.thread)
|
|
214
|
+
// returnValue(args, util) -> functions.returnFrom(util.thread, value)
|
|
215
|
+
|
|
216
|
+
const tools = functions.tools(); // functions exported as tools, OpenAI function-calling shape
|
|
217
|
+
const result = await functions.call('get_score', {}, {exportedOnly: true});
|
|
218
|
+
|
|
219
|
+
functions.release();
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
| Member | Purpose |
|
|
223
|
+
|---|---|
|
|
224
|
+
| `scan()` / `tools()` / `isDefined(name)` | Read and validate `define function` hats |
|
|
225
|
+
| `call(name, args, {caller, exportedOnly})` | Validate arguments, run the function, and resolve with its return value |
|
|
226
|
+
| `start(...)` / `await(ref)` / `awaitAll(refs)` / `isSettled(ref)` | Asynchronous calls through `{"$promise": id}` references |
|
|
227
|
+
| `matchHat` / `argumentsFor` / `returnFrom` | Bridge from the consumer's blocks |
|
|
228
|
+
| `cancelAll(reason)` / `release()` | Fail pending calls; `release` also detaches runtime listeners |
|
|
229
|
+
|
|
230
|
+
## Compatibility
|
|
231
|
+
|
|
232
|
+
| Identifier | Value | Stability |
|
|
233
|
+
|---|---|---|
|
|
234
|
+
| Product name | `TurboWarp-Named-Functions` | Human-facing |
|
|
235
|
+
| Repository | `kubohiroya/turbowarp-named-functions` | Current source location |
|
|
236
|
+
| npm package | `@kubohiroya/turbowarp-named-functions` | Public package contract |
|
|
237
|
+
| Extension ID | `kubohiroyanamedfunctions` | Stored in SB3; migration required to change |
|
|
238
|
+
| Composition API | `@kubohiroya/turbowarp-named-functions/composition` | Public package contract |
|
|
239
|
+
|
|
240
|
+
## Development
|
|
241
|
+
|
|
242
|
+
Use Node.js 22.18.0 or newer and the pnpm version declared by `packageManager`.
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
corepack enable
|
|
246
|
+
pnpm install --frozen-lockfile
|
|
247
|
+
pnpm check
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
To also run the integration test on a real headless TurboWarp VM:
|
|
251
|
+
|
|
252
|
+
```bash
|
|
253
|
+
SCRATCH_VM_PATH=/path/to/TurboWarp/scratch-vm pnpm test
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## License
|
|
257
|
+
|
|
258
|
+
[Mozilla Public License 2.0](LICENSE) (SPDX: `MPL-2.0`).
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
var FunctionDispatcher = class {
|
|
2
|
+
constructor(runtime, options) {
|
|
3
|
+
this.runtime = runtime;
|
|
4
|
+
this.options = options;
|
|
5
|
+
this.queue = [];
|
|
6
|
+
this.running = /* @__PURE__ */ new Map();
|
|
7
|
+
this.byThread = /* @__PURE__ */ new Map();
|
|
8
|
+
this.starting = null;
|
|
9
|
+
this.step = 0;
|
|
10
|
+
this.onAfterExecute = () => this.afterStep();
|
|
11
|
+
this.onStopAll = () => this.cancelAll("The project was stopped.");
|
|
12
|
+
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
13
|
+
this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
|
|
14
|
+
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
|
|
15
|
+
runtime.on("AFTER_EXECUTE", this.onAfterExecute);
|
|
16
|
+
runtime.on("PROJECT_STOP_ALL", this.onStopAll);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Starts a named function. `caller` is the thread of the block making the call, if any; it is used
|
|
20
|
+
* to detect reentrant calls.
|
|
21
|
+
*/
|
|
22
|
+
invoke(name, args, caller) {
|
|
23
|
+
if (!this.options.knownNames().has(name)) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${name}`));
|
|
24
|
+
const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
|
|
25
|
+
if (parentChain.includes(name)) return Promise.reject(/* @__PURE__ */ new Error(`Reentrant call: ${[...parentChain, name].join(" -> ")}. Use a custom block for recursion.`));
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const invocation = {
|
|
28
|
+
name,
|
|
29
|
+
args,
|
|
30
|
+
chain: [...parentChain, name],
|
|
31
|
+
resolve,
|
|
32
|
+
reject,
|
|
33
|
+
thread: null,
|
|
34
|
+
startedAtStep: -1,
|
|
35
|
+
timer: null,
|
|
36
|
+
settled: false
|
|
37
|
+
};
|
|
38
|
+
invocation.timer = this.setTimer(() => this.settle(invocation, /* @__PURE__ */ new Error(`Function ${name} timed out.`)), this.timeoutMs);
|
|
39
|
+
this.queue.push(invocation);
|
|
40
|
+
this.pump();
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/** Hat predicate: true only for the script that should run the invocation being started. */
|
|
44
|
+
matchHat(name, thread) {
|
|
45
|
+
const invocation = this.starting;
|
|
46
|
+
if (!invocation || !thread || invocation.name !== name.trim()) return false;
|
|
47
|
+
invocation.thread = thread;
|
|
48
|
+
this.byThread.set(thread, invocation);
|
|
49
|
+
this.starting = null;
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
argumentsFor(thread) {
|
|
53
|
+
const invocation = thread ? this.byThread.get(thread) : void 0;
|
|
54
|
+
if (!invocation) throw new Error("This block can only be used inside a running function.");
|
|
55
|
+
return invocation.args;
|
|
56
|
+
}
|
|
57
|
+
returnFrom(thread, value) {
|
|
58
|
+
const invocation = thread ? this.byThread.get(thread) : void 0;
|
|
59
|
+
if (!invocation) throw new Error("return can only be used inside a running function.");
|
|
60
|
+
this.settle(invocation, null, value);
|
|
61
|
+
}
|
|
62
|
+
cancelAll(reason) {
|
|
63
|
+
for (const invocation of [...this.queue, ...this.running.values()]) this.settle(invocation, new Error(reason));
|
|
64
|
+
if (this.starting) this.settle(this.starting, new Error(reason));
|
|
65
|
+
}
|
|
66
|
+
get pendingCount() {
|
|
67
|
+
return this.queue.length + this.running.size;
|
|
68
|
+
}
|
|
69
|
+
release() {
|
|
70
|
+
this.cancelAll("Named functions were released.");
|
|
71
|
+
this.runtime.off?.("AFTER_EXECUTE", this.onAfterExecute);
|
|
72
|
+
this.runtime.off?.("PROJECT_STOP_ALL", this.onStopAll);
|
|
73
|
+
}
|
|
74
|
+
pump() {
|
|
75
|
+
if (this.starting) return;
|
|
76
|
+
const index = this.queue.findIndex((invocation) => !this.running.has(invocation.name));
|
|
77
|
+
if (index < 0) return;
|
|
78
|
+
const [invocation] = this.queue.splice(index, 1);
|
|
79
|
+
if (!invocation) return;
|
|
80
|
+
this.running.set(invocation.name, invocation);
|
|
81
|
+
this.starting = invocation;
|
|
82
|
+
invocation.startedAtStep = this.step;
|
|
83
|
+
this.runtime.startHats(this.options.hatOpcode);
|
|
84
|
+
}
|
|
85
|
+
afterStep() {
|
|
86
|
+
this.step += 1;
|
|
87
|
+
const starting = this.starting;
|
|
88
|
+
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);
|
|
90
|
+
this.pump();
|
|
91
|
+
}
|
|
92
|
+
settle(invocation, error, value) {
|
|
93
|
+
if (invocation.settled) return;
|
|
94
|
+
invocation.settled = true;
|
|
95
|
+
this.clearTimer(invocation.timer);
|
|
96
|
+
const queued = this.queue.indexOf(invocation);
|
|
97
|
+
if (queued >= 0) this.queue.splice(queued, 1);
|
|
98
|
+
if (this.running.get(invocation.name) === invocation) this.running.delete(invocation.name);
|
|
99
|
+
if (invocation.thread) this.byThread.delete(invocation.thread);
|
|
100
|
+
if (this.starting === invocation) this.starting = null;
|
|
101
|
+
if (error) invocation.reject(error);
|
|
102
|
+
else invocation.resolve(value);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
/** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
|
|
106
|
+
function readArgumentPath(args, path) {
|
|
107
|
+
const trimmed = path.trim();
|
|
108
|
+
if (trimmed.length === 0) return args;
|
|
109
|
+
let current = args;
|
|
110
|
+
for (const segment of trimmed.split(".")) {
|
|
111
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
112
|
+
current = current[segment];
|
|
113
|
+
}
|
|
114
|
+
return current;
|
|
115
|
+
}
|
|
116
|
+
/** Converts a value for a Scratch reporter: objects and arrays become JSON text. */
|
|
117
|
+
function toScratchValue(value) {
|
|
118
|
+
if (value === void 0 || value === null) return "";
|
|
119
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
120
|
+
return JSON.stringify(value);
|
|
121
|
+
}
|
|
122
|
+
/** Parses block text: JSON text becomes JSON, anything else stays a string. */
|
|
123
|
+
function parseJsonOrText(text) {
|
|
124
|
+
const trimmed = text.trim();
|
|
125
|
+
if (trimmed.length === 0) return "";
|
|
126
|
+
try {
|
|
127
|
+
return JSON.parse(trimmed);
|
|
128
|
+
} catch {
|
|
129
|
+
return text;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/function-registry.ts
|
|
134
|
+
var FUNCTION_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
135
|
+
var MAX_DESCRIPTION_LENGTH = 1024;
|
|
136
|
+
/**
|
|
137
|
+
* Reads every `define function` hat in the project. NAME, DESCRIPTION, and SCHEMA are part of the
|
|
138
|
+
* tool contract sent to the model before any script runs, so they must be literal text.
|
|
139
|
+
*/
|
|
140
|
+
function scanFunctionDefinitions(targets, hatOpcode) {
|
|
141
|
+
const functions = [];
|
|
142
|
+
const errors = [];
|
|
143
|
+
const seen = /* @__PURE__ */ new Map();
|
|
144
|
+
for (const target of targets) {
|
|
145
|
+
if (target.isOriginal === false) continue;
|
|
146
|
+
const targetName = target.getName?.() ?? (target.isStage ? "Stage" : "sprite");
|
|
147
|
+
const blocks = target.blocks._blocks;
|
|
148
|
+
for (const block of Object.values(blocks)) {
|
|
149
|
+
if (block.opcode !== hatOpcode || block.topLevel === false) continue;
|
|
150
|
+
const where = `${targetName} (block ${block.id})`;
|
|
151
|
+
try {
|
|
152
|
+
const definition = readDefinition(block, blocks, targetName);
|
|
153
|
+
const previous = seen.get(definition.name);
|
|
154
|
+
if (previous !== void 0) throw new Error(`function "${definition.name}" is already defined in ${previous}`);
|
|
155
|
+
seen.set(definition.name, where);
|
|
156
|
+
functions.push(definition);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
errors.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
functions.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
|
|
163
|
+
return {
|
|
164
|
+
functions,
|
|
165
|
+
errors
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function toFunctionTools(functions) {
|
|
169
|
+
return functions.filter((definition) => definition.exportAs === "tool").map((definition) => ({
|
|
170
|
+
type: "function",
|
|
171
|
+
name: definition.name,
|
|
172
|
+
description: definition.description,
|
|
173
|
+
parameters: definition.parameters
|
|
174
|
+
}));
|
|
175
|
+
}
|
|
176
|
+
function readDefinition(block, blocks, targetName) {
|
|
177
|
+
const name = readLiteralInput(block, blocks, "NAME").trim();
|
|
178
|
+
if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
|
|
179
|
+
const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
|
|
180
|
+
if (description.length > 1024) throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
|
|
181
|
+
const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"));
|
|
182
|
+
const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
|
|
183
|
+
if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
|
|
184
|
+
return {
|
|
185
|
+
name,
|
|
186
|
+
description,
|
|
187
|
+
parameters,
|
|
188
|
+
exportAs,
|
|
189
|
+
targetName,
|
|
190
|
+
blockId: block.id
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function readLiteralInput(block, blocks, inputName) {
|
|
194
|
+
const input = block.inputs?.[inputName];
|
|
195
|
+
if (!input) throw new Error(`${inputName} is missing`);
|
|
196
|
+
if (input.block && input.block !== input.shadow) throw new Error(`${inputName} must be literal text, not a reporter block`);
|
|
197
|
+
const shadowId = input.shadow ?? input.block;
|
|
198
|
+
const shadow = shadowId ? blocks[shadowId] : void 0;
|
|
199
|
+
const field = shadow?.fields ? Object.values(shadow.fields)[0] : void 0;
|
|
200
|
+
if (!field) throw new Error(`${inputName} is missing`);
|
|
201
|
+
return String(field.value ?? "");
|
|
202
|
+
}
|
|
203
|
+
function parseSchema(text) {
|
|
204
|
+
let value;
|
|
205
|
+
try {
|
|
206
|
+
value = JSON.parse(text);
|
|
207
|
+
} catch {
|
|
208
|
+
throw new Error("args schema must be valid JSON");
|
|
209
|
+
}
|
|
210
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("args schema must be a JSON object");
|
|
211
|
+
const schema = value;
|
|
212
|
+
if (schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
|
|
213
|
+
return schema;
|
|
214
|
+
}
|
|
215
|
+
//#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
|
+
//#region src/composition.ts
|
|
280
|
+
/**
|
|
281
|
+
* Composition API: named functions without TurboWarp block definitions.
|
|
282
|
+
*
|
|
283
|
+
* A consumer extension owns its `define function` hat (and its opcode) and forwards the hat
|
|
284
|
+
* predicate and the argument/return blocks here. Importing this module does not register a
|
|
285
|
+
* TurboWarp extension and does not touch the `Scratch` global.
|
|
286
|
+
*/
|
|
287
|
+
function createNamedFunctions(options) {
|
|
288
|
+
return new NamedFunctionsImpl(options);
|
|
289
|
+
}
|
|
290
|
+
var NamedFunctionsImpl = class {
|
|
291
|
+
constructor(options) {
|
|
292
|
+
this.options = options;
|
|
293
|
+
this.promises = /* @__PURE__ */ new Map();
|
|
294
|
+
this.waiting = [];
|
|
295
|
+
this.inFlight = 0;
|
|
296
|
+
this.nextPromiseId = 1;
|
|
297
|
+
this.maxInFlight = Math.max(1, options.maxInFlight ?? 8);
|
|
298
|
+
this.maxRetained = Math.max(1, options.maxRetainedPromises ?? 256);
|
|
299
|
+
const dispatcherOptions = {
|
|
300
|
+
hatOpcode: options.functionHatOpcode,
|
|
301
|
+
knownNames: () => new Set(this.scan().functions.map((definition) => definition.name)),
|
|
302
|
+
...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
|
|
303
|
+
...options.setTimer ? { setTimer: options.setTimer } : {},
|
|
304
|
+
...options.clearTimer ? { clearTimer: options.clearTimer } : {}
|
|
305
|
+
};
|
|
306
|
+
this.dispatcher = new FunctionDispatcher(options.runtime, dispatcherOptions);
|
|
307
|
+
options.runtime.on("PROJECT_STOP_ALL", () => this.promises.clear());
|
|
308
|
+
}
|
|
309
|
+
scan() {
|
|
310
|
+
return scanFunctionDefinitions(this.options.runtime.targets, this.options.functionHatOpcode);
|
|
311
|
+
}
|
|
312
|
+
tools() {
|
|
313
|
+
const scan = this.scan();
|
|
314
|
+
if (scan.errors.length > 0) throw new Error(`Invalid function definitions: ${scan.errors.join("; ")}`);
|
|
315
|
+
return toFunctionTools(scan.functions);
|
|
316
|
+
}
|
|
317
|
+
isDefined(name) {
|
|
318
|
+
return this.scan().functions.some((definition) => definition.name === name.trim());
|
|
319
|
+
}
|
|
320
|
+
call(name, args, options = {}) {
|
|
321
|
+
const trimmed = name.trim();
|
|
322
|
+
const definition = this.scan().functions.find((candidate) => candidate.name === trimmed);
|
|
323
|
+
if (!definition) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${trimmed}`));
|
|
324
|
+
if (options.exportedOnly && definition.exportAs !== "tool") return Promise.reject(/* @__PURE__ */ new Error(`Function ${trimmed} is not exported as a tool.`));
|
|
325
|
+
const errors = validateAgainstSchema(args, definition.parameters);
|
|
326
|
+
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);
|
|
328
|
+
}
|
|
329
|
+
start(name, args, options = {}) {
|
|
330
|
+
const id = `p_${this.nextPromiseId++}`;
|
|
331
|
+
const promise = this.acquireSlot().then(() => this.call(name, args, options).finally(() => this.releaseSlot()));
|
|
332
|
+
const entry = {
|
|
333
|
+
promise,
|
|
334
|
+
settled: false
|
|
335
|
+
};
|
|
336
|
+
promise.then(() => entry.settled = true, () => entry.settled = true);
|
|
337
|
+
this.promises.set(id, entry);
|
|
338
|
+
this.evictSettled();
|
|
339
|
+
return { $promise: id };
|
|
340
|
+
}
|
|
341
|
+
await(ref) {
|
|
342
|
+
const entry = this.lookup(ref);
|
|
343
|
+
return entry ? entry.promise : Promise.reject(/* @__PURE__ */ new Error("Unknown or expired promise reference."));
|
|
344
|
+
}
|
|
345
|
+
async awaitAll(refs) {
|
|
346
|
+
if (!Array.isArray(refs)) throw new Error("await all needs a JSON array of promise references.");
|
|
347
|
+
return (await Promise.allSettled(refs.map((ref) => this.await(ref)))).map((result) => result.status === "fulfilled" ? result.value : { $error: messageOf(result.reason) });
|
|
348
|
+
}
|
|
349
|
+
isSettled(ref) {
|
|
350
|
+
return this.lookup(ref)?.settled ?? false;
|
|
351
|
+
}
|
|
352
|
+
matchHat(name, thread) {
|
|
353
|
+
return this.dispatcher.matchHat(name, thread);
|
|
354
|
+
}
|
|
355
|
+
argumentsFor(thread) {
|
|
356
|
+
return this.dispatcher.argumentsFor(thread);
|
|
357
|
+
}
|
|
358
|
+
returnFrom(thread, value) {
|
|
359
|
+
this.dispatcher.returnFrom(thread, value);
|
|
360
|
+
}
|
|
361
|
+
cancelAll(reason) {
|
|
362
|
+
this.dispatcher.cancelAll(reason);
|
|
363
|
+
}
|
|
364
|
+
release() {
|
|
365
|
+
this.dispatcher.release();
|
|
366
|
+
this.promises.clear();
|
|
367
|
+
}
|
|
368
|
+
lookup(ref) {
|
|
369
|
+
const id = typeof ref === "object" && ref !== null && typeof ref.$promise === "string" ? ref.$promise : void 0;
|
|
370
|
+
return id ? this.promises.get(id) : void 0;
|
|
371
|
+
}
|
|
372
|
+
acquireSlot() {
|
|
373
|
+
if (this.inFlight < this.maxInFlight) {
|
|
374
|
+
this.inFlight += 1;
|
|
375
|
+
return Promise.resolve();
|
|
376
|
+
}
|
|
377
|
+
return new Promise((resolve) => this.waiting.push(() => {
|
|
378
|
+
this.inFlight += 1;
|
|
379
|
+
resolve();
|
|
380
|
+
}));
|
|
381
|
+
}
|
|
382
|
+
releaseSlot() {
|
|
383
|
+
this.inFlight -= 1;
|
|
384
|
+
this.waiting.shift()?.();
|
|
385
|
+
}
|
|
386
|
+
evictSettled() {
|
|
387
|
+
if (this.promises.size <= this.maxRetained) return;
|
|
388
|
+
for (const [id, entry] of this.promises) {
|
|
389
|
+
if (this.promises.size <= this.maxRetained) break;
|
|
390
|
+
if (entry.settled) this.promises.delete(id);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
function messageOf(error) {
|
|
395
|
+
return error instanceof Error ? error.message : String(error);
|
|
396
|
+
}
|
|
397
|
+
//#endregion
|
|
398
|
+
export { FUNCTION_NAME_PATTERN, createNamedFunctions, parseJsonOrText, readArgumentPath, scanFunctionDefinitions, toFunctionTools, toScratchValue, validateAgainstSchema };
|