@kubohiroya/turbowarp-openai-realtime-api 0.5.0 → 0.5.2

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
@@ -55,7 +55,7 @@ OpenAI Realtime APIと音声やテキストで会話し、ブロックで書い
55
55
  npm packageとして使う場合は、検証済みのversionをexact pinします。
56
56
 
57
57
  ```bash
58
- pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.5.0
58
+ pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.5.2
59
59
  ```
60
60
 
61
61
  ## クイックスタート
package/README.md CHANGED
@@ -61,7 +61,7 @@ The reviewed JavaScript build is committed to this repository, so users do not n
61
61
  Install an exact version that you have reviewed:
62
62
 
63
63
  ```bash
64
- pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.5.0
64
+ pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.5.2
65
65
  ```
66
66
 
67
67
  Standalone bundle:
@@ -196,26 +196,50 @@ function fixedInputEditorOptions() {
196
196
  })
197
197
  }));
198
198
  }
199
- /** Register only visible static contracts; ordinary composition consumers load no editor runtime. */
199
+ /**
200
+ * Register only visible static contracts; ordinary composition consumers load no editor runtime.
201
+ * Every project load disposes the runtime while the extension stays loaded for the next project,
202
+ * so RUNTIME_DISPOSED only releases the registrations and the next PROJECT_LOADED registers the
203
+ * same ones again. The returned dispose is final.
204
+ */
200
205
  function registerFixedInputEditors(scratch, runtime, visibleBlocks) {
201
206
  const api = scratch.gui?.blockEditors;
202
207
  if (api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function") return void 0;
208
+ const registerEditor = api.registerFixedInputEditor;
203
209
  const visibleOpcodes = new Set(visibleBlocks.flatMap((block) => {
204
210
  if (typeof block !== "object" || block === null || !("opcode" in block)) return [];
205
211
  return typeof block.opcode === "string" ? [block.opcode] : [];
206
212
  }));
213
+ const visibleOptions = fixedInputEditorOptions().filter((options) => options.opcodes.some((opcode) => visibleOpcodes.has(opcode.slice(25))));
207
214
  const events = runtime;
208
215
  const removers = [];
209
- let active = true;
210
- const dispose = () => {
211
- if (!active) return;
212
- active = false;
213
- events?.off?.("RUNTIME_DISPOSED", dispose);
216
+ let registered = false;
217
+ let disposed = false;
218
+ const release = () => {
219
+ registered = false;
214
220
  for (const remove of removers.splice(0).reverse()) remove();
215
221
  };
222
+ const register = () => {
223
+ if (disposed || registered) return;
224
+ registered = true;
225
+ try {
226
+ for (const options of visibleOptions) removers.push(registerEditor.call(api, options));
227
+ } catch (error) {
228
+ release();
229
+ throw error;
230
+ }
231
+ };
232
+ const dispose = () => {
233
+ if (disposed) return;
234
+ disposed = true;
235
+ events?.off?.("RUNTIME_DISPOSED", release);
236
+ events?.off?.("PROJECT_LOADED", register);
237
+ release();
238
+ };
216
239
  try {
217
- for (const options of fixedInputEditorOptions()) if (options.opcodes.some((opcode) => visibleOpcodes.has(opcode.slice(25)))) removers.push(api.registerFixedInputEditor.call(api, options));
218
- events?.on?.("RUNTIME_DISPOSED", dispose);
240
+ register();
241
+ events?.on?.("RUNTIME_DISPOSED", release);
242
+ events?.on?.("PROJECT_LOADED", register);
219
243
  } catch (error) {
220
244
  dispose();
221
245
  throw error;
@@ -534,7 +558,7 @@ var block_definitions_default = {
534
558
  }
535
559
  };
536
560
  //#endregion
537
- //#region node_modules/.pnpm/@kubohiroya+turbowarp-named-functions@0.4.1-rc.2/node_modules/@kubohiroya/turbowarp-named-functions/dist/composition.js
561
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-named-functions@0.4.2/node_modules/@kubohiroya/turbowarp-named-functions/dist/composition.js
538
562
  /**
539
563
  * A small JSON Schema validator for function arguments and returns. It interprets the schema at run time and
540
564
  * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
@@ -651,12 +675,18 @@ function deepEqual(left, right) {
651
675
  function asRecord$2(value) {
652
676
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
653
677
  }
678
+ function outcomeToPromise(outcome) {
679
+ if (outcome.state === "fulfilled") return Promise.resolve(outcome.value);
680
+ if (outcome.state === "rejected") return Promise.reject(outcome.error);
681
+ return outcome.promise;
682
+ }
654
683
  var FunctionDispatcher = class {
655
684
  constructor(runtime, options) {
656
685
  this.runtime = runtime;
657
686
  this.options = options;
658
687
  this.queue = [];
659
688
  this.running = /* @__PURE__ */ new Map();
689
+ this.direct = /* @__PURE__ */ new Set();
660
690
  this.byThread = /* @__PURE__ */ new Map();
661
691
  this.starting = null;
662
692
  this.step = 0;
@@ -665,39 +695,62 @@ var FunctionDispatcher = class {
665
695
  this.timeoutMs = options.timeoutMs ?? 3e4;
666
696
  this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
667
697
  this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
698
+ const port = runtime.getThreadExecutionPort?.();
699
+ this.port = port?.version === 1 ? port : null;
668
700
  runtime.on("AFTER_EXECUTE", this.onAfterExecute);
669
701
  runtime.on("PROJECT_STOP_ALL", this.onStopAll);
670
702
  }
703
+ /** True when calls run inside the calling block and may recurse. */
704
+ get runsSynchronously() {
705
+ return this.port !== null;
706
+ }
671
707
  /**
672
708
  * Starts a named function. `caller` is the thread of the block making the call, if any; it is used
673
709
  * to detect reentrant calls.
674
710
  */
675
711
  invoke(name, args, caller, returnSchema) {
676
- if (!this.options.knownNames().has(name)) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${name}`));
712
+ return outcomeToPromise(this.invokeNow({
713
+ name,
714
+ args,
715
+ caller,
716
+ returnSchema
717
+ }));
718
+ }
719
+ /**
720
+ * Starts a named function and reports right away whether it already settled. With the port and a
721
+ * `script`, a function that does not wait settles before this returns.
722
+ */
723
+ invokeNow(request) {
724
+ const { name, caller } = request;
725
+ if (!this.options.knownNames().has(name)) return {
726
+ state: "rejected",
727
+ error: /* @__PURE__ */ new Error(`Unknown function: ${name}`)
728
+ };
677
729
  const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
678
- if (parentChain.includes(name)) return Promise.reject(/* @__PURE__ */ new Error(`Reentrant call: ${[...parentChain, name].join(" -> ")}. Use a custom block for recursion.`));
679
- return new Promise((resolve, reject) => {
680
- const invocation = {
681
- name,
682
- args,
683
- ...returnSchema === void 0 ? {} : { returnSchema },
684
- chain: [...parentChain, name],
685
- resolve,
686
- reject,
687
- thread: null,
688
- startedAtStep: -1,
689
- timer: null,
690
- settled: false
691
- };
692
- invocation.timer = this.setTimer(() => this.settle(invocation, /* @__PURE__ */ new Error(`Function ${name} timed out.`)), this.timeoutMs);
693
- this.queue.push(invocation);
694
- this.pump();
695
- });
730
+ const chain = [...parentChain, name];
731
+ if (this.port && request.script) return this.runDirect(this.port, request, chain);
732
+ if (parentChain.includes(name)) return {
733
+ state: "rejected",
734
+ error: /* @__PURE__ */ new Error(`Reentrant call: ${chain.join(" -> ")}. Recursion needs the TurboWarp Plus runtime; use a custom block for recursion here.`)
735
+ };
736
+ const invocation = this.createInvocation(request, chain);
737
+ this.armTimer(invocation);
738
+ this.queue.push(invocation);
739
+ this.pump();
740
+ return invocation.outcome ?? {
741
+ state: "pending",
742
+ promise: invocation.promise
743
+ };
696
744
  }
697
745
  /** Hat predicate: true only for the script that should run the invocation being started. */
698
746
  matchHat(name, thread) {
747
+ if (!thread) return false;
748
+ const bound = this.byThread.get(thread);
749
+ if (bound) return bound.name === name.trim();
699
750
  const invocation = this.starting;
700
- if (!invocation || !thread || invocation.name !== name.trim()) return false;
751
+ if (!invocation || invocation.name !== name.trim()) return false;
752
+ const script = invocation.script;
753
+ if (script && (thread.topBlock !== script.blockId || thread.target && thread.target !== script.target)) return false;
701
754
  invocation.thread = thread;
702
755
  this.byThread.set(thread, invocation);
703
756
  this.starting = null;
@@ -714,17 +767,68 @@ var FunctionDispatcher = class {
714
767
  this.settleWithValue(invocation, value);
715
768
  }
716
769
  cancelAll(reason) {
717
- for (const invocation of [...this.queue, ...this.running.values()]) this.settle(invocation, new Error(reason));
770
+ for (const invocation of [
771
+ ...this.queue,
772
+ ...this.running.values(),
773
+ ...this.direct
774
+ ]) this.settle(invocation, new Error(reason));
718
775
  if (this.starting) this.settle(this.starting, new Error(reason));
719
776
  }
720
777
  get pendingCount() {
721
- return this.queue.length + this.running.size;
778
+ return this.queue.length + this.running.size + this.direct.size;
722
779
  }
723
780
  release() {
724
781
  this.cancelAll("Named functions were released.");
725
782
  this.runtime.off?.("AFTER_EXECUTE", this.onAfterExecute);
726
783
  this.runtime.off?.("PROJECT_STOP_ALL", this.onStopAll);
727
784
  }
785
+ runDirect(port, request, chain) {
786
+ const invocation = this.createInvocation(request, chain);
787
+ invocation.promise.catch(() => void 0);
788
+ const script = request.script;
789
+ try {
790
+ const thread = port.startScript(script.blockId, script.target);
791
+ invocation.thread = thread;
792
+ this.byThread.set(thread, invocation);
793
+ this.direct.add(invocation);
794
+ if (chain.length <= 128 && port.runNow(thread) === "done") this.settleWithValue(invocation, null);
795
+ } catch (error) {
796
+ this.settle(invocation, error instanceof Error ? error : new Error(String(error)));
797
+ }
798
+ if (invocation.outcome) return invocation.outcome;
799
+ this.armTimer(invocation);
800
+ return {
801
+ state: "pending",
802
+ promise: invocation.promise
803
+ };
804
+ }
805
+ createInvocation(request, chain) {
806
+ let resolve = () => void 0;
807
+ let reject = () => void 0;
808
+ const promise = new Promise((resolvePromise, rejectPromise) => {
809
+ resolve = resolvePromise;
810
+ reject = rejectPromise;
811
+ });
812
+ return {
813
+ name: request.name,
814
+ args: request.args,
815
+ ...request.returnSchema === void 0 ? {} : { returnSchema: request.returnSchema },
816
+ chain,
817
+ ...request.script ? { script: request.script } : {},
818
+ promise,
819
+ resolve,
820
+ reject,
821
+ thread: null,
822
+ startedAtStep: -1,
823
+ timer: null,
824
+ settled: false,
825
+ outcome: null
826
+ };
827
+ }
828
+ armTimer(invocation) {
829
+ if (invocation.settled) return;
830
+ invocation.timer = this.setTimer(() => this.settle(invocation, /* @__PURE__ */ new Error(`Function ${invocation.name} timed out.`)), this.timeoutMs);
831
+ }
728
832
  pump() {
729
833
  if (this.starting) return;
730
834
  const index = this.queue.findIndex((invocation) => !this.running.has(invocation.name));
@@ -740,20 +844,32 @@ var FunctionDispatcher = class {
740
844
  this.step += 1;
741
845
  const starting = this.starting;
742
846
  if (starting && this.step - starting.startedAtStep > 2) this.settle(starting, /* @__PURE__ */ new Error(`Function ${starting.name} did not start. Is its script already running?`));
743
- for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
847
+ for (const invocation of [...this.running.values(), ...this.direct]) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
744
848
  this.pump();
745
849
  }
746
850
  settle(invocation, error, value) {
747
851
  if (invocation.settled) return;
748
852
  invocation.settled = true;
749
- this.clearTimer(invocation.timer);
853
+ if (invocation.timer !== null) this.clearTimer(invocation.timer);
750
854
  const queued = this.queue.indexOf(invocation);
751
855
  if (queued >= 0) this.queue.splice(queued, 1);
752
856
  if (this.running.get(invocation.name) === invocation) this.running.delete(invocation.name);
857
+ this.direct.delete(invocation);
753
858
  if (invocation.thread) this.byThread.delete(invocation.thread);
754
859
  if (this.starting === invocation) this.starting = null;
755
- if (error) invocation.reject(error);
756
- else invocation.resolve(value);
860
+ if (error) {
861
+ invocation.outcome = {
862
+ state: "rejected",
863
+ error
864
+ };
865
+ invocation.reject(error);
866
+ } else {
867
+ invocation.outcome = {
868
+ state: "fulfilled",
869
+ value
870
+ };
871
+ invocation.resolve(value);
872
+ }
757
873
  }
758
874
  settleWithValue(invocation, value) {
759
875
  if (invocation.returnSchema !== void 0) {
@@ -838,9 +954,8 @@ var MAX_DESCRIPTION_LENGTH = 1024;
838
954
  * tool contract sent to the model before any script runs, so they must be literal text.
839
955
  */
840
956
  function scanFunctionDefinitions(targets, hatOpcode, options = {}) {
841
- const functions = [];
957
+ const scanned = [];
842
958
  const errors = [];
843
- const seen = /* @__PURE__ */ new Map();
844
959
  for (const target of targets) {
845
960
  if (target.isOriginal === false) continue;
846
961
  const targetName = target.getName?.() ?? (target.isStage ? "Stage" : "sprite");
@@ -849,22 +964,78 @@ function scanFunctionDefinitions(targets, hatOpcode, options = {}) {
849
964
  if (block.opcode !== hatOpcode || block.topLevel === false) continue;
850
965
  const where = `${targetName} (block ${block.id})`;
851
966
  try {
852
- const definition = readDefinition(block, blocks, targetName, options);
853
- const previous = seen.get(definition.name);
854
- if (previous !== void 0) throw new Error(`function "${definition.name}" is already defined in ${previous}`);
855
- seen.set(definition.name, where);
856
- functions.push(definition);
967
+ scanned.push({
968
+ definition: readDefinition(block, blocks, targetName, target, options),
969
+ where
970
+ });
857
971
  } catch (error) {
858
972
  errors.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
859
973
  }
860
974
  }
861
975
  }
976
+ const functions = [];
977
+ const globals = /* @__PURE__ */ new Map();
978
+ for (const { definition, where } of scanned) {
979
+ if (definition.scope !== "global") continue;
980
+ const previous = globals.get(definition.name);
981
+ if (previous !== void 0) {
982
+ errors.push(`${where}: function "${definition.name}" is already defined in ${previous}`);
983
+ continue;
984
+ }
985
+ globals.set(definition.name, where);
986
+ functions.push(definition);
987
+ }
988
+ const locals = /* @__PURE__ */ new Map();
989
+ for (const { definition, where } of scanned) {
990
+ if (definition.scope !== "sprite") continue;
991
+ const global = globals.get(definition.name);
992
+ if (global !== void 0) {
993
+ errors.push(`${where}: function "${definition.name}" is already defined for all sprites in ${global}`);
994
+ continue;
995
+ }
996
+ const own = locals.get(definition.target) ?? /* @__PURE__ */ new Map();
997
+ locals.set(definition.target, own);
998
+ const previous = own.get(definition.name);
999
+ if (previous !== void 0) {
1000
+ errors.push(`${where}: function "${definition.name}" is already defined in ${previous}`);
1001
+ continue;
1002
+ }
1003
+ own.set(definition.name, where);
1004
+ functions.push(definition);
1005
+ }
862
1006
  functions.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
863
1007
  return {
864
1008
  functions,
865
1009
  errors
866
1010
  };
867
1011
  }
1012
+ /** True when both are the same sprite: the original, one of its clones, or the stage itself. */
1013
+ function sameSprite(left, right) {
1014
+ return left === right || left.sprite !== void 0 && left.sprite === right.sprite;
1015
+ }
1016
+ /**
1017
+ * Finds the function a call names. A caller's own sprite function runs as the caller (a clone runs it
1018
+ * as itself, as with a custom block); a global function runs as the sprite or stage that defines it.
1019
+ * Without a caller (a call from outside the project), only global functions are visible.
1020
+ */
1021
+ function resolveFunction(functions, name, caller) {
1022
+ if (caller) {
1023
+ const own = functions.find((definition) => definition.scope === "sprite" && definition.name === name && sameSprite(definition.target, caller));
1024
+ if (own) return {
1025
+ definition: own,
1026
+ runAs: caller
1027
+ };
1028
+ }
1029
+ const global = functions.find((definition) => definition.scope === "global" && definition.name === name);
1030
+ return global ? {
1031
+ definition: global,
1032
+ runAs: global.target
1033
+ } : void 0;
1034
+ }
1035
+ /** Functions a script of `caller` can call: its sprite's own functions, then the global ones. */
1036
+ function visibleFunctions(functions, caller) {
1037
+ return functions.filter((definition) => definition.scope === "global" || caller !== void 0 && sameSprite(definition.target, caller));
1038
+ }
868
1039
  function toFunctionTools(functions) {
869
1040
  return functions.filter((definition) => definition.exportAs === "tool").map((definition) => ({
870
1041
  type: "function",
@@ -873,7 +1044,7 @@ function toFunctionTools(functions) {
873
1044
  parameters: definition.parameters
874
1045
  }));
875
1046
  }
876
- function readDefinition(block, blocks, targetName, options) {
1047
+ function readDefinition(block, blocks, targetName, target, options) {
877
1048
  const name = readLiteralInput(block, blocks, "NAME").trim();
878
1049
  if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
879
1050
  const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
@@ -883,16 +1054,27 @@ function readDefinition(block, blocks, targetName, options) {
883
1054
  const returns = returnsText === void 0 || returnsText.trim() === "" ? void 0 : parseSchema(returnsText, "returns schema", false, options);
884
1055
  const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
885
1056
  if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
1057
+ const scope = readScope(block);
1058
+ if (exportAs === "tool" && scope !== "global") throw new Error("a function exported as a tool must be for all sprites");
886
1059
  return {
887
1060
  name,
1061
+ scope,
888
1062
  description,
889
1063
  parameters,
890
1064
  ...returns ? { returns } : {},
891
1065
  exportAs,
892
1066
  targetName,
1067
+ target,
893
1068
  blockId: block.id
894
1069
  };
895
1070
  }
1071
+ /** SCOPE is a menu field. Hats saved before it existed have none and keep their global meaning. */
1072
+ function readScope(block) {
1073
+ const value = block.fields?.SCOPE?.value;
1074
+ if (value === void 0 || value === null || value === "global") return "global";
1075
+ if (value === "sprite") return "sprite";
1076
+ throw new Error(`unknown function scope "${String(value)}"`);
1077
+ }
896
1078
  /**
897
1079
  * SCHEMA and RETURNS hold either JSON Schema text or, when the consumer supports it, the name of a
898
1080
  * `define schema` hat. Text that is not JSON is treated as a name, so existing JSON projects are
@@ -1259,17 +1441,39 @@ var NamedFunctionsImpl = class {
1259
1441
  if (errors.length > 0) throw new Error(`Invalid function definitions: ${errors.join("; ")}`);
1260
1442
  return toFunctionTools(this.scan().functions);
1261
1443
  }
1262
- isDefined(name) {
1263
- return this.scan().functions.some((definition) => definition.name === name.trim());
1444
+ isDefined(name, caller) {
1445
+ return resolveFunction(this.scan().functions, name.trim(), caller) !== void 0;
1446
+ }
1447
+ visible(caller) {
1448
+ const functions = visibleFunctions(this.scan().functions, caller);
1449
+ return [...functions.filter((definition) => definition.scope === "sprite"), ...functions.filter((definition) => definition.scope === "global")];
1450
+ }
1451
+ get runsSynchronously() {
1452
+ return this.dispatcher.runsSynchronously;
1264
1453
  }
1265
1454
  call(name, args, options = {}) {
1455
+ return outcomeToPromise(this.callNow(name, args, options));
1456
+ }
1457
+ callNow(name, args, options = {}) {
1266
1458
  const trimmed = name.trim();
1267
- const definition = this.scan().functions.find((candidate) => candidate.name === trimmed);
1268
- if (!definition) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${trimmed}`));
1269
- if (options.exportedOnly && definition.exportAs !== "tool") return Promise.reject(/* @__PURE__ */ new Error(`Function ${trimmed} is not exported as a tool.`));
1459
+ const scan = this.scan();
1460
+ const caller = options.caller?.target;
1461
+ const resolved = resolveFunction(scan.functions, trimmed, caller);
1462
+ if (!resolved) return rejected(unknownFunctionMessage(scan.functions, trimmed, caller));
1463
+ const { definition, runAs } = resolved;
1464
+ if (options.exportedOnly && definition.exportAs !== "tool") return rejected(`Function ${trimmed} is not exported as a tool.`);
1270
1465
  const errors = validateAgainstSchema(args, definition.parameters);
1271
- if (errors.length > 0) return Promise.reject(/* @__PURE__ */ new Error(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`));
1272
- return this.dispatcher.invoke(trimmed, args, options.caller, definition.returns);
1466
+ if (errors.length > 0) return rejected(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`);
1467
+ return this.dispatcher.invokeNow({
1468
+ name: trimmed,
1469
+ args,
1470
+ caller: options.caller,
1471
+ returnSchema: definition.returns,
1472
+ script: {
1473
+ target: runAs,
1474
+ blockId: definition.blockId
1475
+ }
1476
+ });
1273
1477
  }
1274
1478
  start(name, args, options = {}) {
1275
1479
  const id = `p_${this.nextPromiseId++}`;
@@ -1336,6 +1540,18 @@ var NamedFunctionsImpl = class {
1336
1540
  }
1337
1541
  }
1338
1542
  };
1543
+ /** Names the sprite that owns a function the caller cannot see, so the fix is obvious. */
1544
+ function unknownFunctionMessage(functions, name, caller) {
1545
+ const elsewhere = functions.find((definition) => definition.name === name);
1546
+ if (!elsewhere) return `Unknown function: ${name}`;
1547
+ return caller ? `Function ${name} belongs to ${elsewhere.targetName}; make it for all sprites to call it from here.` : `Function ${name} belongs to ${elsewhere.targetName}; only functions for all sprites can be called from outside.`;
1548
+ }
1549
+ function rejected(message) {
1550
+ return {
1551
+ state: "rejected",
1552
+ error: new Error(message)
1553
+ };
1554
+ }
1339
1555
  function messageOf$2(error) {
1340
1556
  return error instanceof Error ? error.message : String(error);
1341
1557
  }
@@ -10,6 +10,11 @@ export declare function readNumber(value: LiteralValue): number;
10
10
  export declare function newNumberToken(value: JsonValue): string;
11
11
  export declare function candidateValid(_opcode: string, _argument: string, schema: InputSchema, value: LiteralValue): boolean;
12
12
  export declare function fixedInputEditorOptions(): readonly FixedInputEditorOptions[];
13
- /** Register only visible static contracts; ordinary composition consumers load no editor runtime. */
13
+ /**
14
+ * Register only visible static contracts; ordinary composition consumers load no editor runtime.
15
+ * Every project load disposes the runtime while the extension stays loaded for the next project,
16
+ * so RUNTIME_DISPOSED only releases the registrations and the next PROJECT_LOADED registers the
17
+ * same ones again. The returned dispose is final.
18
+ */
14
19
  export declare function registerFixedInputEditors(scratch: unknown, runtime: unknown, visibleBlocks: readonly unknown[]): (() => void) | undefined;
15
20
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-openai-realtime-api",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "A TurboWarp extension for the OpenAI Realtime API, using a localhost relay for credentials.",
5
5
  "author": {
6
6
  "name": "Hiroya Kubo",
@@ -73,7 +73,7 @@
73
73
  "typescript-eslint": "^8.66.0",
74
74
  "vite": "^8.2.2",
75
75
  "vitest": "^5.0.0",
76
- "@kubohiroya/turbowarp-extension-data-editor": "^0.8.1"
76
+ "@kubohiroya/turbowarp-extension-data-editor": "^0.10.0"
77
77
  },
78
78
  "exports": {
79
79
  "./composition": {
@@ -84,7 +84,7 @@
84
84
  "./package.json": "./package.json"
85
85
  },
86
86
  "dependencies": {
87
- "@kubohiroya/turbowarp-named-functions": "^0.4.1-rc.2"
87
+ "@kubohiroya/turbowarp-named-functions": "^0.4.2"
88
88
  },
89
89
  "gitHead": "2386a92f281d6285af4c9c61f19e2577453708e5",
90
90
  "x-turbowarp-source": {
@@ -157,7 +157,12 @@ interface RegistrationRuntime {
157
157
  on?(event: string, listener: () => void): void;
158
158
  off?(event: string, listener: () => void): void;
159
159
  }
160
- /** Register only visible static contracts; ordinary composition consumers load no editor runtime. */
160
+ /**
161
+ * Register only visible static contracts; ordinary composition consumers load no editor runtime.
162
+ * Every project load disposes the runtime while the extension stays loaded for the next project,
163
+ * so RUNTIME_DISPOSED only releases the registrations and the next PROJECT_LOADED registers the
164
+ * same ones again. The returned dispose is final.
165
+ */
161
166
  export function registerFixedInputEditors(
162
167
  scratch: unknown,
163
168
  runtime: unknown,
@@ -180,6 +185,7 @@ export function registerFixedInputEditors(
180
185
  typeof api.registerFixedInputEditor !== "function"
181
186
  )
182
187
  return undefined;
188
+ const registerEditor = api.registerFixedInputEditor;
183
189
  const visibleOpcodes = new Set(
184
190
  visibleBlocks.flatMap((block) => {
185
191
  if (typeof block !== "object" || block === null || !("opcode" in block))
@@ -187,25 +193,41 @@ export function registerFixedInputEditors(
187
193
  return typeof block.opcode === "string" ? [block.opcode] : [];
188
194
  }),
189
195
  );
196
+ const visibleOptions = fixedInputEditorOptions().filter((options) =>
197
+ options.opcodes.some((opcode) =>
198
+ visibleOpcodes.has(opcode.slice(extensionId.length + 1)),
199
+ ),
200
+ );
190
201
  const events = runtime as RegistrationRuntime | undefined;
191
202
  const removers: (() => void)[] = [];
192
- let active = true;
193
- const dispose = () => {
194
- if (!active) return;
195
- active = false;
196
- events?.off?.("RUNTIME_DISPOSED", dispose);
203
+ let registered = false;
204
+ let disposed = false;
205
+ const release = () => {
206
+ registered = false;
197
207
  for (const remove of removers.splice(0).reverse()) remove();
198
208
  };
199
- try {
200
- for (const options of fixedInputEditorOptions()) {
201
- if (
202
- options.opcodes.some((opcode) =>
203
- visibleOpcodes.has(opcode.slice(extensionId.length + 1)),
204
- )
205
- )
206
- removers.push(api.registerFixedInputEditor.call(api, options));
209
+ const register = () => {
210
+ if (disposed || registered) return;
211
+ registered = true;
212
+ try {
213
+ for (const options of visibleOptions)
214
+ removers.push(registerEditor.call(api, options));
215
+ } catch (error) {
216
+ release();
217
+ throw error;
207
218
  }
208
- events?.on?.("RUNTIME_DISPOSED", dispose);
219
+ };
220
+ const dispose = () => {
221
+ if (disposed) return;
222
+ disposed = true;
223
+ events?.off?.("RUNTIME_DISPOSED", release);
224
+ events?.off?.("PROJECT_LOADED", register);
225
+ release();
226
+ };
227
+ try {
228
+ register();
229
+ events?.on?.("RUNTIME_DISPOSED", release);
230
+ events?.on?.("PROJECT_LOADED", register);
209
231
  } catch (error) {
210
232
  dispose();
211
233
  throw error;