paseo-plugin-zcode-provider 0.4.4 → 0.5.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.
Files changed (51) hide show
  1. package/NOTICE.md +2 -2
  2. package/README.md +14 -12
  3. package/client/account.tsx +13 -22
  4. package/index.server.ts +1 -3
  5. package/package.json +4 -4
  6. package/paseo-plugin.json +1 -1
  7. package/server/build-info.ts +1 -1
  8. package/server/diagnostics.ts +4 -1
  9. package/server/discovery/manifest.ts +2 -2
  10. package/server/errors.ts +1 -0
  11. package/server/host/bridge.ts +3 -0
  12. package/server/mapping.ts +23 -6
  13. package/server/provider-status.ts +3 -3
  14. package/server/provider.ts +16 -1
  15. package/server/runtime/pins.ts +3 -3
  16. package/server/session.ts +49 -13
  17. package/server/turn-failure.ts +6 -1
  18. package/server/usage.ts +1 -3
  19. package/server/vendor/zcode/NOTICE.md +1 -1
  20. package/server/vendor/zcode/packages/rpc/src/channelClient.ts +18 -3
  21. package/server/vendor/zcode/packages/rpc/src/channelServer.ts +32 -12
  22. package/server/vendor/zcode/packages/rpc/src/channels.shared.ts +8 -1
  23. package/server/vendor/zcode/packages/rpc/src/serialization.ts +9 -3
  24. package/server/vendor/zcode/packages/shared/src/browser-use/command-metadata.ts +2 -0
  25. package/server/vendor/zcode/packages/shared/src/browser-use/commands.ts +2 -0
  26. package/server/vendor/zcode/packages/shared/src/browser-use/result.ts +4 -0
  27. package/server/vendor/zcode/packages/shared/src/gen-ui/contract.ts +246 -0
  28. package/server/vendor/zcode/packages/shared/src/gen-ui/tweakProtocol.ts +143 -0
  29. package/server/vendor/zcode/packages/shared/src/{localTtft.ts → local-ttft/contract.ts} +56 -1
  30. package/server/vendor/zcode/packages/shared/src/mcp-apps/contract.ts +8 -0
  31. package/server/vendor/zcode/packages/shared/src/official-mcp-auth.ts +8 -0
  32. package/server/vendor/zcode/packages/shared/src/protocol.ts +2 -0
  33. package/server/vendor/zcode/packages/shared/src/request-security-edition/verification-policy.ts +9 -1
  34. package/server/vendor/zcode/packages/shared/src/runtimeEnv.ts +10 -0
  35. package/server/vendor/zcode/packages/shared/src/server-remote.ts +2 -0
  36. package/server/vendor/zcode/packages/shared/src/source-server/compatibility.ts +11 -0
  37. package/server/vendor/zcode/packages/shared/src/source-server/contracts.ts +21 -1
  38. package/server/vendor/zcode/packages/shared/src/source-server/errorCodes.ts +27 -9
  39. package/server/vendor/zcode/packages/shared/src/subagent-profile.ts +5 -0
  40. package/server/vendor/zcode/packages/shared/src/validationAppSettings.ts +1 -0
  41. package/server/vendor/zcode/packages/shared/src/zcode-protocol/index.ts +164 -11
  42. package/server/vendor/zcode/packages/shared/src/zcode-protocol-legacy-types.ts +1 -0
  43. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/apply.ts +4 -2
  44. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/command.ts +11 -7
  45. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/delta.ts +2 -0
  46. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/input-intent.ts +2 -0
  47. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/rows.ts +19 -1
  48. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/snapshot.ts +11 -0
  49. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/transport.ts +20 -1
  50. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-row-meta.ts +8 -0
  51. package/server/vendor/zcode/provenance.json +71 -63
@@ -99,6 +99,7 @@ export class ChannelClient implements IChannelClient, IDisposable {
99
99
  "taskId",
100
100
  "traceId",
101
101
  "retryable",
102
+ "profileId",
102
103
  ] as const;
103
104
  for (const key of passthroughKeys) {
104
105
  const value = response.data[key];
@@ -170,7 +171,18 @@ export class ChannelClient implements IChannelClient, IDisposable {
170
171
  });
171
172
 
172
173
  this.handlers.set(id, (response) => {
173
- emitter.fire((response as { data: any }).data);
174
+ if (response.type === ResponseType.EventFire) {
175
+ emitter.fire(response.data);
176
+ } else if (response.type === ResponseType.EventError) {
177
+ // 订阅失败必须结束其监听器,不能把错误对象写入终端等正常事件流,也不能继续保留旧请求。
178
+ this.handlers.delete(id);
179
+ this.activeRequests.delete(emitter);
180
+ emitter.dispose();
181
+ const error = new Error(response.data.message);
182
+ error.name = response.data.name;
183
+ if (response.data.stack) error.stack = response.data.stack.join("\n");
184
+ console.error(`RPC event subscription failed: ${channelName}.${name}`, error);
185
+ }
174
186
  });
175
187
 
176
188
  return emitter.event;
@@ -208,9 +220,11 @@ export class ChannelClient implements IChannelClient, IDisposable {
208
220
  }
209
221
 
210
222
  private onBuffer(message: VSBuffer): void {
223
+ // 修复原因:同一 protocol 上还有反向 ChannelServer(host ↔ 远端 WebSocket 两端都是),对方发来的
224
+ // 请求也会到这里。原来先解码消息体再判断类型,每条请求都被完整解码两次,大请求(例如数据同步的
225
+ // 归档)白白多花一倍 CPU。修法:先读消息头,只解码属于本端的响应体。
211
226
  const reader = new BufferReader(message);
212
227
  const header = deserialize(reader);
213
- const body = deserialize(reader);
214
228
  const type = header[0] as ResponseType;
215
229
 
216
230
  switch (type) {
@@ -220,11 +234,12 @@ export class ChannelClient implements IChannelClient, IDisposable {
220
234
  case ResponseType.PromiseSuccess:
221
235
  case ResponseType.PromiseError:
222
236
  case ResponseType.EventFire:
237
+ case ResponseType.EventError:
223
238
  case ResponseType.PromiseErrorObj:
224
239
  this.onResponse({
225
240
  type,
226
241
  id: header[1],
227
- data: body,
242
+ data: deserialize(reader),
228
243
  } as IRawResponse);
229
244
  return;
230
245
  }
@@ -48,6 +48,7 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
48
48
  case ResponseType.PromiseSuccess:
49
49
  case ResponseType.PromiseError:
50
50
  case ResponseType.EventFire:
51
+ case ResponseType.EventError:
51
52
  case ResponseType.PromiseErrorObj:
52
53
  this.send([response.type, response.id], response.data);
53
54
  return;
@@ -66,9 +67,10 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
66
67
  }
67
68
 
68
69
  private onRawMessage(message: VSBuffer): void {
70
+ // 修复原因:同一 protocol 上还有反向 ChannelClient,对方发来的响应也会到这里;原来先解码消息体
71
+ // 再判断类型,每条响应都被完整解码两次。修法:先读消息头,只解码属于本端的请求体。
69
72
  const reader = new BufferReader(message);
70
73
  const header = deserialize(reader);
71
- const body = deserialize(reader);
72
74
  const type = header[0] as RequestType;
73
75
 
74
76
  switch (type) {
@@ -78,7 +80,7 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
78
80
  id: header[1],
79
81
  channelName: header[2],
80
82
  name: header[3],
81
- arg: body,
83
+ arg: deserialize(reader),
82
84
  });
83
85
  return;
84
86
  case RequestType.EventListen:
@@ -87,7 +89,7 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
87
89
  id: header[1],
88
90
  channelName: header[2],
89
91
  name: header[3],
90
- arg: body,
92
+ arg: deserialize(reader),
91
93
  });
92
94
  return;
93
95
  case RequestType.PromiseCancel:
@@ -147,6 +149,7 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
147
149
  taskId?: unknown;
148
150
  traceId?: unknown;
149
151
  retryable?: unknown;
152
+ profileId?: unknown;
150
153
  } = {
151
154
  message: error.message,
152
155
  name: error.name,
@@ -164,6 +167,9 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
164
167
  "taskId",
165
168
  "traceId",
166
169
  "retryable",
170
+ // Bug 原因:Host 的远程等待点(需要安装/升级、补凭据)用 profileId 指明实际操作线路;
171
+ // 旧白名单丢掉它,侧栏项目只能把不含凭据的目标交给向导,确认安装后报“SSH 认证失败”。
172
+ "profileId",
167
173
  ] as const;
168
174
  for (const key of passthroughKeys) {
169
175
  const value = errorRecord[key];
@@ -205,18 +211,32 @@ export class ChannelServer<TContext = string> implements IChannelServer<TContext
205
211
  return;
206
212
  }
207
213
 
208
- const disposable = channel.listen(
209
- this.ctx,
210
- request.name,
211
- request.arg,
212
- )((data) => {
214
+ try {
215
+ const disposable = channel.listen(
216
+ this.ctx,
217
+ request.name,
218
+ request.arg,
219
+ )((data) => {
220
+ this.sendResponse({
221
+ id: request.id,
222
+ data,
223
+ type: ResponseType.EventFire,
224
+ });
225
+ });
226
+ this.activeRequests.set(request.id, disposable);
227
+ } catch (error) {
228
+ // 已结束的终端等资源会拒绝迟到订阅;该拒绝属于本次请求,不能逃逸并退出整个 Host。
229
+ // 独立失败帧不会被旧客户端当作业务事件,也不会建立无法释放的活动订阅。
213
230
  this.sendResponse({
214
231
  id: request.id,
215
- data,
216
- type: ResponseType.EventFire,
232
+ type: ResponseType.EventError,
233
+ data: {
234
+ name: error instanceof Error ? error.name : "Error",
235
+ message: error instanceof Error ? error.message : String(error),
236
+ ...(error instanceof Error && error.stack ? { stack: error.stack.split("\n") } : {}),
237
+ },
217
238
  });
218
- });
219
- this.activeRequests.set(request.id, disposable);
239
+ }
220
240
  }
221
241
 
222
242
  private disposeActiveRequest(id: number): void {
@@ -28,6 +28,7 @@ export const enum ResponseType {
28
28
  PromiseError = 202,
29
29
  PromiseErrorObj = 203,
30
30
  EventFire = 204,
31
+ EventError = 205,
31
32
  }
32
33
 
33
34
  export type IRawResponse =
@@ -50,10 +51,16 @@ export type IRawResponse =
50
51
  taskId?: unknown;
51
52
  traceId?: unknown;
52
53
  retryable?: unknown;
54
+ profileId?: unknown;
53
55
  };
54
56
  }
55
57
  | { type: ResponseType.PromiseErrorObj; id: number; data: any }
56
- | { type: ResponseType.EventFire; id: number; data: any };
58
+ | { type: ResponseType.EventFire; id: number; data: any }
59
+ | {
60
+ type: ResponseType.EventError;
61
+ id: number;
62
+ data: { name: string; message: string; stack?: string[] };
63
+ };
57
64
 
58
65
  export type IHandler = (response: IRawResponse) => void;
59
66
 
@@ -217,11 +217,17 @@ export function deserialize(reader: IReader): any {
217
217
  }
218
218
  }
219
219
 
220
- function encodeRpcJsonValue(_key: string, value: unknown): unknown {
221
- if (value instanceof Uint8Array) {
220
+ function encodeRpcJsonValue(this: unknown, key: string, value: unknown): unknown {
221
+ // Bug 根因:JSON.stringify 先调用 toJSON 再调用 replacer。Node Buffer(Uint8Array 子类,技能 / 插件
222
+ // 归档都是 gzip 产出的 Buffer)到这里已被展开成 {type:"Buffer",data:[...]},不进 base64 标记:体积约 3.6 倍,
223
+ // 每一跳解码 1500 万个数字的数组(15MB 归档单跳十几秒,渲染进程卡住),约 28MB 以上的插件还超出远端
224
+ // WebSocket 单条消息 100MiB 上限;接收端拿到的是普通对象,归档大小检查读不到 byteLength。
225
+ // 修法:按 holder 上的原值判断是否为二进制。
226
+ const original = (this as Record<string, unknown>)[key];
227
+ if (original instanceof Uint8Array) {
222
228
  return {
223
229
  [RPC_NESTED_UINT8_ARRAY_MARKER]: true,
224
- [RPC_NESTED_UINT8_ARRAY_BASE64_KEY]: bytesToBase64(value),
230
+ [RPC_NESTED_UINT8_ARRAY_BASE64_KEY]: bytesToBase64(original),
225
231
  };
226
232
  }
227
233
  return value;
@@ -114,6 +114,8 @@ export const browserCommandMethodSchema = z.enum([
114
114
  "markDeliverable",
115
115
  "markHandoff",
116
116
  "nameSession",
117
+ "openScope",
118
+ "releaseScope",
117
119
  "turnEnded",
118
120
  "closeSession",
119
121
  "cancelRequest",
@@ -577,6 +577,8 @@ export const browserCommandSchema = z.discriminatedUnion("method", [
577
577
  deliverable: z.boolean().optional(),
578
578
  })
579
579
  .strict(),
580
+ z.object({ method: z.literal("openScope") }).strict(),
581
+ z.object({ method: z.literal("releaseScope"), closeTabs: z.boolean().optional() }).strict(),
580
582
  z.object({ method: z.literal("turnEnded"), turnId: z.string().min(1).optional() }).strict(),
581
583
  // closeTabs:连同该 session 名下的 tab 一起关(含已释放回该 session 的)。只给永不回来认领的
582
584
  // session 用——dwf 子代理(docs/browser-use/2026-07-14-browser-tab-conversation-isolation-spec.md §2.3)。
@@ -95,6 +95,10 @@ export type BrowserRecordingJob = z.infer<typeof browserRecordingJobSchema>;
95
95
  export const browserCommandResultSchema = z
96
96
  .object({
97
97
  ok: z.boolean(),
98
+ scope: z
99
+ .object({ id: z.string().min(1), state: z.enum(["open", "released", "absent", "rejected"]) })
100
+ .strict()
101
+ .optional(),
98
102
  state: browserPageStateSchema.optional(),
99
103
  snapshot: browserSnapshotSchema.optional(),
100
104
  image: z
@@ -0,0 +1,246 @@
1
+ import { z } from "zod";
2
+ export * from "./tweakProtocol.js";
3
+
4
+ export const GEN_UI_HTML_MAX_BYTES = 5_000_000;
5
+ export const GEN_UI_STATE_MAX_BYTES = 16 * 1024;
6
+ export const GEN_UI_STATE_MAX_ENTRIES = 100;
7
+ export const GEN_UI_CONTEXT_MAX_BYTES = 64 * 1024;
8
+ export const GEN_UI_GLOBALS_EVENT = "zcode:set_globals";
9
+ export const GEN_UI_STATE_CONTEXT_KEY = "zcode/genUiState";
10
+ export const GEN_UI_TWEAK_CONTEXT_KEY = "zcode/genUiTweaks";
11
+ export const GEN_UI_STYLE_CONTEXT_KEY = "zcode/genUiStyles";
12
+ export const genUiStyleVariablesSchema = z.record(
13
+ z.string().regex(/^--gen-ui-[a-z-]+$/),
14
+ z.string(),
15
+ );
16
+ export const GEN_UI_STATE_METHOD = "zcode/gen-ui/state";
17
+ export const GEN_UI_FOLLOW_UP_METHOD = "zcode/gen-ui/follow-up";
18
+ export const GEN_UI_TWEAK_METHOD = "zcode/gen-ui/tweak";
19
+ export const GEN_UI_PRESENTATION_METHOD = "zcode/gen-ui/presentation";
20
+ export const GEN_UI_STATIC_DOMAINS = [
21
+ "cdnjs.cloudflare.com",
22
+ "esm.sh",
23
+ "cdn.jsdelivr.net",
24
+ "unpkg.com",
25
+ "fonts.googleapis.com",
26
+ "fonts.gstatic.com",
27
+ "fonts.bunny.net",
28
+ // 自有 CDN:visualize/gen-ui 页面引用 zcode.z.ai 上的图片等静态资源(与上面公共 CDN 同走 resourceDomains,
29
+ // 会同时进 img/script/style/media/font 五类 src,可控性高于公共 CDN)
30
+ "zcode.z.ai",
31
+ ] as const;
32
+
33
+ /** This is a wire-format check. The executor owns normalization and filesystem authorization. */
34
+ export const genUiPathSchema = z
35
+ .string()
36
+ .min(1)
37
+ .max(4096)
38
+ .refine((path) => {
39
+ if (path.includes("\0") || /[\r\n]/u.test(path)) return false;
40
+ const segments = path.split(/[\\/]/u);
41
+ return (
42
+ /^(?:\/|[A-Za-z]:[\\/]|\\\\)/u.test(path) &&
43
+ !segments.includes("..") &&
44
+ /^[a-z0-9]+(?:-[a-z0-9]+)*\.html$/u.test(segments.at(-1) ?? "")
45
+ );
46
+ }, "Expected an absolute executor path to a lowercase-hyphenated HTML file");
47
+ export const genUiReferenceSchema = z
48
+ .object({
49
+ path: genUiPathSchema,
50
+ title: z.string().max(250).optional(),
51
+ mode: z.enum(["wide"]).optional(),
52
+ })
53
+ .strict();
54
+ export type GenUiReference = z.infer<typeof genUiReferenceSchema>;
55
+
56
+ export const genUiScopeSchema = z
57
+ .object({
58
+ workspacePath: z.string().min(1).max(4096),
59
+ workspaceIdentity: z.string().max(4096).optional(),
60
+ sessionId: z.string().min(1).max(512),
61
+ })
62
+ .strict();
63
+ export type GenUiScope = z.infer<typeof genUiScopeSchema>;
64
+ export const genUiStateTargetSchema = genUiScopeSchema.extend({ path: genUiPathSchema });
65
+ export type GenUiStateTarget = z.infer<typeof genUiStateTargetSchema>;
66
+
67
+ function serializeJson(value: unknown): string {
68
+ return JSON.stringify(value, (_key, item: unknown) => {
69
+ if (
70
+ typeof item === "undefined" ||
71
+ typeof item === "function" ||
72
+ typeof item === "symbol" ||
73
+ typeof item === "bigint" ||
74
+ (typeof item === "number" && !Number.isFinite(item))
75
+ ) {
76
+ throw new Error("Widget state must contain JSON values only");
77
+ }
78
+ return item;
79
+ });
80
+ }
81
+ export const genUiWidgetStateSchema = z
82
+ .object({
83
+ modelContent: z.unknown().default(null),
84
+ privateContent: z.unknown().default(null),
85
+ })
86
+ .strict()
87
+ .transform((state, context) => {
88
+ try {
89
+ const serialized = serializeJson(state);
90
+ if (new TextEncoder().encode(serialized).byteLength > GEN_UI_STATE_MAX_BYTES) {
91
+ throw new Error("Widget state exceeds 16 KiB");
92
+ }
93
+ return JSON.parse(serialized) as { modelContent: unknown; privateContent: unknown };
94
+ } catch (error) {
95
+ context.addIssue({
96
+ code: "custom",
97
+ message: error instanceof Error ? error.message : "Invalid widget state",
98
+ });
99
+ return z.NEVER;
100
+ }
101
+ });
102
+ export type GenUiWidgetState = z.infer<typeof genUiWidgetStateSchema>;
103
+ export const genUiFollowUpSchema = z
104
+ .object({
105
+ prompt: z
106
+ .string()
107
+ .trim()
108
+ .min(1)
109
+ .max(64 * 1024),
110
+ title: z.string().max(250).optional(),
111
+ })
112
+ .strict();
113
+
114
+ export interface GenUiDocument {
115
+ path: string;
116
+ html: string;
117
+ }
118
+ const controlBase = {
119
+ id: z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),
120
+ label: z.string().min(1).max(120),
121
+ reference: z
122
+ .string()
123
+ .regex(/^[\w./:@$#-]{1,160}$/u)
124
+ .optional(),
125
+ };
126
+ export const genUiTweakControlSchema = z.discriminatedUnion("type", [
127
+ z
128
+ .object({
129
+ ...controlBase,
130
+ type: z.literal("slider"),
131
+ value: z.number().finite(),
132
+ min: z.number().finite(),
133
+ max: z.number().finite(),
134
+ step: z.number().positive().optional(),
135
+ unit: z.string().max(24).optional(),
136
+ })
137
+ .strict(),
138
+ z
139
+ .object({
140
+ ...controlBase,
141
+ type: z.literal("color"),
142
+ value: z.string().regex(/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i),
143
+ })
144
+ .strict(),
145
+ z.object({ ...controlBase, type: z.literal("toggle"), value: z.boolean() }).strict(),
146
+ z
147
+ .object({
148
+ ...controlBase,
149
+ type: z.literal("select"),
150
+ value: z.string().max(120),
151
+ options: z
152
+ .array(
153
+ z.union([
154
+ z.string().min(1).max(120),
155
+ z.object({ label: z.string().min(1).max(120), value: z.string().max(120) }).strict(),
156
+ ]),
157
+ )
158
+ .min(1)
159
+ .max(12),
160
+ })
161
+ .strict(),
162
+ ]);
163
+ export const genUiTweakSchema = z
164
+ .object({
165
+ title: z.string().min(1).max(120),
166
+ controls: z.array(genUiTweakControlSchema).min(1).max(12),
167
+ })
168
+ .strict()
169
+ .superRefine((input, ctx) => {
170
+ const ids = new Set<string>();
171
+ for (const control of input.controls) {
172
+ if (
173
+ ids.has(control.id) ||
174
+ (control.type === "slider" &&
175
+ (control.min >= control.max ||
176
+ control.value < control.min ||
177
+ control.value > control.max)) ||
178
+ (control.type === "select" &&
179
+ !control.options.some(
180
+ (option) => (typeof option === "string" ? option : option.value) === control.value,
181
+ ))
182
+ )
183
+ ctx.addIssue({ code: "custom", message: "Invalid or duplicate tweak control" });
184
+ ids.add(control.id);
185
+ }
186
+ });
187
+ export type GenUiTweak = z.infer<typeof genUiTweakSchema>;
188
+ export type GenUiTweakValues = Record<string, string | number | boolean>;
189
+ export interface GenUiStateEntry {
190
+ path: string;
191
+ state: GenUiWidgetState;
192
+ }
193
+ export interface GenUiStateChange {
194
+ target: GenUiStateTarget;
195
+ state: GenUiWidgetState | null;
196
+ }
197
+ export function buildGenUiScopeKey(scope: GenUiScope): string {
198
+ return JSON.stringify([scope.workspaceIdentity?.trim() || scope.workspacePath, scope.sessionId]);
199
+ }
200
+ export function buildGenUiStateKey(target: GenUiStateTarget): string {
201
+ return JSON.stringify([buildGenUiScopeKey(target), target.path]);
202
+ }
203
+ export function selectGenUiModelContext(entries: readonly GenUiStateEntry[]): GenUiModelContext {
204
+ const selected: GenUiModelContext = [];
205
+ for (const entry of [...entries]
206
+ .sort((a, b) => a.path.localeCompare(b.path))
207
+ .slice(0, GEN_UI_STATE_MAX_ENTRIES)) {
208
+ const parsed = genUiWidgetStateSchema.safeParse(entry.state);
209
+ if (!parsed.success || parsed.data.modelContent === null) continue;
210
+ const next = { path: entry.path, state: parsed.data.modelContent };
211
+ if (
212
+ new TextEncoder().encode(JSON.stringify([...selected, next])).length >
213
+ GEN_UI_CONTEXT_MAX_BYTES
214
+ )
215
+ break;
216
+ selected.push(next);
217
+ }
218
+ return genUiModelContextSchema.parse(selected);
219
+ }
220
+
221
+ export const genUiModelContextSchema = z
222
+ .array(z.object({ path: genUiPathSchema, state: z.unknown() }).strict())
223
+ .max(GEN_UI_STATE_MAX_ENTRIES)
224
+ .transform((entries, context) => {
225
+ try {
226
+ const serialized = serializeJson(entries);
227
+ if (
228
+ new TextEncoder().encode(serialized).byteLength > GEN_UI_CONTEXT_MAX_BYTES ||
229
+ entries.some(
230
+ (entry) =>
231
+ new TextEncoder().encode(serializeJson(entry.state)).byteLength >
232
+ GEN_UI_STATE_MAX_BYTES,
233
+ )
234
+ ) {
235
+ throw new Error("Gen UI model context exceeds its size limit");
236
+ }
237
+ return JSON.parse(serialized) as Array<{ path: string; state: unknown }>;
238
+ } catch (error) {
239
+ context.addIssue({
240
+ code: "custom",
241
+ message: error instanceof Error ? error.message : "Invalid Gen UI model context",
242
+ });
243
+ return z.NEVER;
244
+ }
245
+ });
246
+ export type GenUiModelContext = z.infer<typeof genUiModelContextSchema>;
@@ -0,0 +1,143 @@
1
+ import { z } from "zod";
2
+
3
+ const value = z.union([z.string(), z.number().finite(), z.boolean()]);
4
+ const base = {
5
+ callback: z.string().min(1).max(128),
6
+ label: z.string().min(1).max(120),
7
+ reference: z.string().max(160).optional(),
8
+ };
9
+ export const genUiAnnotationControlSchema = z.discriminatedUnion("type", [
10
+ z
11
+ .object({
12
+ ...base,
13
+ type: z.literal("range"),
14
+ currentValue: z.number().finite(),
15
+ min: z.number().finite(),
16
+ max: z.number().finite(),
17
+ step: z.number().positive(),
18
+ })
19
+ .strict(),
20
+ z
21
+ .object({
22
+ ...base,
23
+ type: z.literal("color"),
24
+ currentValue: z.string().regex(/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i),
25
+ })
26
+ .strict(),
27
+ z.object({ ...base, type: z.literal("toggle"), currentValue: z.boolean() }).strict(),
28
+ z
29
+ .object({
30
+ ...base,
31
+ type: z.literal("select"),
32
+ currentValue: z.string().max(120),
33
+ options: z
34
+ .array(z.object({ label: z.string().min(1).max(120), value: z.string().max(120) }).strict())
35
+ .min(1)
36
+ .max(12),
37
+ })
38
+ .strict(),
39
+ ]);
40
+ export type GenUiAnnotationControl = z.infer<typeof genUiAnnotationControlSchema>;
41
+ export function isGenUiAnnotationValue(
42
+ control: GenUiAnnotationControl,
43
+ candidate: unknown,
44
+ ): candidate is string | number | boolean {
45
+ switch (control.type) {
46
+ case "range":
47
+ return (
48
+ typeof candidate === "number" &&
49
+ Number.isFinite(candidate) &&
50
+ candidate >= control.min &&
51
+ candidate <= control.max
52
+ );
53
+ case "color":
54
+ return (
55
+ typeof candidate === "string" &&
56
+ /^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i.test(candidate)
57
+ );
58
+ case "toggle":
59
+ return typeof candidate === "boolean";
60
+ case "select":
61
+ return (
62
+ typeof candidate === "string" &&
63
+ control.options.some((option) => option.value === candidate)
64
+ );
65
+ }
66
+ }
67
+ const annotationControls = z
68
+ .object({
69
+ controlsMode: z.literal("replace"),
70
+ controls: z.array(genUiAnnotationControlSchema).min(1).max(12),
71
+ })
72
+ .strict()
73
+ .superRefine((input, ctx) => {
74
+ const callbacks = new Set(input.controls.map((control) => control.callback));
75
+ if (
76
+ callbacks.size !== input.controls.length ||
77
+ input.controls.some((control) => !isGenUiAnnotationValue(control, control.currentValue)) ||
78
+ JSON.stringify(input).length > 16384
79
+ ) {
80
+ ctx.addIssue({ code: "custom", message: "Invalid annotation controls" });
81
+ }
82
+ });
83
+ const target = z
84
+ .object({
85
+ id: z.string().min(1).max(128),
86
+ label: z.string().min(1).max(80),
87
+ selector: z.string().max(1024),
88
+ tagName: z.string().min(1).max(120),
89
+ rect: z
90
+ .object({
91
+ x: z.number().finite(),
92
+ y: z.number().finite(),
93
+ width: z.number().nonnegative(),
94
+ height: z.number().nonnegative(),
95
+ })
96
+ .strict(),
97
+ })
98
+ .strict();
99
+ const registration = {
100
+ registrationId: z.string().min(1).max(128),
101
+ annotationControls,
102
+ targets: z.array(target).length(1),
103
+ };
104
+ export const genUiTweakMessageSchema = z.discriminatedUnion("type", [
105
+ z.object({ type: z.literal("register"), ...registration }).strict(),
106
+ z.object({ type: z.literal("update"), ...registration }).strict(),
107
+ z.object({ type: z.literal("dispose"), registrationId: registration.registrationId }).strict(),
108
+ z
109
+ .object({
110
+ type: z.literal("select"),
111
+ registrationId: registration.registrationId,
112
+ targetId: target.shape.id,
113
+ })
114
+ .strict(),
115
+ z.object({ type: z.literal("escape") }).strict(),
116
+ ]);
117
+ export type GenUiTweakMessage = z.infer<typeof genUiTweakMessageSchema>;
118
+ export const genUiTweakResultSchema = z
119
+ .object({ annotationControls: annotationControls.optional() })
120
+ .strict();
121
+ export type GenUiTweakResult = z.infer<typeof genUiTweakResultSchema>;
122
+ export const genUiTweakAnnotationSchema = z
123
+ .object({
124
+ active: z.boolean(),
125
+ selection: z
126
+ .object({ registrationId: registration.registrationId, targetId: target.shape.id })
127
+ .nullable(),
128
+ changes: z
129
+ .array(
130
+ z
131
+ .object({
132
+ registrationId: registration.registrationId,
133
+ targetId: target.shape.id,
134
+ annotationControlChanges: z
135
+ .array(z.object({ callback: base.callback, previousValue: value, value }).strict())
136
+ .max(12),
137
+ })
138
+ .strict(),
139
+ )
140
+ .max(64),
141
+ })
142
+ .strict();
143
+ export type GenUiTweakAnnotation = z.infer<typeof genUiTweakAnnotationSchema>;