@trim21/personal-pi-extensions 0.1.20261012010044 → 0.1.20261012023047

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.md CHANGED
@@ -31,7 +31,8 @@
31
31
 
32
32
  `codemode` 让模型写一段 JavaScript(作为 async 函数体,`await` 与 `return` 都可用),在
33
33
  进程内的 worker 线程里用 QuickJS wasm VM 执行。VM 里没有 node、文件系统、网络、timer
34
- 或模块加载,脚本的出口只有 `call(name, args)` 与 `fs.read` / `fs.write` 两个文件原语。
34
+ 或模块加载,脚本的出口只有 `call(name, args)`、`fs.read` / `fs.write` 两个文件原语与内建的
35
+ `sleep`。
35
36
 
36
37
  - **嵌套调用经工具总线**:`call("Bash", { command })` 最终执行的是 `Bash` 工具自己的
37
38
  `execute`,所以工具的审批照常生效(Bash 沙箱外执行会弹自己的提权确认)。codemode
@@ -60,9 +61,11 @@
60
61
  (脚本可按 `instanceof CallFailedError` 区分调用失败与自身运行期错误)。没有声明输出
61
62
  结构的工具不进集合,`call()` 会报「not available in codemode」。
62
63
  - **脚本接口**:`call` / `CallFailedError` / `ALL_TOOLS` / `fs.read` / `fs.write` /
63
- `text` / `image` / `exit` / `console.*` / `store.set` / `store.get` / `store.list`
64
+ `text` / `image` / `exit` / `sleep` / `console.*` / `store.set` / `store.get` / `store.list`
64
65
  (会话内持久的键值表);首行可选 `// @options: {"max_output_tokens": 10000}`。
65
66
  脚本没有超时:死循环由调用方中止(Esc)结束,等嵌套调用返回(含用户审批弹窗)多久都不算超时。
67
+ `await sleep(seconds)`(秒,可为小数)是脚本唯一的等待手段,由 worker 线程自己的定时器驱动
68
+ (不经主线程、不产生进度帧),也没有上限——要等多久由脚本决定,不想等就中止。
66
69
  - **工具描述**里给出每个可调用工具的 `declare function call(name, args): Promise<T>` 重载,
67
70
  参数与返回类型都取自工具自己的 schema,所以模型在写脚本前就知道返回值形状。
68
71
  - **store** 记在每次成功调用工具结果的 `details.store` 上(与 `src/lib/file-reads.ts` 的
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trim21/personal-pi-extensions",
3
- "version": "0.1.20261012010044",
3
+ "version": "0.1.20261012023047",
4
4
  "type": "module",
5
5
  "description": "Custom pi coding-agent extensions: bwrap sandbox, workspace guard, opencode edit, and more",
6
6
  "keywords": [
@@ -152,6 +152,7 @@ export function renderDeclarations(tools: readonly ToolLike[]): string {
152
152
  "declare function text(value: unknown): void;",
153
153
  "declare function image(value: unknown): void;",
154
154
  "declare function exit(): void;",
155
+ "declare function sleep(seconds: number): Promise<void>;",
155
156
  "declare const store: { set(key: string, value: unknown): void; get(key: string): unknown; list(): string[] };",
156
157
  ].join("\n");
157
158
  }
@@ -1,16 +1,17 @@
1
1
  /**
2
2
  * codemode 脚本侧的 prelude:在 QuickJS VM 里先于脚本求值,构建脚本能看到的全部
3
3
  * 能力(`call` / `CallFailedError` / `ALL_TOOLS` / `fs` / `text` / `image` / `exit` /
4
- * `console` / `store`),并把宿主桥接封在闭包里——脚本拿不到 `bridge` 本身。
4
+ * `sleep` / `console` / `store`),并把宿主桥接封在闭包里——脚本拿不到 `bridge` 本身。
5
5
  *
6
6
  * 值与参数过桥时都是 JSON 文本,本侧负责 parse/stringify;异步调用用一个 pending
7
7
  * 表把 id 映射到 promise,由宿主在结果到达时 settle。每次调用失败(工具或 fs 原语)
8
8
  * 都由宿主以 `ok: false` 回报,本侧统一 reject 成 `CallFailedError`(脚本可以按
9
9
  * instanceof 区分「调用失败」与自己的运行期错误)。
10
10
  *
11
- * 求值结果是一个函数 `(bridge, toolsJson, storeJson) => { settle, run, stalled }`。
11
+ * 求值结果是一个函数 `(bridge, toolsJson, storeJson) => { settle, timerDone, run, stalled }`。
12
12
  * `bridge(kind, a, b, c)`:
13
13
  * - `"call"`(id, name, argsJson):工具,以及名字为 `fs.read` / `fs.write` 的 fs 原语
14
+ * - `"sleep"`(id, ms):等待,由 worker 线程自己的定时器在 ms 后调 `timerDone(id)`
14
15
  * - `"output"`("text", text)/("image", data, mimeType)
15
16
  * - `"done"`(ok, valueJsonOrErrorJson, writesJson)
16
17
  */
@@ -259,6 +260,22 @@ export const PRELUDE_SOURCE = String.raw`(function (bridge, toolsJson, storeJson
259
260
  throw EXIT;
260
261
  }
261
262
 
263
+ // 脚本唯一的等待手段:worker 线程在 ms 后调 timerDone(id) 解开它。沙箱里没有别的
264
+ // timer,也没有上限——睡多久由脚本决定,结束只能靠调用方中止。
265
+ function sleep(seconds) {
266
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds < 0) {
267
+ throw new TypeErrorCtor(
268
+ "sleep(seconds) expects a non-negative number of seconds, got " + format(seconds),
269
+ );
270
+ }
271
+ return new Promise((resolve) => {
272
+ const id = nextId++;
273
+ // sleep 只会被 timerDone 成功解开,reject 用不到
274
+ pending.set(id, { resolve, reject: () => {} });
275
+ bridge("sleep", id, Math.round(seconds * 1000));
276
+ });
277
+ }
278
+
262
279
  const console = {};
263
280
  for (const level of ["log", "info", "warn", "error", "debug"]) {
264
281
  console[level] = (...args) => {
@@ -275,6 +292,7 @@ export const PRELUDE_SOURCE = String.raw`(function (bridge, toolsJson, storeJson
275
292
  Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
276
293
  Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
277
294
  Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
295
+ Object.defineProperty(globalThis, "sleep", { value: sleep, enumerable: true });
278
296
 
279
297
  return {
280
298
  settle(id, ok, payload) {
@@ -294,6 +312,13 @@ export const PRELUDE_SOURCE = String.raw`(function (bridge, toolsJson, storeJson
294
312
  }
295
313
  entry.resolve(value);
296
314
  },
315
+ // worker 线程的定时器到点后解开一次 sleep(成功路径,不带值)
316
+ timerDone(id) {
317
+ const entry = pending.get(id);
318
+ if (!entry) return;
319
+ pending.delete(id);
320
+ entry.resolve();
321
+ },
297
322
  run(fn) {
298
323
  let promise;
299
324
  try {
@@ -6,8 +6,9 @@
6
6
  * 主线程执行工具后把结果发回去。脚本没有超时,只有调用方的中止:中止时主线程直接
7
7
  * `worker.terminate()`,因此不需要取消消息。
8
8
  *
9
- * worker 边界两侧都做 typebox 校验:worker 里跑的是模型写的代码,回传的消息同样
10
- * 当外部输入对待。
9
+ * 校验只做一个方向:worker 里跑的是模型写的代码,它回传的消息由主线程用 typebox
10
+ * 当外部输入复核;反向的消息是主线程自己构造的,形状由 `HostMessage` 类型约束,
11
+ * worker 只按 `t` 分派。
11
12
  */
12
13
 
13
14
  import { type TSchema, Type } from "typebox";
@@ -32,35 +33,6 @@ const outputItemSchema = Type.Union([
32
33
  Type.Object({ type: Type.Literal("image"), data: Type.String(), mimeType: Type.String() }),
33
34
  ]);
34
35
 
35
- const toolDeclSchema = Type.Object({
36
- name: Type.String(),
37
- description: Type.Optional(Type.String()),
38
- /** 工具的 structuredSchema(TypeBox schema):脚本侧据此渲染 call() 的返回类型。 */
39
- structuredSchema: Type.Optional(Type.Unknown()),
40
- });
41
-
42
- const startSchema = Type.Object({
43
- t: Type.Literal("start"),
44
- code: Type.String(),
45
- tools: Type.Array(toolDeclSchema),
46
- store: Type.Record(Type.String(), Type.Unknown()),
47
- });
48
-
49
- const resultSchema = Type.Union([
50
- Type.Object({
51
- t: Type.Literal("result"),
52
- id: Type.Number(),
53
- ok: Type.Literal(true),
54
- value: Type.Unknown(),
55
- }),
56
- Type.Object({
57
- t: Type.Literal("result"),
58
- id: Type.Number(),
59
- ok: Type.Literal(false),
60
- error: Type.String(),
61
- }),
62
- ]);
63
-
64
36
  const callSchema = Type.Object({
65
37
  t: Type.Literal("call"),
66
38
  id: Type.Number(),
@@ -100,7 +72,6 @@ const doneSchema = Type.Union([
100
72
  }),
101
73
  ]);
102
74
 
103
- const hostMessageSchema = Type.Union([startSchema, resultSchema]);
104
75
  const workerMessageSchema = Type.Union([callSchema, outputFrameSchema, doneSchema]);
105
76
 
106
77
  /** worker 启动数据:注册时编译好的 wasm 模块(结构化克隆可以带它跨线程)。 */
@@ -155,11 +126,6 @@ function decode<T>(schema: TSchema, value: unknown): DecodeResult<T> {
155
126
  return { ok: true, frame: value as T };
156
127
  }
157
128
 
158
- /** 校验主线程发给 worker 的消息。 */
159
- export function decodeHostMessage(value: unknown): DecodeResult<HostMessage> {
160
- return decode<HostMessage>(hostMessageSchema, value);
161
- }
162
-
163
129
  /** 校验 worker 发回主线程的消息。 */
164
130
  export function decodeWorkerMessage(value: unknown): DecodeResult<WorkerMessage> {
165
131
  return decode<WorkerMessage>(workerMessageSchema, value);
@@ -113,6 +113,8 @@ function buildDescription(tools: readonly CallableTool[]): string {
113
113
  " fields you need into `text(value)` / `return` — e.g. `text(result.items.map((item) => item.title))`.",
114
114
  "- Do not stringify whole results (`JSON.stringify(result)`) or print every field the tool happened to",
115
115
  " return: urls, ids and metadata you will not use cost context and buy nothing.",
116
+ "- `await sleep(seconds)` waits that many seconds (fractions allowed). It is the only way to",
117
+ ' wait: the sandbox has no timers, and it beats `call("Bash", { command: "sleep 1" })`.',
116
118
  "- `store.set(key, value)`, `store.get(key)` and `store.list()` are a small key/value store that",
117
119
  " persists across codemode calls in this session; `store.set(key, undefined)` removes a key.",
118
120
  "- The sandbox has no file system, network, timers or Node APIs: calling tools is its only",
@@ -8,6 +8,11 @@ var __export = (target, all) => {
8
8
  import { parentPort, workerData } from "node:worker_threads";
9
9
  import { JSException, MAX_STACK_SIZE, QuickJS } from "quickjs-wasi";
10
10
 
11
+ // src/lib/narrow.ts
12
+ function isRecord(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+
11
16
  // src/codemode/prelude.ts
12
17
  var MAX_STORE_VALUE_CHARS = 256 * 1024;
13
18
  var MAX_STORE_TOTAL_CHARS = 1024 * 1024;
@@ -248,6 +253,22 @@ var PRELUDE_SOURCE = String.raw`(function (bridge, toolsJson, storeJson) {
248
253
  throw EXIT;
249
254
  }
250
255
 
256
+ // 脚本唯一的等待手段:worker 线程在 ms 后调 timerDone(id) 解开它。沙箱里没有别的
257
+ // timer,也没有上限——睡多久由脚本决定,结束只能靠调用方中止。
258
+ function sleep(seconds) {
259
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds < 0) {
260
+ throw new TypeErrorCtor(
261
+ "sleep(seconds) expects a non-negative number of seconds, got " + format(seconds),
262
+ );
263
+ }
264
+ return new Promise((resolve) => {
265
+ const id = nextId++;
266
+ // sleep 只会被 timerDone 成功解开,reject 用不到
267
+ pending.set(id, { resolve, reject: () => {} });
268
+ bridge("sleep", id, Math.round(seconds * 1000));
269
+ });
270
+ }
271
+
251
272
  const console = {};
252
273
  for (const level of ["log", "info", "warn", "error", "debug"]) {
253
274
  console[level] = (...args) => {
@@ -264,6 +285,7 @@ var PRELUDE_SOURCE = String.raw`(function (bridge, toolsJson, storeJson) {
264
285
  Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
265
286
  Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
266
287
  Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
288
+ Object.defineProperty(globalThis, "sleep", { value: sleep, enumerable: true });
267
289
 
268
290
  return {
269
291
  settle(id, ok, payload) {
@@ -283,6 +305,13 @@ var PRELUDE_SOURCE = String.raw`(function (bridge, toolsJson, storeJson) {
283
305
  }
284
306
  entry.resolve(value);
285
307
  },
308
+ // worker 线程的定时器到点后解开一次 sleep(成功路径,不带值)
309
+ timerDone(id) {
310
+ const entry = pending.get(id);
311
+ if (!entry) return;
312
+ pending.delete(id);
313
+ entry.resolve();
314
+ },
286
315
  run(fn) {
287
316
  let promise;
288
317
  try {
@@ -1371,15 +1400,15 @@ function Get2() {
1371
1400
 
1372
1401
  // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/type/types/_codec.mjs
1373
1402
  var EncodeBuilder = class {
1374
- constructor(type, decode2) {
1403
+ constructor(type, decode) {
1375
1404
  this.type = type;
1376
- this.decode = decode2;
1405
+ this.decode = decode;
1377
1406
  }
1378
1407
  Encode(callback) {
1379
1408
  const type = this.type;
1380
- const decode2 = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
1409
+ const decode = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
1381
1410
  const encode = IsCodec(type) ? (value) => type["~codec"].encode(callback(value)) : callback;
1382
- const codec = { decode: decode2, encode };
1411
+ const codec = { decode, encode };
1383
1412
  return memory_exports.Update(this.type, { "~codec": codec }, {});
1384
1413
  }
1385
1414
  };
@@ -4707,8 +4736,8 @@ function RestSpread(types) {
4707
4736
  }
4708
4737
 
4709
4738
  // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/type/engine/instantiate.mjs
4710
- function State(callstack, visited2) {
4711
- return { callstack, visited: visited2 };
4739
+ function State(callstack, visited) {
4740
+ return { callstack, visited };
4712
4741
  }
4713
4742
  function CanInstantiate(types) {
4714
4743
  return guard_exports.ShiftLeft(types, (left, right) => IsRef(left) ? false : CanInstantiate(right), () => true);
@@ -7286,15 +7315,6 @@ var AssertError = class extends Error {
7286
7315
  });
7287
7316
  }
7288
7317
  };
7289
- function Assert(...args) {
7290
- const [context, type, value] = arguments_exports.Match(args, {
7291
- 3: (context2, type2, value2) => [context2, type2, value2],
7292
- 2: (type2, value2) => [{}, type2, value2]
7293
- });
7294
- const check = Check2(context, type, value);
7295
- if (!check)
7296
- throw new AssertError("Assert", value, Errors2(context, type, value));
7297
- }
7298
7318
 
7299
7319
  // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/clean/from_array.mjs
7300
7320
  function FromArray7(context, type, value) {
@@ -8095,7 +8115,7 @@ var DecodeError = class extends AssertError {
8095
8115
  super("Decode", value, errors);
8096
8116
  }
8097
8117
  };
8098
- function Assert2(context, type, value) {
8118
+ function Assert(context, type, value) {
8099
8119
  if (!Check2(context, type, value))
8100
8120
  throw new DecodeError(value, Errors2(context, type, value));
8101
8121
  return value;
@@ -8109,16 +8129,9 @@ var Decoder = Pipeline([
8109
8129
  (context, type, value) => Default(context, type, value),
8110
8130
  (context, type, value) => Convert(context, type, value),
8111
8131
  (context, type, value) => Clean(context, type, value),
8112
- (context, type, value) => Assert2(context, type, value),
8132
+ (context, type, value) => Assert(context, type, value),
8113
8133
  (context, type, value) => DecodeUnsafe(context, type, value)
8114
8134
  ]);
8115
- function Decode10(...args) {
8116
- const [context, type, value] = arguments_exports.Match(args, {
8117
- 3: (context2, type2, value2) => [context2, type2, value2],
8118
- 2: (type2, value2) => [{}, type2, value2]
8119
- });
8120
- return Decoder(context, type, value);
8121
- }
8122
8135
 
8123
8136
  // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/codec/encode.mjs
8124
8137
  var EncodeError = class extends AssertError {
@@ -8126,7 +8139,7 @@ var EncodeError = class extends AssertError {
8126
8139
  super("Encode", value, errors);
8127
8140
  }
8128
8141
  };
8129
- function Assert3(context, type, value) {
8142
+ function Assert2(context, type, value) {
8130
8143
  if (!Check2(context, type, value))
8131
8144
  throw new EncodeError(value, Errors2(context, type, value));
8132
8145
  return value;
@@ -8141,248 +8154,8 @@ var Encoder = Pipeline([
8141
8154
  (context, type, value) => Default(context, type, value),
8142
8155
  (context, type, value) => Convert(context, type, value),
8143
8156
  (context, type, value) => Clean(context, type, value),
8144
- (context, type, value) => Assert3(context, type, value)
8157
+ (context, type, value) => Assert2(context, type, value)
8145
8158
  ]);
8146
- function Encode10(...args) {
8147
- const [context, type, value] = arguments_exports.Match(args, {
8148
- 3: (context2, type2, value2) => [context2, type2, value2],
8149
- 2: (type2, value2) => [{}, type2, value2]
8150
- });
8151
- return Encoder(context, type, value);
8152
- }
8153
-
8154
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/codec/has.mjs
8155
- function FromArray11(context, type) {
8156
- return IsCodec(type) || FromType24(context, type.items);
8157
- }
8158
- function FromCyclic10(context, type) {
8159
- return IsCodec(type) || FromRef9({ ...context, ...type.$defs }, Ref(type.$ref));
8160
- }
8161
- function FromIntersect10(context, type) {
8162
- return IsCodec(type) || type.allOf.some((type2) => FromType24(context, type2));
8163
- }
8164
- function FromObject15(context, type) {
8165
- return IsCodec(type) || guard_exports.Keys(type.properties).some((key) => {
8166
- return FromType24(context, type.properties[key]);
8167
- });
8168
- }
8169
- function FromRecord7(context, type) {
8170
- return IsCodec(type) || FromType24(context, RecordValue(type));
8171
- }
8172
- function FromRef9(context, type) {
8173
- if (visited.has(type.$ref))
8174
- return false;
8175
- visited.add(type.$ref);
8176
- return IsCodec(type) || guard_exports.HasPropertyKey(context, type.$ref) && FromType24(context, context[type.$ref]);
8177
- }
8178
- function FromTuple9(context, type) {
8179
- return IsCodec(type) || type.items.some((type2) => FromType24(context, type2));
8180
- }
8181
- function FromUnion13(context, type) {
8182
- return IsCodec(type) || type.anyOf.some((type2) => FromType24(context, type2));
8183
- }
8184
- function FromType24(context, type) {
8185
- return IsArray2(type) ? FromArray11(context, type) : IsCyclic(type) ? FromCyclic10(context, type) : IsIntersect(type) ? FromIntersect10(context, type) : IsObject2(type) ? FromObject15(context, type) : IsRecord(type) ? FromRecord7(context, type) : IsRef(type) ? FromRef9(context, type) : IsTuple(type) ? FromTuple9(context, type) : IsUnion(type) ? FromUnion13(context, type) : IsCodec(type);
8186
- }
8187
- var visited = /* @__PURE__ */ new Set();
8188
- function HasCodec(...args) {
8189
- const [context, type] = arguments_exports.Match(args, {
8190
- 2: (context2, type2) => [context2, type2],
8191
- 1: (type2) => [{}, type2]
8192
- });
8193
- visited.clear();
8194
- return FromType24(context, type);
8195
- }
8196
-
8197
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/error.mjs
8198
- var CreateError = class extends Error {
8199
- constructor(type, message) {
8200
- super(message);
8201
- this.type = type;
8202
- }
8203
- };
8204
-
8205
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_default.mjs
8206
- function FromDefault2(_context, schema) {
8207
- return guard_exports.IsFunction(schema.default) ? schema.default(schema) : guard_exports.IsObject(schema.default) ? Clone2(schema.default) : schema.default;
8208
- }
8209
-
8210
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_array.mjs
8211
- function FromArray12(context, type) {
8212
- if (IsUniqueItems(type) && !IsDefault(type))
8213
- throw new CreateError(type, "Arrays with uniqueItems constraints must specify a default annotation");
8214
- const length = IsMinItems(type) ? type.minItems : 0;
8215
- return Array.from({ length }, () => FromType25(context, type.items));
8216
- }
8217
-
8218
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_bigint.mjs
8219
- function FromBigInt7(_context, type) {
8220
- return IsExclusiveMinimum(type) ? BigInt(type.exclusiveMinimum) + BigInt(1) : IsMinimum(type) ? BigInt(type.minimum) : BigInt(0);
8221
- }
8222
-
8223
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_boolean.mjs
8224
- function FromBoolean7(_context, _type) {
8225
- return false;
8226
- }
8227
-
8228
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_constructor.mjs
8229
- function FromConstructor2(context, type) {
8230
- const instanceType = FromType25(context, type.instanceType);
8231
- return class {
8232
- constructor() {
8233
- Object.assign(this, instanceType);
8234
- }
8235
- };
8236
- }
8237
-
8238
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_cyclic.mjs
8239
- function FromCyclic11(context, type) {
8240
- return FromType25({ ...context, ...type.$defs }, Ref(type.$ref));
8241
- }
8242
-
8243
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_enum.mjs
8244
- function FromEnum4(context, type) {
8245
- return FromType25(context, Evaluate(type));
8246
- }
8247
-
8248
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_function.mjs
8249
- function FromFunction2(context, type) {
8250
- const returnType = FromType25(context, type.returnType);
8251
- return () => returnType;
8252
- }
8253
-
8254
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_integer.mjs
8255
- function FromInteger2(_context, type) {
8256
- return IsExclusiveMinimum(type) && guard_exports.IsNumber(type.exclusiveMinimum) ? type.exclusiveMinimum + 1 : IsMinimum(type) ? type.minimum : 0;
8257
- }
8258
-
8259
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_intersect.mjs
8260
- function FromIntersect11(context, type) {
8261
- const instantiated = Instantiate(context, type);
8262
- const evaluated = Evaluate(instantiated);
8263
- return FromType25(context, evaluated);
8264
- }
8265
-
8266
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_literal.mjs
8267
- function FromLiteral7(_context, type) {
8268
- return type.const;
8269
- }
8270
-
8271
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_never.mjs
8272
- function FromNever(_context, type) {
8273
- throw new CreateError(type, "Cannot create TNever types");
8274
- }
8275
-
8276
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_null.mjs
8277
- function FromNull3(_context, _type) {
8278
- return null;
8279
- }
8280
-
8281
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_number.mjs
8282
- function FromNumber6(_context, type) {
8283
- return IsExclusiveMinimum(type) && guard_exports.IsNumber(type.exclusiveMinimum) ? type.exclusiveMinimum + 1 : IsMinimum(type) ? type.minimum : 0;
8284
- }
8285
-
8286
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_object.mjs
8287
- function FromObject16(context, type) {
8288
- const required = guard_exports.IsUndefined(type.required) ? [] : type.required;
8289
- return required.reduce((result, key) => {
8290
- return { ...result, [key]: FromType25(context, type.properties[key]) };
8291
- }, {});
8292
- }
8293
-
8294
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_record.mjs
8295
- function FromRecord8(_context, type) {
8296
- if (IsMinProperties(type) && !IsDefault(type))
8297
- throw new CreateError(type, "Record with the minProperties constraint must have a default annotation");
8298
- return {};
8299
- }
8300
-
8301
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_ref.mjs
8302
- function FromRef10(context, type) {
8303
- return guard_exports.HasPropertyKey(context, type.$ref) ? FromType25(context, context[type.$ref]) : (() => {
8304
- throw new CreateError(type, "Unable to deref Ref");
8305
- })();
8306
- }
8307
-
8308
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_string.mjs
8309
- function FromString8(_context, type) {
8310
- const needsDefault = (IsPattern(type) || IsFormat(type)) && !IsDefault(type);
8311
- if (needsDefault)
8312
- throw Error("Strings with format or pattern constraints must specify default");
8313
- const minLength = IsMinLength3(type) ? type.minLength : 0;
8314
- return "".padEnd(minLength);
8315
- }
8316
-
8317
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_symbol.mjs
8318
- function FromSymbol2(_context, _type) {
8319
- return /* @__PURE__ */ Symbol();
8320
- }
8321
-
8322
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_template_literal.mjs
8323
- function FromTemplateLiteral5(context, type) {
8324
- const decoded = TemplateLiteralDecode(type.pattern);
8325
- if (IsString3(decoded))
8326
- throw new CreateError(type, "Unable to create TemplateLiteral due to infinite type expansion");
8327
- return FromType25(context, decoded);
8328
- }
8329
-
8330
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_tuple.mjs
8331
- function FromTuple10(context, type) {
8332
- return Array.from({ length: type.minItems }, (_, i) => FromType25(context, type.items[i]));
8333
- }
8334
-
8335
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_undefined.mjs
8336
- function FromUndefined3(_context, _type) {
8337
- return void 0;
8338
- }
8339
-
8340
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_union.mjs
8341
- function FromUnion14(context, type) {
8342
- if (guard_exports.IsEqual(type.anyOf.length, 0)) {
8343
- throw Error("Unable to create Union with no variants");
8344
- }
8345
- return FromType25(context, type.anyOf[0]);
8346
- }
8347
-
8348
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_void.mjs
8349
- function FromVoid2(_context, _type) {
8350
- return void 0;
8351
- }
8352
-
8353
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/from_type.mjs
8354
- function FromType25(context, type) {
8355
- return (
8356
- // -----------------------------------------------------
8357
- // Default
8358
- // -----------------------------------------------------
8359
- IsDefault(type) ? FromDefault2(context, type) : (
8360
- // -----------------------------------------------------
8361
- // Types
8362
- // -----------------------------------------------------
8363
- IsArray2(type) ? FromArray12(context, type) : IsBigInt2(type) ? FromBigInt7(context, type) : IsBoolean3(type) ? FromBoolean7(context, type) : IsConstructor2(type) ? FromConstructor2(context, type) : IsCyclic(type) ? FromCyclic11(context, type) : IsEnum(type) ? FromEnum4(context, type) : IsFunction2(type) ? FromFunction2(context, type) : IsInteger2(type) ? FromInteger2(context, type) : IsIntersect(type) ? FromIntersect11(context, type) : IsLiteral(type) ? FromLiteral7(context, type) : IsNever(type) ? FromNever(context, type) : IsNull2(type) ? FromNull3(context, type) : IsNumber3(type) ? FromNumber6(context, type) : IsObject2(type) ? FromObject16(context, type) : IsRecord(type) ? FromRecord8(context, type) : IsRef(type) ? FromRef10(context, type) : IsString3(type) ? FromString8(context, type) : IsSymbol2(type) ? FromSymbol2(context, type) : IsTemplateLiteral(type) ? FromTemplateLiteral5(context, type) : IsTuple(type) ? FromTuple10(context, type) : IsUndefined2(type) ? FromUndefined3(context, type) : IsUnion(type) ? FromUnion14(context, type) : IsVoid(type) ? FromVoid2(context, type) : void 0
8364
- )
8365
- );
8366
- }
8367
-
8368
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/create/create.mjs
8369
- function Create2(...args) {
8370
- const [context, type] = arguments_exports.Match(args, {
8371
- 2: (context2, type2) => [context2, type2],
8372
- 1: (type2) => [{}, type2]
8373
- });
8374
- return FromType25(context, type);
8375
- }
8376
-
8377
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/equal/equal.mjs
8378
- function Equal(left, right) {
8379
- return guard_exports.IsDeepEqual(left, right);
8380
- }
8381
-
8382
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/hash/hash.mjs
8383
- function Hash2(value) {
8384
- return hash_exports.Hash(value);
8385
- }
8386
8159
 
8387
8160
  // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/parse/parse.mjs
8388
8161
  var ParseError = class extends AssertError {
@@ -8390,7 +8163,7 @@ var ParseError = class extends AssertError {
8390
8163
  super("Parse", value, errors);
8391
8164
  }
8392
8165
  };
8393
- function Assert4(context, type, value) {
8166
+ function Assert3(context, type, value) {
8394
8167
  if (!Check2(context, type, value))
8395
8168
  throw new ParseError(value, Errors2(context, type, value));
8396
8169
  return value;
@@ -8400,107 +8173,8 @@ var Parser = Pipeline([
8400
8173
  (context, type, value) => Default(context, type, value),
8401
8174
  (context, type, value) => Convert(context, type, value),
8402
8175
  (context, type, value) => Clean(context, type, value),
8403
- (context, type, value) => Assert4(context, type, value)
8176
+ (context, type, value) => Assert3(context, type, value)
8404
8177
  ]);
8405
- function Parse(...args) {
8406
- const [context, type, value] = arguments_exports.Match(args, {
8407
- 3: (context2, type2, value2) => [context2, type2, value2],
8408
- 2: (type2, value2) => [{}, type2, value2]
8409
- });
8410
- const checked = Check2(context, type, value);
8411
- if (checked)
8412
- return value;
8413
- if (settings_exports.Get().correctiveParse)
8414
- return Parser(context, type, value);
8415
- throw new ParseError(value, Errors2(context, type, value));
8416
- }
8417
-
8418
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/delta/diff.mjs
8419
- function CreateUpdate(path, value) {
8420
- return { type: "update", path, value };
8421
- }
8422
- function CreateInsert(path, value) {
8423
- return { type: "insert", path, value };
8424
- }
8425
- function CreateDelete(path) {
8426
- return { type: "delete", path };
8427
- }
8428
- function AssertCanDiffObject(value) {
8429
- if (guard_exports.IsObject(value) && guard_exports.IsEqual(guard_exports.Symbols(value).length, 0))
8430
- return;
8431
- throw new Error("Cannot create diffs for objects with symbols keys");
8432
- }
8433
- function* FromObject17(path, left, right) {
8434
- if (!guard_exports.IsObject(right) || guard_exports.IsArray(right))
8435
- return yield CreateUpdate(path, right);
8436
- AssertCanDiffObject(left);
8437
- AssertCanDiffObject(right);
8438
- const leftKeys = guard_exports.Keys(left);
8439
- const rightKeys = guard_exports.Keys(right);
8440
- for (const key of rightKeys) {
8441
- if (guard_exports.HasPropertyKey(left, key))
8442
- continue;
8443
- if (guard_exports.IsUnsafePropertyKey(key))
8444
- continue;
8445
- yield CreateInsert(`${path}/${key}`, right[key]);
8446
- }
8447
- for (const key of leftKeys) {
8448
- if (!guard_exports.HasPropertyKey(right, key))
8449
- continue;
8450
- if (guard_exports.IsUnsafePropertyKey(key))
8451
- continue;
8452
- if (Equal(left, right))
8453
- continue;
8454
- yield* FromValue4(`${path}/${key}`, left[key], right[key]);
8455
- }
8456
- for (const key of leftKeys) {
8457
- if (guard_exports.HasPropertyKey(right, key))
8458
- continue;
8459
- if (guard_exports.IsUnsafePropertyKey(key))
8460
- continue;
8461
- yield CreateDelete(`${path}/${key}`);
8462
- }
8463
- }
8464
- function* FromArray13(path, left, right) {
8465
- if (!guard_exports.IsArray(right))
8466
- return yield CreateUpdate(path, right);
8467
- for (let i = 0; i < Math.min(left.length, right.length); i++) {
8468
- yield* FromValue4(`${path}/${i}`, left[i], right[i]);
8469
- }
8470
- for (let i = 0; i < right.length; i++) {
8471
- if (i < left.length)
8472
- continue;
8473
- yield CreateInsert(`${path}/${i}`, right[i]);
8474
- }
8475
- for (let i = left.length - 1; i >= 0; i--) {
8476
- if (i < right.length)
8477
- continue;
8478
- yield CreateDelete(`${path}/${i}`);
8479
- }
8480
- }
8481
- function* FromTypedArray2(path, left, right) {
8482
- const typeLeft = globalThis.Object.getPrototypeOf(left).constructor.name;
8483
- const typeRight = globalThis.Object.getPrototypeOf(right).constructor.name;
8484
- const predicate = globals_exports.IsTypeArray(right) && guard_exports.IsEqual(left.length, right.length) && guard_exports.IsEqual(typeLeft, typeRight);
8485
- if (predicate) {
8486
- for (let index = 0; index < Math.min(left.length, right.length); index++) {
8487
- yield* FromValue4(`${path}/${index}`, left[index], right[index]);
8488
- }
8489
- } else {
8490
- return yield CreateUpdate(path, right);
8491
- }
8492
- }
8493
- function* FromUnknown(path, left, right) {
8494
- if (left === right)
8495
- return;
8496
- yield CreateUpdate(path, right);
8497
- }
8498
- function* FromValue4(path, left, right) {
8499
- return globals_exports.IsTypeArray(left) ? yield* FromTypedArray2(path, left, right) : guard_exports.IsArray(left) ? yield* FromArray13(path, left, right) : guard_exports.IsObject(left) ? yield* FromObject17(path, left, right) : yield* FromUnknown(path, left, right);
8500
- }
8501
- function Diff(current, next) {
8502
- return [...FromValue4("", current, next)];
8503
- }
8504
8178
 
8505
8179
  // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/delta/edit.mjs
8506
8180
  var Insert2 = _Object_({
@@ -8519,307 +8193,12 @@ var Delete2 = _Object_({
8519
8193
  });
8520
8194
  var Edit = Union([Insert2, Update2, Delete2]);
8521
8195
 
8522
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/delta/patch.mjs
8523
- function IsRoot(edits) {
8524
- return edits.length > 0 && edits[0].path === "" && edits[0].type === "update";
8525
- }
8526
- function IsEmpty(edits) {
8527
- return edits.length === 0;
8528
- }
8529
- function Patch(current, edits) {
8530
- if (IsRoot(edits))
8531
- return Clone2(edits[0].value);
8532
- if (IsEmpty(edits))
8533
- return Clone2(current);
8534
- const clone = Clone2(current);
8535
- for (const edit of edits) {
8536
- switch (edit.type) {
8537
- case "insert": {
8538
- pointer_exports.Set(clone, edit.path, edit.value);
8539
- break;
8540
- }
8541
- case "update": {
8542
- pointer_exports.Set(clone, edit.path, edit.value);
8543
- break;
8544
- }
8545
- case "delete": {
8546
- pointer_exports.Delete(clone, edit.path);
8547
- break;
8548
- }
8549
- }
8550
- }
8551
- return clone;
8552
- }
8553
-
8554
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/error.mjs
8555
- var RepairError = class extends Error {
8556
- constructor(context, type, value, message) {
8557
- super(message);
8558
- this.context = context;
8559
- this.type = type;
8560
- this.value = value;
8561
- }
8562
- };
8563
-
8564
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_array.mjs
8565
- function MakeUnique(values) {
8566
- const [hashes, result] = [/* @__PURE__ */ new Set(), []];
8567
- for (const value of values) {
8568
- const hash = Hash2(value);
8569
- if (hashes.has(hash))
8570
- continue;
8571
- hashes.add(hash);
8572
- result.push(value);
8573
- }
8574
- return result;
8575
- }
8576
- function FromArray14(context, type, value) {
8577
- if (Check2(context, type, value))
8578
- return value;
8579
- const created = guard_exports.IsArray(value) ? value : Create2(context, type);
8580
- const minimum = IsMinItems(type) && created.length < type.minItems ? [...created, ...Array.from({ length: type.minItems - created.length }, () => Create2(context, type))] : created;
8581
- const maximum = IsMaxItems(type) && minimum.length > type.maxItems ? minimum.slice(0, type.maxItems) : minimum;
8582
- const repaired = maximum.map((value2) => FromType26(context, type.items, value2));
8583
- if (!IsUniqueItems(type) || IsUniqueItems(type) && !guard_exports.IsEqual(type.uniqueItems, true))
8584
- return repaired;
8585
- const unique = MakeUnique(repaired);
8586
- if (!Check2(context, type, unique))
8587
- throw new RepairError(context, type, value, "Failed to repair Array due to uniqueItems constraint");
8588
- return unique;
8589
- }
8590
-
8591
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_enum.mjs
8592
- function FromEnum5(context, type, value) {
8593
- return FromType26(context, Evaluate(type), value);
8594
- }
8595
-
8596
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_intersect.mjs
8597
- function FromIntersect12(context, type, value) {
8598
- const instantiated = Instantiate(context, type);
8599
- const evaluated = Evaluate(instantiated);
8600
- return FromType26(context, evaluated, value);
8601
- }
8602
-
8603
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_object.mjs
8604
- function FromObject18(context, type, value) {
8605
- if (Check2(context, type, value))
8606
- return value;
8607
- if (!guard_exports.IsObjectNotArray(value))
8608
- return Create2(context, type);
8609
- const required = new Set(guard_exports.IsUndefined(type.required) ? [] : type.required);
8610
- const result = {};
8611
- for (const [key, schema] of guard_exports.Entries(type.properties)) {
8612
- if (!required.has(key) && guard_exports.IsUndefined(value[key]))
8613
- continue;
8614
- result[key] = key in value ? FromType26(context, schema, value[key]) : Create2(context, schema);
8615
- }
8616
- const evaluatedKeys = guard_exports.Keys(type.properties);
8617
- if (IsAdditionalProperties(type) && guard_exports.IsObject(type.additionalProperties)) {
8618
- for (const key of guard_exports.Keys(value)) {
8619
- if (evaluatedKeys.includes(key))
8620
- continue;
8621
- result[key] = FromType26(context, type.additionalProperties, value[key]);
8622
- }
8623
- }
8624
- return result;
8625
- }
8626
-
8627
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_record.mjs
8628
- function FromRecord9(context, type, value) {
8629
- if (Check2(context, type, value))
8630
- return value;
8631
- if (guard_exports.IsNull(value) || !guard_exports.IsObject(value) || guard_exports.IsArray(value))
8632
- return Create2(context, type);
8633
- const recordKey = new RegExp(RecordPattern(type));
8634
- const recordValue = RecordValue(type);
8635
- const evaluatedKeys = /* @__PURE__ */ new Set();
8636
- const result = {};
8637
- for (const [key, value_] of guard_exports.Entries(value)) {
8638
- if (!recordKey.test(key))
8639
- continue;
8640
- result[key] = FromType26(context, recordValue, value_);
8641
- evaluatedKeys.add(key);
8642
- }
8643
- if (IsAdditionalProperties(type)) {
8644
- for (const key of guard_exports.Keys(value)) {
8645
- if (evaluatedKeys.has(key))
8646
- continue;
8647
- result[key] = FromType26(context, type.additionalProperties, value[key]);
8648
- }
8649
- }
8650
- return result;
8651
- }
8652
-
8653
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_ref.mjs
8654
- function FromRef11(context, type, value) {
8655
- return guard_exports.HasPropertyKey(context, type.$ref) ? FromType26(context, context[type.$ref], value) : (() => {
8656
- throw new RepairError(context, type, value, "Unable to de-reference target type");
8657
- })();
8658
- }
8659
-
8660
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_template_literal.mjs
8661
- function FromTemplateLiteral6(context, type, value) {
8662
- const decoded = TemplateLiteralDecode(type.pattern);
8663
- return FromType26(context, decoded, value);
8664
- }
8665
-
8666
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_tuple.mjs
8667
- function FromTuple11(context, schema, value) {
8668
- if (Check2(context, schema, value))
8669
- return value;
8670
- if (!guard_exports.IsArray(value))
8671
- return Create2(context, schema);
8672
- return schema.items.map((schema2, index) => FromType26(context, schema2, value[index]));
8673
- }
8674
-
8675
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/shared/union_score_select.mjs
8676
- function Deref(context, type, value) {
8677
- return IsRef(type) ? guard_exports.HasPropertyKey(context, type.$ref) ? Deref(context, context[type.$ref], value) : (() => {
8678
- throw new Error("Unable to Deref target");
8679
- })() : type;
8680
- }
8681
- function ScoreVariant(context, type, value) {
8682
- if (!(IsObject2(type) && guard_exports.IsObject(value)))
8683
- return 0;
8684
- const keys = guard_exports.Keys(value);
8685
- const entries = guard_exports.Entries(type.properties);
8686
- return entries.reduce((result, [key, schema]) => {
8687
- const literal = IsLiteral(schema) && guard_exports.IsEqual(schema.const, value[key]) ? 100 : 0;
8688
- const checks = Check2(context, schema, value[key]) ? 10 : 0;
8689
- const exists = keys.includes(key) ? 1 : 0;
8690
- return result + (literal + checks + exists);
8691
- }, 0);
8692
- }
8693
- function UnionScoreSelect(context, type, value) {
8694
- const schemas = type.anyOf.map((schema) => Deref(context, schema, value));
8695
- let [select, best] = [schemas[0], 0];
8696
- for (const schema of schemas) {
8697
- const score = ScoreVariant(context, schema, value);
8698
- if (score > best) {
8699
- select = schema;
8700
- best = score;
8701
- }
8702
- }
8703
- return select;
8704
- }
8705
-
8706
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_union.mjs
8707
- function RepairUnion(context, type, value) {
8708
- const union = Union(Flatten(type.anyOf));
8709
- const schema = UnionScoreSelect(context, union, value);
8710
- return FromType26(context, schema, value);
8711
- }
8712
- function FromUnion15(context, type, value) {
8713
- if (Check2(context, type, value))
8714
- return Clone2(value);
8715
- if (IsDefault(type))
8716
- return Create2(context, type);
8717
- return RepairUnion(context, type, value);
8718
- }
8719
-
8720
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_unknown.mjs
8721
- function FromUnknown2(context, type, value) {
8722
- if (Check2(context, type, value))
8723
- return value;
8724
- const converted = Convert(context, type, value);
8725
- if (Check2(context, type, converted))
8726
- return converted;
8727
- return Create2(context, type);
8728
- }
8729
-
8730
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/from_type.mjs
8731
- function AssertRepairableValue(context, type, value) {
8732
- const unsupported = globals_exports.IsDate(value) || globals_exports.IsMap(value) || globals_exports.IsSet(value) || globals_exports.IsTypeArray(value) || guard_exports.IsConstructor(value) || guard_exports.IsFunction(value);
8733
- if (unsupported) {
8734
- throw new RepairError(context, type, value, "Value is not repairable");
8735
- }
8736
- }
8737
- function AssertRepairableType(context, type, value) {
8738
- const unsupported = IsConstructor2(type) || IsFunction2(type) || IsNever(type);
8739
- if (unsupported) {
8740
- throw new RepairError(context, type, value, "Type is not repairable");
8741
- }
8742
- }
8743
- function CreateWhenUndefined(context, type, value) {
8744
- return guard_exports.IsUndefined(value) && !IsUndefined2(type) ? Create2(context, type) : value;
8745
- }
8746
- function FinalizeRepair(context, type, repaired) {
8747
- return IsRefine(type) ? Check2(context, type, repaired) ? repaired : Create2(context, type) : repaired;
8748
- }
8749
- function FromType26(context, type, value) {
8750
- AssertRepairableValue(context, type, value);
8751
- AssertRepairableType(context, type, value);
8752
- const candidate = CreateWhenUndefined(context, type, value);
8753
- const repaired = IsArray2(type) ? FromArray14(context, type, candidate) : IsEnum(type) ? FromEnum5(context, type, candidate) : IsIntersect(type) ? FromIntersect12(context, type, candidate) : IsObject2(type) ? FromObject18(context, type, candidate) : IsRecord(type) ? FromRecord9(context, type, candidate) : IsRef(type) ? FromRef11(context, type, candidate) : IsTemplateLiteral(type) ? FromTemplateLiteral6(context, type, candidate) : IsTuple(type) ? FromTuple11(context, type, candidate) : IsUnion(type) ? FromUnion15(context, type, candidate) : FromUnknown2(context, type, candidate);
8754
- return FinalizeRepair(context, type, repaired);
8755
- }
8756
-
8757
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/repair/repair.mjs
8758
- function Repair(...args) {
8759
- const [context, type, value] = arguments_exports.Match(args, {
8760
- 3: (context2, type2, value2) => [context2, type2, value2],
8761
- 2: (type2, value2) => [{}, type2, value2]
8762
- });
8763
- const repaired = FromType26(context, type, value);
8764
- Assert(context, type, repaired);
8765
- return repaired;
8766
- }
8767
-
8768
- // node_modules/.pnpm/typebox@1.3.27/node_modules/typebox/build/value/value.mjs
8769
- var value_exports = {};
8770
- __export(value_exports, {
8771
- Assert: () => Assert,
8772
- Check: () => Check2,
8773
- Clean: () => Clean,
8774
- Clone: () => Clone2,
8775
- Convert: () => Convert,
8776
- Create: () => Create2,
8777
- Decode: () => Decode10,
8778
- Default: () => Default,
8779
- Diff: () => Diff,
8780
- Encode: () => Encode10,
8781
- Equal: () => Equal,
8782
- Errors: () => Errors2,
8783
- HasCodec: () => HasCodec,
8784
- Hash: () => Hash2,
8785
- Parse: () => Parse,
8786
- Patch: () => Patch,
8787
- Pointer: () => pointer_exports,
8788
- Repair: () => Repair
8789
- });
8790
-
8791
8196
  // src/codemode/protocol.ts
8792
8197
  var MEMORY_LIMIT_BYTES = 2 * 1024 ** 3;
8793
8198
  var outputItemSchema = typebox_exports.Union([
8794
8199
  typebox_exports.Object({ type: typebox_exports.Literal("text"), text: typebox_exports.String() }),
8795
8200
  typebox_exports.Object({ type: typebox_exports.Literal("image"), data: typebox_exports.String(), mimeType: typebox_exports.String() })
8796
8201
  ]);
8797
- var toolDeclSchema = typebox_exports.Object({
8798
- name: typebox_exports.String(),
8799
- description: typebox_exports.Optional(typebox_exports.String()),
8800
- /** 工具的 structuredSchema(TypeBox schema):脚本侧据此渲染 call() 的返回类型。 */
8801
- structuredSchema: typebox_exports.Optional(typebox_exports.Unknown())
8802
- });
8803
- var startSchema = typebox_exports.Object({
8804
- t: typebox_exports.Literal("start"),
8805
- code: typebox_exports.String(),
8806
- tools: typebox_exports.Array(toolDeclSchema),
8807
- store: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
8808
- });
8809
- var resultSchema = typebox_exports.Union([
8810
- typebox_exports.Object({
8811
- t: typebox_exports.Literal("result"),
8812
- id: typebox_exports.Number(),
8813
- ok: typebox_exports.Literal(true),
8814
- value: typebox_exports.Unknown()
8815
- }),
8816
- typebox_exports.Object({
8817
- t: typebox_exports.Literal("result"),
8818
- id: typebox_exports.Number(),
8819
- ok: typebox_exports.Literal(false),
8820
- error: typebox_exports.String()
8821
- })
8822
- ]);
8823
8202
  var callSchema = typebox_exports.Object({
8824
8203
  t: typebox_exports.Literal("call"),
8825
8204
  id: typebox_exports.Number(),
@@ -8854,18 +8233,7 @@ var doneSchema = typebox_exports.Union([
8854
8233
  writes: storeWritesSchema
8855
8234
  })
8856
8235
  ]);
8857
- var hostMessageSchema = typebox_exports.Union([startSchema, resultSchema]);
8858
8236
  var workerMessageSchema = typebox_exports.Union([callSchema, outputFrameSchema, doneSchema]);
8859
- function decode(schema, value) {
8860
- if (!value_exports.Check(schema, value)) {
8861
- const preview = JSON.stringify(value).slice(0, 200);
8862
- return { ok: false, error: `unexpected message shape: ${preview}` };
8863
- }
8864
- return { ok: true, frame: value };
8865
- }
8866
- function decodeHostMessage(value) {
8867
- return decode(hostMessageSchema, value);
8868
- }
8869
8237
 
8870
8238
  // src/codemode/worker.ts
8871
8239
  function discardOutput(memory) {
@@ -8884,6 +8252,19 @@ function discardOutput(memory) {
8884
8252
  function post(message) {
8885
8253
  parentPort?.postMessage(message);
8886
8254
  }
8255
+ function isResultMessage(value) {
8256
+ return isRecord(value) && value.t === "result" && typeof value.id === "number";
8257
+ }
8258
+ function isStartMessage(value) {
8259
+ return isRecord(value) && value.t === "start";
8260
+ }
8261
+ function previewMessage(value) {
8262
+ try {
8263
+ return JSON.stringify(value).slice(0, 200);
8264
+ } catch {
8265
+ return String(value);
8266
+ }
8267
+ }
8887
8268
  function emptyWrites() {
8888
8269
  return { set: {}, delete: [] };
8889
8270
  }
@@ -8935,6 +8316,7 @@ async function runScript(wasm, start) {
8935
8316
  "bridge",
8936
8317
  (kind, a, b, c) => {
8937
8318
  const stringOr = (value, fallback) => value === void 0 || value.isUndefined ? fallback : value.toString();
8319
+ const numberOr = (value, fallback) => value === void 0 || value.isUndefined ? fallback : value.toNumber();
8938
8320
  switch (kind.toString()) {
8939
8321
  case "call": {
8940
8322
  post({
@@ -8958,6 +8340,20 @@ async function runScript(wasm, start) {
8958
8340
  });
8959
8341
  break;
8960
8342
  }
8343
+ case "sleep": {
8344
+ const id = a.toNumber();
8345
+ const ms = numberOr(b, 0);
8346
+ setTimeout(() => {
8347
+ try {
8348
+ vm.withScope(() => {
8349
+ vm.callFunction(timerDone, api, vm.newNumber(id)).dispose();
8350
+ });
8351
+ } catch {
8352
+ }
8353
+ drain();
8354
+ }, ms);
8355
+ break;
8356
+ }
8961
8357
  case "done": {
8962
8358
  const writes = c === void 0 || c.isUndefined ? emptyWrites() : parseWrites(c.toString());
8963
8359
  if (a.toBoolean()) {
@@ -9001,6 +8397,7 @@ async function runScript(wasm, start) {
9001
8397
  )
9002
8398
  );
9003
8399
  const settle = api.getProp("settle");
8400
+ const timerDone = api.getProp("timerDone");
9004
8401
  const run = api.getProp("run");
9005
8402
  const stalled = api.getProp("stalled");
9006
8403
  const drain = () => {
@@ -9008,19 +8405,26 @@ async function runScript(wasm, start) {
9008
8405
  vm.callFunction(stalled, api).dispose();
9009
8406
  };
9010
8407
  port.on("message", (value) => {
9011
- const message = decodeHostMessage(value);
9012
- if (!message.ok || message.frame.t !== "result") {
8408
+ if (!isResultMessage(value)) {
8409
+ post({
8410
+ t: "done",
8411
+ ok: false,
8412
+ error: {
8413
+ kind: "sandbox",
8414
+ message: `codemode worker: unexpected host message: ${previewMessage(value)}`
8415
+ },
8416
+ writes: emptyWrites()
8417
+ });
9013
8418
  return;
9014
8419
  }
9015
- const result = message.frame;
9016
8420
  try {
9017
8421
  vm.withScope(() => {
9018
8422
  vm.callFunction(
9019
8423
  settle,
9020
8424
  api,
9021
- vm.newNumber(result.id),
9022
- result.ok ? vm.true : vm.false,
9023
- result.ok ? result.value === void 0 ? vm.undefined : vm.newString(JSON.stringify(result.value)) : vm.newString(result.error)
8425
+ vm.newNumber(value.id),
8426
+ value.ok ? vm.true : vm.false,
8427
+ value.ok ? value.value === void 0 ? vm.undefined : vm.newString(JSON.stringify(value.value)) : vm.newString(value.error)
9024
8428
  );
9025
8429
  });
9026
8430
  } catch {
@@ -9060,8 +8464,7 @@ function main() {
9060
8464
  }
9061
8465
  const { wasm } = workerData;
9062
8466
  port.once("message", (value) => {
9063
- const message = decodeHostMessage(value);
9064
- if (!message.ok || message.frame.t !== "start") {
8467
+ if (!isStartMessage(value)) {
9065
8468
  post({
9066
8469
  t: "done",
9067
8470
  ok: false,
@@ -9070,7 +8473,7 @@ function main() {
9070
8473
  });
9071
8474
  return;
9072
8475
  }
9073
- void runScript(wasm, message.frame);
8476
+ void runScript(wasm, value);
9074
8477
  });
9075
8478
  }
9076
8479
  main();
@@ -13,9 +13,9 @@ import { parentPort, workerData } from "node:worker_threads";
13
13
 
14
14
  import { JSException, type JSValueHandle, MAX_STACK_SIZE, QuickJS } from "quickjs-wasi";
15
15
 
16
+ import { isRecord } from "../lib/narrow.js";
16
17
  import { PRELUDE_SOURCE } from "./prelude.js";
17
18
  import {
18
- decodeHostMessage,
19
19
  type HostMessage,
20
20
  MEMORY_LIMIT_BYTES,
21
21
  type ScriptError,
@@ -46,6 +46,28 @@ function post(message: WorkerMessage): void {
46
46
  parentPort?.postMessage(message);
47
47
  }
48
48
 
49
+ /**
50
+ * 主线程发来的消息由主线程自己构造,形状由 `HostMessage` 类型约束,所以这里只做分派、
51
+ * 不重复 typebox 校验;但形状对不上就是内部 bug,得报错而不是静默丢弃——静默丢弃只会
52
+ * 让脚本永远等在 pending 上,症状比故障本身难查得多。
53
+ */
54
+ function isResultMessage(value: unknown): value is Extract<HostMessage, { t: "result" }> {
55
+ return isRecord(value) && value.t === "result" && typeof value.id === "number";
56
+ }
57
+
58
+ function isStartMessage(value: unknown): value is Extract<HostMessage, { t: "start" }> {
59
+ return isRecord(value) && value.t === "start";
60
+ }
61
+
62
+ /** 畸形消息的预览:截断成一行,序列化不了(循环引用、undefined 等)就退化成 String()。 */
63
+ function previewMessage(value: unknown): string {
64
+ try {
65
+ return JSON.stringify(value).slice(0, 200);
66
+ } catch {
67
+ return String(value);
68
+ }
69
+ }
70
+
49
71
  function emptyWrites(): StoreWrites {
50
72
  return { set: {}, delete: [] };
51
73
  }
@@ -111,6 +133,8 @@ async function runScript(wasm: object, start: Extract<HostMessage, { t: "start"
111
133
  ) => {
112
134
  const stringOr = (value: JSValueHandle | undefined, fallback: string): string =>
113
135
  value === undefined || value.isUndefined ? fallback : value.toString();
136
+ const numberOr = (value: JSValueHandle | undefined, fallback: number): number =>
137
+ value === undefined || value.isUndefined ? fallback : value.toNumber();
114
138
  switch (kind.toString()) {
115
139
  case "call": {
116
140
  post({
@@ -138,6 +162,22 @@ async function runScript(wasm: object, start: Extract<HostMessage, { t: "start"
138
162
  });
139
163
  break;
140
164
  }
165
+ case "sleep": {
166
+ // 用 worker 线程自己的定时器:不经主线程,也没有消息往返
167
+ const id = a.toNumber();
168
+ const ms = numberOr(b, 0);
169
+ setTimeout(() => {
170
+ try {
171
+ vm.withScope(() => {
172
+ vm.callFunction(timerDone, api, vm.newNumber(id)).dispose();
173
+ });
174
+ } catch {
175
+ /* VM 已中止 */
176
+ }
177
+ drain();
178
+ }, ms);
179
+ break;
180
+ }
141
181
  case "done": {
142
182
  const writes =
143
183
  c === undefined || c.isUndefined ? emptyWrites() : parseWrites(c.toString());
@@ -186,6 +226,7 @@ async function runScript(wasm: object, start: Extract<HostMessage, { t: "start"
186
226
  ),
187
227
  );
188
228
  const settle = api.getProp("settle");
229
+ const timerDone = api.getProp("timerDone");
189
230
  const run = api.getProp("run");
190
231
  const stalled = api.getProp("stalled");
191
232
 
@@ -196,23 +237,31 @@ async function runScript(wasm: object, start: Extract<HostMessage, { t: "start"
196
237
  };
197
238
 
198
239
  port.on("message", (value: unknown) => {
199
- const message = decodeHostMessage(value);
200
- if (!message.ok || message.frame.t !== "result") {
240
+ if (!isResultMessage(value)) {
241
+ // 主线程只会发 result:对不上就是宿主自己的 bug,报出去而不是静默让脚本挂住
242
+ post({
243
+ t: "done",
244
+ ok: false,
245
+ error: {
246
+ kind: "sandbox",
247
+ message: `codemode worker: unexpected host message: ${previewMessage(value)}`,
248
+ },
249
+ writes: emptyWrites(),
250
+ });
201
251
  return;
202
252
  }
203
- const result = message.frame;
204
253
  try {
205
254
  vm.withScope(() => {
206
255
  vm.callFunction(
207
256
  settle,
208
257
  api,
209
- vm.newNumber(result.id),
210
- result.ok ? vm.true : vm.false,
211
- result.ok
212
- ? result.value === undefined
258
+ vm.newNumber(value.id),
259
+ value.ok ? vm.true : vm.false,
260
+ value.ok
261
+ ? value.value === undefined
213
262
  ? vm.undefined
214
- : vm.newString(JSON.stringify(result.value))
215
- : vm.newString(result.error),
263
+ : vm.newString(JSON.stringify(value.value))
264
+ : vm.newString(value.error),
216
265
  );
217
266
  });
218
267
  } catch {
@@ -256,8 +305,7 @@ function main(): void {
256
305
  const { wasm } = workerData as WorkerBootstrap;
257
306
  // 主线程先发 start;worker 收到后才实例化 VM(wasm 已在主线程编译好)
258
307
  port.once("message", (value: unknown) => {
259
- const message = decodeHostMessage(value);
260
- if (!message.ok || message.frame.t !== "start") {
308
+ if (!isStartMessage(value)) {
261
309
  post({
262
310
  t: "done",
263
311
  ok: false,
@@ -266,7 +314,7 @@ function main(): void {
266
314
  });
267
315
  return;
268
316
  }
269
- void runScript(wasm, message.frame);
317
+ void runScript(wasm, value);
270
318
  });
271
319
  }
272
320