@dev-anywhere/proxy 0.8.0 → 0.9.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 (54) hide show
  1. package/README.md +7 -5
  2. package/THIRD_PARTY_NOTICES.md +30 -0
  3. package/assets/scrcpy/scrcpy-server-v4.1 +0 -0
  4. package/dist/{chunk-43VZTEDR.js → chunk-57LA2LWY.js} +2 -2
  5. package/dist/chunk-C5RUR5MY.js +426 -0
  6. package/dist/chunk-C5RUR5MY.js.map +1 -0
  7. package/dist/{chunk-AQPTQ44T.js → chunk-DZ4GXMP5.js} +2 -2
  8. package/dist/{chunk-AQPTQ44T.js.map → chunk-DZ4GXMP5.js.map} +1 -1
  9. package/dist/chunk-HLN3NOD2.js +451 -0
  10. package/dist/chunk-HLN3NOD2.js.map +1 -0
  11. package/dist/chunk-K72MFCMC.js +304 -0
  12. package/dist/chunk-K72MFCMC.js.map +1 -0
  13. package/dist/{chunk-OWPHJ5LA.js → chunk-KGTYU4WO.js} +2 -2
  14. package/dist/chunk-RN3KQK6E.js +2745 -0
  15. package/dist/chunk-RN3KQK6E.js.map +1 -0
  16. package/dist/{chunk-MSIZBFLV.js → chunk-SEMZ7GW7.js} +3 -3
  17. package/dist/{chunk-HIZNGFB5.js → chunk-WRU3BXW6.js} +10 -1
  18. package/dist/chunk-WRU3BXW6.js.map +1 -0
  19. package/dist/{chunk-T2RI7YUO.js → chunk-YM74AWYC.js} +54 -14
  20. package/dist/chunk-YM74AWYC.js.map +1 -0
  21. package/dist/{chunk-FJHCP2HS.js → chunk-ZNMJH7BK.js} +2 -2
  22. package/dist/index.js +148 -96
  23. package/dist/index.js.map +1 -1
  24. package/dist/{quick-tunnel-C2WILO6I.js → quick-tunnel-RI62V2RH.js} +17 -89
  25. package/dist/quick-tunnel-RI62V2RH.js.map +1 -0
  26. package/dist/{relay-token-V6EA4HPM.js → relay-token-ZP3PAZD2.js} +4 -4
  27. package/dist/serve.js +10630 -2166
  28. package/dist/serve.js.map +1 -1
  29. package/dist/session-worker.js +105 -31
  30. package/dist/session-worker.js.map +1 -1
  31. package/dist/{terminal-NWKJTN2R.js → terminal-AHMO45YN.js} +166 -124
  32. package/dist/terminal-AHMO45YN.js.map +1 -0
  33. package/dist/terminal-worker.js +83 -43
  34. package/dist/terminal-worker.js.map +1 -1
  35. package/dist/update-runner.js +2 -2
  36. package/licenses/Apache-2.0.txt +204 -0
  37. package/licenses/BSD-3-Clause.txt +29 -0
  38. package/licenses/Boost-1.0.txt +23 -0
  39. package/package.json +8 -4
  40. package/dist/chunk-2FVY2JAS.js +0 -123
  41. package/dist/chunk-2FVY2JAS.js.map +0 -1
  42. package/dist/chunk-HIZNGFB5.js.map +0 -1
  43. package/dist/chunk-JU6MVCCD.js +0 -1644
  44. package/dist/chunk-JU6MVCCD.js.map +0 -1
  45. package/dist/chunk-T2RI7YUO.js.map +0 -1
  46. package/dist/chunk-UHJRVS65.js +0 -49
  47. package/dist/chunk-UHJRVS65.js.map +0 -1
  48. package/dist/quick-tunnel-C2WILO6I.js.map +0 -1
  49. package/dist/terminal-NWKJTN2R.js.map +0 -1
  50. /package/dist/{chunk-43VZTEDR.js.map → chunk-57LA2LWY.js.map} +0 -0
  51. /package/dist/{chunk-OWPHJ5LA.js.map → chunk-KGTYU4WO.js.map} +0 -0
  52. /package/dist/{chunk-MSIZBFLV.js.map → chunk-SEMZ7GW7.js.map} +0 -0
  53. /package/dist/{chunk-FJHCP2HS.js.map → chunk-ZNMJH7BK.js.map} +0 -0
  54. /package/dist/{relay-token-V6EA4HPM.js.map → relay-token-ZP3PAZD2.js.map} +0 -0
@@ -0,0 +1,2745 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../../packages/shared/dist/schemas/envelope.js
4
+ import { z as z6 } from "zod";
5
+
6
+ // ../../packages/shared/dist/constants/envelope.js
7
+ var MESSAGE_ENVELOPE_VERSION = "1.0";
8
+
9
+ // ../../packages/shared/dist/schemas/id.js
10
+ import { z } from "zod";
11
+ var MAX_ID_LENGTH = 256;
12
+ var IdSchema = z.string().min(1).max(MAX_ID_LENGTH);
13
+
14
+ // ../../packages/shared/dist/schemas/chat.js
15
+ import { z as z2 } from "zod";
16
+ var UserInputPayloadSchema = z2.object({
17
+ text: z2.string().min(1),
18
+ messageId: z2.string().min(1).optional()
19
+ }).strict();
20
+ var AssistantMessagePayloadSchema = z2.object({
21
+ turnId: z2.string().min(1).max(256),
22
+ revision: z2.number().int().positive(),
23
+ text: z2.string(),
24
+ status: z2.enum(["streaming", "completed"])
25
+ }).strict();
26
+ var ThinkingPayloadSchema = z2.object({
27
+ text: z2.string()
28
+ }).strict();
29
+
30
+ // ../../packages/shared/dist/schemas/tool.js
31
+ import { z as z3 } from "zod";
32
+ var ApprovalOptionKindSchema = z3.enum([
33
+ "allow_once",
34
+ "allow_always",
35
+ "reject_once",
36
+ "reject_always"
37
+ ]);
38
+ var ApprovalOptionSchema = z3.object({
39
+ optionId: IdSchema,
40
+ name: z3.string().min(1),
41
+ kind: ApprovalOptionKindSchema
42
+ }).strict();
43
+ var ToolUseRequestPayloadSchema = z3.object({
44
+ toolName: z3.string(),
45
+ toolId: IdSchema,
46
+ parameters: z3.record(z3.string(), z3.unknown()),
47
+ options: z3.array(ApprovalOptionSchema).optional()
48
+ }).strict();
49
+ var ToolApprovePayloadSchema = z3.object({
50
+ toolId: IdSchema,
51
+ whitelistTool: z3.boolean().optional(),
52
+ optionId: IdSchema.optional()
53
+ });
54
+ var ToolDenyPayloadSchema = z3.object({
55
+ toolId: IdSchema,
56
+ reason: z3.string().optional(),
57
+ optionId: IdSchema.optional()
58
+ });
59
+ var ToolResultPayloadSchema = z3.object({
60
+ toolId: IdSchema,
61
+ result: z3.unknown(),
62
+ isError: z3.boolean()
63
+ }).strict();
64
+
65
+ // ../../packages/shared/dist/schemas/session.js
66
+ import { z as z4 } from "zod";
67
+
68
+ // ../../packages/shared/dist/constants/enums.js
69
+ var providerValues = ["claude", "codex", "kimi"];
70
+ var ptyOwnerValues = ["local-terminal", "proxy-hosted"];
71
+ var sessionModeValues = ["pty", "json"];
72
+
73
+ // ../../packages/shared/dist/constants/pty.js
74
+ var PtySemanticState = {
75
+ WORKING: "working",
76
+ TURN_COMPLETE: "turn_complete",
77
+ APPROVAL_WAIT: "approval_wait"
78
+ };
79
+ var ptySemanticStateValues = [
80
+ PtySemanticState.WORKING,
81
+ PtySemanticState.TURN_COMPLETE,
82
+ PtySemanticState.APPROVAL_WAIT
83
+ ];
84
+ var PTY_INITIAL_MIN_COLS = 80;
85
+ var PTY_INITIAL_MIN_ROWS = 24;
86
+ var PTY_INITIAL_MAX_COLS = 500;
87
+ var PTY_INITIAL_MAX_ROWS = 200;
88
+
89
+ // ../../packages/shared/dist/schemas/session.js
90
+ var sessionStateValues = [
91
+ "idle",
92
+ "working",
93
+ "compacting",
94
+ "waiting_approval",
95
+ "error",
96
+ "terminated"
97
+ ];
98
+ var agentStatusPhaseValues = [
99
+ "idle",
100
+ "thinking",
101
+ "tool_use",
102
+ "outputting",
103
+ "waiting_permission",
104
+ "error"
105
+ ];
106
+ function createSessionIdentitySchema(commonFields) {
107
+ return z4.union([
108
+ z4.object({
109
+ ...commonFields,
110
+ kind: z4.literal("agent"),
111
+ mode: z4.literal("json"),
112
+ provider: z4.enum(providerValues)
113
+ }).strict(),
114
+ z4.object({
115
+ ...commonFields,
116
+ kind: z4.literal("agent"),
117
+ mode: z4.literal("pty"),
118
+ provider: z4.enum(providerValues),
119
+ ptyOwner: z4.enum(ptyOwnerValues)
120
+ }).strict(),
121
+ z4.object({
122
+ ...commonFields,
123
+ kind: z4.literal("terminal"),
124
+ mode: z4.literal("pty"),
125
+ provider: z4.literal("claude"),
126
+ ptyOwner: z4.literal("local-terminal")
127
+ }).strict()
128
+ ]);
129
+ }
130
+ var SessionInfoSchema = createSessionIdentitySchema({
131
+ sessionId: IdSchema,
132
+ name: z4.string().optional(),
133
+ // cwd 只用于展示完整路径/tooltip,不作为前端路由或权限判断来源。
134
+ cwd: z4.string(),
135
+ // true 表示 name 是用户显式命名,PTY UI 不再让 OSC terminal_title 覆盖它。
136
+ nameLocked: z4.boolean().optional(),
137
+ state: z4.enum(sessionStateValues),
138
+ lastActive: z4.number()
139
+ });
140
+ var SessionListPayloadSchema = z4.object({
141
+ sessions: z4.array(SessionInfoSchema)
142
+ }).strict();
143
+ var SessionStatusPayloadSchema = z4.object({
144
+ sessionId: IdSchema,
145
+ state: z4.enum(sessionStateValues),
146
+ lastActive: z4.number()
147
+ }).strict();
148
+ var PtyStatePayloadSchema = z4.object({
149
+ state: z4.enum(ptySemanticStateValues),
150
+ seq: z4.number().int().nonnegative(),
151
+ title: z4.string().optional(),
152
+ tool: z4.string().optional()
153
+ });
154
+ var AgentStatusPayloadSchema = z4.object({
155
+ provider: z4.enum(providerValues),
156
+ phase: z4.enum(agentStatusPhaseValues),
157
+ seq: z4.number().int().nonnegative(),
158
+ updatedAt: z4.number(),
159
+ toolName: z4.string().optional(),
160
+ toolInput: z4.record(z4.string(), z4.unknown()).optional(),
161
+ permissionRequest: z4.object({
162
+ requestId: IdSchema,
163
+ toolName: z4.string(),
164
+ input: z4.record(z4.string(), z4.unknown())
165
+ }).optional(),
166
+ permissionResolution: z4.object({
167
+ requestId: IdSchema,
168
+ outcome: z4.enum(["allow", "deny"])
169
+ }).optional(),
170
+ summary: z4.string().optional()
171
+ });
172
+
173
+ // ../../packages/shared/dist/schemas/system.js
174
+ import { z as z5 } from "zod";
175
+ var HeartbeatPayloadSchema = z5.object({}).strict();
176
+ var AuthPayloadSchema = z5.object({
177
+ pairingCode: z5.string().optional(),
178
+ token: z5.string().optional()
179
+ }).strict();
180
+ var SyncRequestPayloadSchema = z5.object({
181
+ lastSeq: z5.number().int().nonnegative()
182
+ }).strict();
183
+ var SyncResponsePayloadSchema = z5.object({
184
+ messages: z5.array(z5.record(z5.string(), z5.unknown()))
185
+ }).strict();
186
+
187
+ // ../../packages/shared/dist/schemas/envelope.js
188
+ var BaseEnvelopeFields = {
189
+ seq: z6.number().int().nonnegative(),
190
+ timestamp: z6.number(),
191
+ source: z6.enum(["proxy", "client"]),
192
+ version: z6.literal(MESSAGE_ENVELOPE_VERSION)
193
+ };
194
+ var SessionedEnvelopeFields = {
195
+ ...BaseEnvelopeFields,
196
+ sessionId: IdSchema
197
+ };
198
+ var MessageEnvelopeSchema = z6.discriminatedUnion("type", [
199
+ // chat (3)
200
+ z6.object({
201
+ ...SessionedEnvelopeFields,
202
+ type: z6.literal("user_input"),
203
+ payload: UserInputPayloadSchema
204
+ }).strict(),
205
+ z6.object({
206
+ ...SessionedEnvelopeFields,
207
+ type: z6.literal("assistant_message"),
208
+ payload: AssistantMessagePayloadSchema
209
+ }).strict(),
210
+ z6.object({
211
+ ...SessionedEnvelopeFields,
212
+ type: z6.literal("thinking"),
213
+ payload: ThinkingPayloadSchema
214
+ }).strict(),
215
+ // tool (4): 工具审批决策属于 relay control,不进入会话消息信封。
216
+ // tool_use_request: 审批流请求(proxy → client),toolId 是 approval requestId
217
+ z6.object({
218
+ ...SessionedEnvelopeFields,
219
+ type: z6.literal("tool_use_request"),
220
+ payload: ToolUseRequestPayloadSchema
221
+ }).strict(),
222
+ // tool_result: 工具执行结果(proxy → client),toolId 对应 assistant_tool_use / tool_use_request 的 toolId
223
+ z6.object({
224
+ ...SessionedEnvelopeFields,
225
+ type: z6.literal("tool_result"),
226
+ payload: ToolResultPayloadSchema
227
+ }).strict(),
228
+ // assistant_tool_use: 纯展示型工具调用(proxy → client),区别于 tool_use_request 无审批语义
229
+ // payload 结构复用 ToolUseRequestPayloadSchema;toolId 是 Claude 分配的 tool_use id
230
+ z6.object({
231
+ ...SessionedEnvelopeFields,
232
+ type: z6.literal("assistant_tool_use"),
233
+ payload: ToolUseRequestPayloadSchema
234
+ }).strict(),
235
+ // session (2)
236
+ // session_list 是全局广播 (列出所有 session), 不绑定具体 sessionId, 不携带该字段。
237
+ z6.object({
238
+ ...BaseEnvelopeFields,
239
+ type: z6.literal("session_list"),
240
+ payload: SessionListPayloadSchema
241
+ }).strict(),
242
+ z6.object({
243
+ ...SessionedEnvelopeFields,
244
+ type: z6.literal("session_status"),
245
+ payload: SessionStatusPayloadSchema
246
+ }).strict(),
247
+ // system (5): 心跳 / 认证 / 同步——全局, 无 sessionId
248
+ z6.object({
249
+ ...BaseEnvelopeFields,
250
+ type: z6.literal("heartbeat"),
251
+ payload: HeartbeatPayloadSchema
252
+ }).strict(),
253
+ z6.object({
254
+ ...BaseEnvelopeFields,
255
+ type: z6.literal("auth"),
256
+ payload: AuthPayloadSchema
257
+ }).strict(),
258
+ z6.object({
259
+ ...BaseEnvelopeFields,
260
+ type: z6.literal("sync_request"),
261
+ payload: SyncRequestPayloadSchema
262
+ }).strict(),
263
+ z6.object({
264
+ ...BaseEnvelopeFields,
265
+ type: z6.literal("sync_response"),
266
+ payload: SyncResponsePayloadSchema
267
+ }).strict()
268
+ ]);
269
+
270
+ // ../../packages/shared/dist/builders/index.js
271
+ function buildMessage(type, sessionId, seq, payload, source) {
272
+ const envelope = {
273
+ seq,
274
+ ...sessionId !== null ? { sessionId } : {},
275
+ type,
276
+ payload,
277
+ timestamp: Date.now(),
278
+ source,
279
+ version: MESSAGE_ENVELOPE_VERSION
280
+ };
281
+ return MessageEnvelopeSchema.parse(envelope);
282
+ }
283
+ function serializeControl(msg) {
284
+ return JSON.stringify(msg);
285
+ }
286
+
287
+ // ../../packages/shared/dist/constants/control-errors.js
288
+ var ControlErrorCode = {
289
+ INVALID_PATH: "INVALID_PATH",
290
+ PATH_NOT_FOUND: "PATH_NOT_FOUND",
291
+ PATH_NOT_DIRECTORY: "PATH_NOT_DIRECTORY",
292
+ PATH_ACCESS_DENIED: "PATH_ACCESS_DENIED",
293
+ PROXY_OFFLINE: "PROXY_OFFLINE",
294
+ PROXY_NOT_FOUND: "PROXY_NOT_FOUND",
295
+ PROXY_ONLINE: "PROXY_ONLINE",
296
+ SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
297
+ SESSION_ALREADY_ACTIVE: "SESSION_ALREADY_ACTIVE",
298
+ PROVIDER_UNSUPPORTED: "PROVIDER_UNSUPPORTED",
299
+ APPROVAL_POLICY_UNSUPPORTED: "APPROVAL_POLICY_UNSUPPORTED",
300
+ WORKER_START_FAILED: "WORKER_START_FAILED",
301
+ PROCESS_START_FAILED: "PROCESS_START_FAILED",
302
+ STREAM_CAPACITY_EXCEEDED: "STREAM_CAPACITY_EXCEEDED",
303
+ CONTROL_LEASE_INVALID: "CONTROL_LEASE_INVALID",
304
+ OPERATION_CONFLICT: "OPERATION_CONFLICT",
305
+ RATE_LIMITED: "RATE_LIMITED",
306
+ UNKNOWN: "UNKNOWN"
307
+ };
308
+
309
+ // ../../packages/shared/dist/state-machine.js
310
+ function computeAbsorbingSet(transitions) {
311
+ const absorbing = /* @__PURE__ */ new Set();
312
+ const entries = Object.entries(transitions);
313
+ for (const [s, outs] of entries) {
314
+ if (outs.length === 0)
315
+ absorbing.add(s);
316
+ }
317
+ let changed = true;
318
+ while (changed) {
319
+ changed = false;
320
+ for (const [s, outs] of entries) {
321
+ if (absorbing.has(s))
322
+ continue;
323
+ if (outs.length > 0 && outs.every((t) => absorbing.has(t))) {
324
+ absorbing.add(s);
325
+ changed = true;
326
+ }
327
+ }
328
+ }
329
+ return absorbing;
330
+ }
331
+ function createFSM(def) {
332
+ let state = def.initial;
333
+ const absorbing = computeAbsorbingSet(def.transitions);
334
+ const tryTransitionTo = (to) => {
335
+ const allowed = def.transitions[state];
336
+ if (!allowed?.includes(to)) {
337
+ def.onRejected?.(state, to, absorbing.has(state));
338
+ return false;
339
+ }
340
+ const from = state;
341
+ state = to;
342
+ def.onTransition?.(from, to);
343
+ return true;
344
+ };
345
+ return {
346
+ current: () => state,
347
+ is: (s) => state === s,
348
+ isIn: (ss) => ss.includes(state),
349
+ canTransitionTo: (to) => def.transitions[state]?.includes(to) ?? false,
350
+ transitionTo: (to) => {
351
+ if (!tryTransitionTo(to)) {
352
+ throw new Error(`Invalid FSM transition: ${state} -> ${to}`);
353
+ }
354
+ },
355
+ tryTransitionTo,
356
+ isInAbsorbingState: () => absorbing.has(state)
357
+ };
358
+ }
359
+ function defineFSM(transitions) {
360
+ const absorbing = computeAbsorbingSet(transitions);
361
+ return {
362
+ canTransition: (from, to) => transitions[from]?.includes(to) ?? false,
363
+ isAbsorbing: (state) => absorbing.has(state)
364
+ };
365
+ }
366
+
367
+ // ../../packages/shared/dist/schemas/voice.js
368
+ import { z as z7 } from "zod";
369
+ var voiceProviderValues = ["aliyun-bailian"];
370
+ var voiceRegionValues = ["cn", "intl"];
371
+ var voiceOptionSourceValues = ["official", "custom"];
372
+ var voiceOptionGenderValues = ["male", "female", "unknown"];
373
+ var VoiceProviderConfigSchema = z7.object({
374
+ provider: z7.enum(voiceProviderValues),
375
+ configured: z7.boolean(),
376
+ region: z7.enum(voiceRegionValues),
377
+ asrModel: z7.string().min(1),
378
+ ttsModel: z7.string().min(1),
379
+ ttsVoice: z7.string().min(1),
380
+ turnIdleSeconds: z7.number().int().positive().safe().default(3)
381
+ }).strict();
382
+ var VoiceConfigUpdateSchema = z7.object({
383
+ provider: z7.enum(voiceProviderValues).optional(),
384
+ apiKey: z7.string().min(1).optional(),
385
+ clearApiKey: z7.boolean().optional(),
386
+ region: z7.enum(voiceRegionValues).optional(),
387
+ asrModel: z7.string().min(1).optional(),
388
+ ttsModel: z7.string().min(1).optional(),
389
+ ttsVoice: z7.string().min(1).optional(),
390
+ turnIdleSeconds: z7.number().int().positive().safe().optional()
391
+ }).strict();
392
+ var VoiceOptionSchema = z7.object({
393
+ value: z7.string().min(1),
394
+ label: z7.string().min(1),
395
+ description: z7.string().min(1).optional(),
396
+ gender: z7.enum(voiceOptionGenderValues).optional(),
397
+ age: z7.string().min(1).optional(),
398
+ model: z7.string().min(1).optional(),
399
+ source: z7.enum(voiceOptionSourceValues)
400
+ }).strict();
401
+ var VoiceCapabilitiesSchema = z7.object({
402
+ asrModels: z7.array(VoiceOptionSchema),
403
+ ttsModels: z7.array(VoiceOptionSchema),
404
+ ttsVoices: z7.array(VoiceOptionSchema),
405
+ fetchedAt: z7.number().optional()
406
+ }).strict();
407
+ var VoiceSummaryReasonSchema = z7.enum([
408
+ "code",
409
+ "table",
410
+ "diff",
411
+ "log",
412
+ "stack_trace",
413
+ "long_list",
414
+ "long_text",
415
+ "mixed",
416
+ "approval"
417
+ ]);
418
+
419
+ // ../../packages/shared/dist/schemas/preview-scope.js
420
+ import { z as z8 } from "zod";
421
+ var PreviewScopeSchema = z8.object({
422
+ proxyId: IdSchema,
423
+ bindingId: IdSchema
424
+ }).strict();
425
+
426
+ // ../../packages/shared/dist/schemas/web-preview.js
427
+ import { z as z9 } from "zod";
428
+ var WEB_PREVIEW_PATH_MAX_LENGTH = 4096;
429
+ var WEB_PREVIEW_SOURCE_URL_MAX_LENGTH = 4096;
430
+ var WEB_PREVIEW_PUBLIC_URL_MAX_LENGTH = 65536;
431
+ var WEB_PREVIEW_NAME_MAX_LENGTH = 256;
432
+ var WEB_PREVIEW_ERROR_MAX_LENGTH = 4096;
433
+ var WEB_PREVIEW_HTML_ENTRY_MAX_COUNT = 1e3;
434
+ var WebPreviewNameSchema = z9.string().trim().min(1).max(WEB_PREVIEW_NAME_MAX_LENGTH);
435
+ var tunnelProviderValues = ["cloudflare", "cpolar"];
436
+ var TunnelProviderSchema = z9.enum(tunnelProviderValues);
437
+ var WebPreviewPathSchema = z9.string().min(1).max(WEB_PREVIEW_PATH_MAX_LENGTH);
438
+ function parseUrlSafely(value) {
439
+ try {
440
+ return new URL(value);
441
+ } catch {
442
+ return null;
443
+ }
444
+ }
445
+ var LoopbackHttpUrlSchema = z9.string().min(1).max(WEB_PREVIEW_SOURCE_URL_MAX_LENGTH).url().refine((value) => {
446
+ const url = parseUrlSafely(value);
447
+ if (!url)
448
+ return false;
449
+ if (url.protocol !== "http:" || url.username !== "" || url.password !== "")
450
+ return false;
451
+ return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
452
+ }, "Local preview URL must use http:// with a loopback host and no credentials");
453
+ var PublicPreviewUrlSchema = z9.string().min(1).max(WEB_PREVIEW_PUBLIC_URL_MAX_LENGTH).url().refine((value) => {
454
+ const url = parseUrlSafely(value);
455
+ if (!url)
456
+ return false;
457
+ return url.protocol === "https:" && url.username === "" && url.password === "" && url.port === "";
458
+ }, "Preview public URL must use standard HTTPS without credentials");
459
+ var DNS_LABEL_PATTERN = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
460
+ var CLOUDFLARE_PUBLIC_HOST_PATTERN = new RegExp(`^${DNS_LABEL_PATTERN}\\.trycloudflare\\.com$`, "i");
461
+ var CPOLAR_PUBLIC_HOST_PATTERN = new RegExp(`^(?:${DNS_LABEL_PATTERN}\\.)+cpolar\\.(?:top|cn|io)$`, "i");
462
+ var WebPreviewTunnelSuggestionsSchema = z9.array(z9.string().min(1).max(WEB_PREVIEW_PATH_MAX_LENGTH)).max(32).optional();
463
+ var WebPreviewTunnelStatusSchema = z9.discriminatedUnion("available", [
464
+ z9.object({
465
+ available: z9.literal(true),
466
+ command: z9.string().min(1).max(WEB_PREVIEW_PATH_MAX_LENGTH),
467
+ version: z9.string().min(1).max(256).optional(),
468
+ error: z9.never().optional(),
469
+ suggestions: WebPreviewTunnelSuggestionsSchema
470
+ }).strict(),
471
+ z9.object({
472
+ available: z9.literal(false),
473
+ command: z9.never().optional(),
474
+ version: z9.never().optional(),
475
+ error: z9.string().min(1).max(WEB_PREVIEW_ERROR_MAX_LENGTH),
476
+ suggestions: WebPreviewTunnelSuggestionsSchema
477
+ }).strict()
478
+ ]);
479
+ var WebPreviewCapabilitySchema = z9.object({
480
+ cloudflared: WebPreviewTunnelStatusSchema,
481
+ cpolar: WebPreviewTunnelStatusSchema
482
+ }).strict();
483
+ var WebPreviewSourceInputSchema = z9.discriminatedUnion("kind", [
484
+ z9.object({
485
+ kind: z9.literal("local"),
486
+ url: LoopbackHttpUrlSchema
487
+ }).strict(),
488
+ z9.object({
489
+ kind: z9.literal("static"),
490
+ path: WebPreviewPathSchema,
491
+ entryPath: WebPreviewPathSchema
492
+ }).strict()
493
+ ]);
494
+ var PreviewSourceSchema = z9.discriminatedUnion("kind", [
495
+ z9.object({
496
+ kind: z9.literal("local"),
497
+ url: LoopbackHttpUrlSchema
498
+ }).strict(),
499
+ z9.object({
500
+ kind: z9.literal("static"),
501
+ rootPath: WebPreviewPathSchema,
502
+ entryPath: WebPreviewPathSchema
503
+ }).strict()
504
+ ]);
505
+ var previewStateValues = [
506
+ "starting",
507
+ "ready",
508
+ "disconnected",
509
+ "failed",
510
+ "stopping"
511
+ ];
512
+ var PreviewStateSchema = z9.enum(previewStateValues);
513
+ var PreviewSummaryBaseSchema = z9.object({
514
+ previewId: IdSchema,
515
+ name: WebPreviewNameSchema,
516
+ source: PreviewSourceSchema,
517
+ tunnelProvider: TunnelProviderSchema,
518
+ createdAt: z9.number().int().nonnegative(),
519
+ updatedAt: z9.number().int().nonnegative()
520
+ });
521
+ var PreviewSummaryInactiveShape = {
522
+ publicUrl: z9.never().optional(),
523
+ error: z9.never().optional()
524
+ };
525
+ var PreviewSummarySchema = z9.discriminatedUnion("state", [
526
+ PreviewSummaryBaseSchema.extend({
527
+ state: z9.literal("starting"),
528
+ ...PreviewSummaryInactiveShape
529
+ }).strict(),
530
+ PreviewSummaryBaseSchema.extend({
531
+ state: z9.literal("ready"),
532
+ publicUrl: PublicPreviewUrlSchema,
533
+ error: z9.never().optional()
534
+ }).strict(),
535
+ PreviewSummaryBaseSchema.extend({
536
+ state: z9.literal("disconnected"),
537
+ ...PreviewSummaryInactiveShape
538
+ }).strict(),
539
+ PreviewSummaryBaseSchema.extend({
540
+ state: z9.literal("failed"),
541
+ publicUrl: z9.never().optional(),
542
+ error: z9.string().min(1).max(WEB_PREVIEW_ERROR_MAX_LENGTH)
543
+ }).strict(),
544
+ PreviewSummaryBaseSchema.extend({
545
+ state: z9.literal("stopping"),
546
+ ...PreviewSummaryInactiveShape
547
+ }).strict()
548
+ ]).superRefine((preview, context) => {
549
+ if (preview.state !== "ready")
550
+ return;
551
+ const publicUrl = parseUrlSafely(preview.publicUrl);
552
+ if (!publicUrl)
553
+ return;
554
+ const hostname = publicUrl.hostname;
555
+ const provider = preview.tunnelProvider;
556
+ const valid = provider === "cloudflare" ? CLOUDFLARE_PUBLIC_HOST_PATTERN.test(hostname) : CPOLAR_PUBLIC_HOST_PATTERN.test(hostname);
557
+ if (!valid) {
558
+ context.addIssue({
559
+ code: "custom",
560
+ path: ["publicUrl"],
561
+ message: `Preview public URL hostname does not match tunnel provider ${provider}`
562
+ });
563
+ }
564
+ });
565
+ var PreviewHtmlEntriesSchema = z9.array(WebPreviewPathSchema).max(WEB_PREVIEW_HTML_ENTRY_MAX_COUNT);
566
+
567
+ // ../../packages/shared/dist/schemas/device-preview.js
568
+ import { z as z10 } from "zod";
569
+ var DEVICE_PREVIEW_PATH_MAX_LENGTH = 4096;
570
+ var DEVICE_PREVIEW_TEXT_MAX_LENGTH = 4096;
571
+ var DEVICE_PREVIEW_ERROR_MAX_LENGTH = 4096;
572
+ var DEVICE_PREVIEW_NAME_MAX_LENGTH = 256;
573
+ var DEVICE_PREVIEW_VERSION_MAX_LENGTH = 256;
574
+ var DEVICE_PREVIEW_SCREEN_EDGE_MAX = 16384;
575
+ var DevicePreviewNameSchema = z10.string().trim().min(1).max(DEVICE_PREVIEW_NAME_MAX_LENGTH);
576
+ var devicePreviewStreamFormatValues = ["jpeg", "h264_annex_b"];
577
+ var DevicePreviewStreamFormatSchema = z10.enum(devicePreviewStreamFormatValues);
578
+ var devicePreviewPlatformValues = ["ios", "android"];
579
+ var DevicePreviewPlatformSchema = z10.enum(devicePreviewPlatformValues);
580
+ var DevicePreviewToolSuggestionsSchema = z10.array(z10.string().min(1).max(DEVICE_PREVIEW_PATH_MAX_LENGTH)).max(32).optional();
581
+ var DevicePreviewToolStatusSchema = z10.union([
582
+ z10.object({
583
+ supported: z10.literal(false),
584
+ available: z10.literal(false),
585
+ interactive: z10.literal(false),
586
+ command: z10.never().optional(),
587
+ version: z10.never().optional(),
588
+ error: z10.string().min(1).max(DEVICE_PREVIEW_ERROR_MAX_LENGTH),
589
+ suggestions: DevicePreviewToolSuggestionsSchema
590
+ }).strict(),
591
+ z10.object({
592
+ supported: z10.literal(true),
593
+ available: z10.literal(false),
594
+ interactive: z10.literal(false),
595
+ command: z10.string().min(1).max(DEVICE_PREVIEW_PATH_MAX_LENGTH).optional(),
596
+ version: z10.string().min(1).max(DEVICE_PREVIEW_VERSION_MAX_LENGTH).optional(),
597
+ error: z10.string().min(1).max(DEVICE_PREVIEW_ERROR_MAX_LENGTH),
598
+ suggestions: DevicePreviewToolSuggestionsSchema
599
+ }).strict(),
600
+ z10.object({
601
+ supported: z10.literal(true),
602
+ available: z10.literal(true),
603
+ interactive: z10.literal(true),
604
+ command: z10.string().min(1).max(DEVICE_PREVIEW_PATH_MAX_LENGTH),
605
+ version: z10.string().min(1).max(DEVICE_PREVIEW_VERSION_MAX_LENGTH).optional(),
606
+ error: z10.never().optional(),
607
+ suggestions: DevicePreviewToolSuggestionsSchema
608
+ }).strict()
609
+ ]);
610
+ var DevicePreviewCapabilitySchema = z10.object({
611
+ ios: DevicePreviewToolStatusSchema,
612
+ android: DevicePreviewToolStatusSchema
613
+ }).strict();
614
+ var DevicePreviewTargetBaseSchema = z10.object({
615
+ targetId: IdSchema,
616
+ platform: DevicePreviewPlatformSchema,
617
+ name: z10.string().min(1).max(DEVICE_PREVIEW_NAME_MAX_LENGTH),
618
+ model: z10.string().min(1).max(DEVICE_PREVIEW_NAME_MAX_LENGTH),
619
+ osVersion: z10.string().min(1).max(DEVICE_PREVIEW_VERSION_MAX_LENGTH),
620
+ interactive: z10.boolean()
621
+ });
622
+ var DevicePreviewScreenEdgeSchema = z10.number().int().positive().max(DEVICE_PREVIEW_SCREEN_EDGE_MAX);
623
+ var DevicePreviewTargetSchema = z10.union([
624
+ DevicePreviewTargetBaseSchema.extend({
625
+ width: DevicePreviewScreenEdgeSchema,
626
+ height: DevicePreviewScreenEdgeSchema
627
+ }).strict(),
628
+ DevicePreviewTargetBaseSchema.extend({
629
+ width: z10.never().optional(),
630
+ height: z10.never().optional()
631
+ }).strict()
632
+ ]);
633
+ var DevicePreviewStateSchema = z10.enum(["ready", "disconnected"]);
634
+ var DevicePreviewSummaryBaseSchema = z10.object({
635
+ previewId: IdSchema,
636
+ name: DevicePreviewNameSchema,
637
+ platform: DevicePreviewPlatformSchema,
638
+ targetId: IdSchema,
639
+ model: z10.string().min(1).max(DEVICE_PREVIEW_NAME_MAX_LENGTH),
640
+ osVersion: z10.string().min(1).max(DEVICE_PREVIEW_VERSION_MAX_LENGTH),
641
+ interactive: z10.boolean(),
642
+ createdAt: z10.number().int().nonnegative(),
643
+ updatedAt: z10.number().int().nonnegative()
644
+ });
645
+ var DevicePreviewSummarySchema = z10.discriminatedUnion("state", [
646
+ DevicePreviewSummaryBaseSchema.extend({
647
+ state: z10.literal("ready"),
648
+ error: z10.never().optional()
649
+ }).strict(),
650
+ DevicePreviewSummaryBaseSchema.extend({
651
+ state: z10.literal("disconnected"),
652
+ error: z10.never().optional()
653
+ }).strict()
654
+ ]);
655
+ var DevicePreviewJpegStreamProfileSchema = z10.object({
656
+ format: z10.literal("jpeg"),
657
+ maxFps: z10.number().int().min(1).max(30).optional()
658
+ }).strict();
659
+ var DevicePreviewH264StreamProfileSchema = z10.object({
660
+ format: z10.literal("h264_annex_b")
661
+ }).strict();
662
+ var DevicePreviewStreamProfileSchema = z10.discriminatedUnion("format", [
663
+ DevicePreviewJpegStreamProfileSchema,
664
+ DevicePreviewH264StreamProfileSchema
665
+ ]);
666
+ var devicePreviewStreamStopReasonValues = [
667
+ "client_closed",
668
+ "preview_closed",
669
+ "proxy_offline",
670
+ "relay_shutdown",
671
+ "stream_error"
672
+ ];
673
+ var DevicePreviewStreamStopReasonSchema = z10.enum(devicePreviewStreamStopReasonValues);
674
+ var NormalizedCoordinateSchema = z10.number().finite().min(0).max(1);
675
+ var devicePreviewTouchPhaseValues = ["down", "move", "up"];
676
+ var DevicePreviewTouchPhaseSchema = z10.enum(devicePreviewTouchPhaseValues);
677
+ var devicePreviewOrientationValues = [
678
+ "portrait",
679
+ "landscape_left",
680
+ "landscape_right",
681
+ "portrait_upside_down",
682
+ "auto"
683
+ ];
684
+ var DevicePreviewOrientationSchema = z10.enum(devicePreviewOrientationValues);
685
+ var DevicePreviewInputSchema = z10.discriminatedUnion("kind", [
686
+ z10.object({
687
+ kind: z10.literal("touch"),
688
+ phase: DevicePreviewTouchPhaseSchema,
689
+ x: NormalizedCoordinateSchema,
690
+ y: NormalizedCoordinateSchema
691
+ }).strict(),
692
+ z10.object({
693
+ kind: z10.literal("text"),
694
+ text: z10.string().min(1).max(DEVICE_PREVIEW_TEXT_MAX_LENGTH)
695
+ }).strict(),
696
+ z10.object({
697
+ kind: z10.literal("button"),
698
+ button: z10.enum(["home", "back"])
699
+ }).strict(),
700
+ z10.object({
701
+ kind: z10.literal("orientation"),
702
+ orientation: DevicePreviewOrientationSchema
703
+ }).strict()
704
+ ]);
705
+ var DevicePreviewStreamRegisterSchema = z10.object({
706
+ type: z10.literal("device_preview_stream_register"),
707
+ proxyId: IdSchema,
708
+ connectionId: IdSchema
709
+ }).strict();
710
+ var DevicePreviewStreamRegisterResponseSchema = z10.discriminatedUnion("success", [
711
+ z10.object({
712
+ type: z10.literal("device_preview_stream_register_response"),
713
+ success: z10.literal(true)
714
+ }).strict(),
715
+ z10.object({
716
+ type: z10.literal("device_preview_stream_register_response"),
717
+ success: z10.literal(false),
718
+ error: z10.string().min(1).max(DEVICE_PREVIEW_ERROR_MAX_LENGTH)
719
+ }).strict()
720
+ ]);
721
+ var DevicePreviewStreamFlowBaseSchema = z10.object({
722
+ type: z10.literal("device_preview_stream_flow"),
723
+ streamId: IdSchema
724
+ });
725
+ var DevicePreviewStreamFlowSchema = z10.discriminatedUnion("paused", [
726
+ DevicePreviewStreamFlowBaseSchema.extend({
727
+ paused: z10.literal(true),
728
+ resyncRequired: z10.literal(false)
729
+ }).strict(),
730
+ DevicePreviewStreamFlowBaseSchema.extend({
731
+ paused: z10.literal(false),
732
+ resyncRequired: z10.boolean()
733
+ }).strict()
734
+ ]);
735
+ var DevicePreviewStreamServerMessageSchema = z10.union([
736
+ DevicePreviewStreamRegisterResponseSchema,
737
+ DevicePreviewStreamFlowSchema
738
+ ]);
739
+
740
+ // ../../packages/shared/dist/schemas/voice-stream.js
741
+ import { z as z11 } from "zod";
742
+ var VoiceAsrAudioEncodingSchema = z11.enum(["pcm_s16le", "mulaw"]);
743
+ var VoiceAsrStartMessageSchema = z11.object({
744
+ type: z11.literal("start"),
745
+ sessionId: z11.string().min(1),
746
+ attemptId: z11.string().min(1),
747
+ sampleRate: z11.number().int().positive(),
748
+ encoding: VoiceAsrAudioEncodingSchema
749
+ });
750
+ var VoiceAsrStopMessageSchema = z11.object({
751
+ type: z11.literal("stop"),
752
+ attemptId: z11.string().min(1)
753
+ });
754
+ var VoiceAsrClientMessageSchema = z11.discriminatedUnion("type", [
755
+ VoiceAsrStartMessageSchema,
756
+ VoiceAsrStopMessageSchema
757
+ ]);
758
+ var VoiceAsrServerMessageSchema = z11.discriminatedUnion("type", [
759
+ z11.object({ type: z11.literal("ready"), attemptId: z11.string().min(1) }),
760
+ z11.object({
761
+ type: z11.literal("audio_ack"),
762
+ attemptId: z11.string().min(1),
763
+ encodedBytes: z11.number().int().nonnegative(),
764
+ pcmBytes: z11.number().int().nonnegative(),
765
+ chunks: z11.number().int().nonnegative()
766
+ }),
767
+ z11.object({ type: z11.literal("partial"), attemptId: z11.string().min(1), text: z11.string() }),
768
+ z11.object({ type: z11.literal("final"), attemptId: z11.string().min(1), text: z11.string() }),
769
+ z11.object({
770
+ type: z11.literal("closed"),
771
+ attemptId: z11.string().min(1),
772
+ code: z11.number().int().optional(),
773
+ reason: z11.string().optional()
774
+ }),
775
+ z11.object({
776
+ type: z11.literal("error"),
777
+ attemptId: z11.string().min(1),
778
+ error: z11.string().optional(),
779
+ errorCode: z11.string().optional()
780
+ })
781
+ ]);
782
+
783
+ // ../../packages/shared/dist/slash-commands.js
784
+ function isCompactCommandText(text) {
785
+ return /^\/compact(?:\s|$)/.test(text.trimStart());
786
+ }
787
+
788
+ // ../../packages/shared/dist/tool-activity-summary.js
789
+ var SECRET_VALUE_PATTERN = /((?:authorization|api[_-]?key|token|password|secret)\s*[:=]\s*)(?:bearer\s+)?[^\s'"]+/giu;
790
+ var SECRET_FLAG_PATTERN = /(--(?:api-key|token|password|secret)(?:=|\s+))[^\s'"]+/giu;
791
+ function asString(value) {
792
+ return typeof value === "string" ? value : "";
793
+ }
794
+ function compact(value, max = 140) {
795
+ const text = value.replace(/\s+/gu, " ").trim();
796
+ if (text.length <= max)
797
+ return text;
798
+ return `${text.slice(0, max - 1)}\u2026`;
799
+ }
800
+ function redact(value) {
801
+ return value.replace(SECRET_VALUE_PATTERN, "$1[redacted]").replace(SECRET_FLAG_PATTERN, "$1[redacted]");
802
+ }
803
+ function filePath(input) {
804
+ return asString(input.file_path) || asString(input.path) || asString(input.notebook_path);
805
+ }
806
+ function summarizeToolActivity(toolName, input) {
807
+ switch (toolName) {
808
+ case "Bash": {
809
+ const command = compact(redact(asString(input.command)));
810
+ return command ? `\u8FD0\u884C\u547D\u4EE4\uFF1A${command}` : "\u8FD0\u884C\u547D\u4EE4";
811
+ }
812
+ case "BashBatch": {
813
+ const commands = Array.isArray(input.commands) ? input.commands.filter((item) => typeof item === "string") : [];
814
+ return commands.length > 0 ? `\u6279\u91CF\u8FD0\u884C\u547D\u4EE4\uFF1A${commands.length} \u6761` : "\u6279\u91CF\u8FD0\u884C\u547D\u4EE4";
815
+ }
816
+ case "ProcessWait":
817
+ return "\u7B49\u5F85\u547D\u4EE4\u5B8C\u6210";
818
+ case "ProcessInput": {
819
+ const value = compact(redact(asString(input.input)), 80);
820
+ return value ? `\u53D1\u9001\u7EC8\u7AEF\u8F93\u5165\uFF1A${value}` : "\u53D1\u9001\u7EC8\u7AEF\u8F93\u5165";
821
+ }
822
+ case "Read": {
823
+ const path = filePath(input);
824
+ return path ? `\u8BFB\u53D6\u6587\u4EF6\uFF1A${path}` : "\u8BFB\u53D6\u6587\u4EF6";
825
+ }
826
+ case "Write": {
827
+ const path = filePath(input);
828
+ return path ? `\u5199\u5165\u6587\u4EF6\uFF1A${path}` : "\u5199\u5165\u6587\u4EF6";
829
+ }
830
+ case "Edit":
831
+ case "MultiEdit": {
832
+ const path = filePath(input);
833
+ return path ? `\u7F16\u8F91\u6587\u4EF6\uFF1A${path}` : "\u7F16\u8F91\u6587\u4EF6";
834
+ }
835
+ case "LS": {
836
+ const path = filePath(input);
837
+ return path ? `\u5217\u51FA\u76EE\u5F55\uFF1A${path}` : "\u5217\u51FA\u76EE\u5F55";
838
+ }
839
+ case "Grep": {
840
+ const pattern = compact(redact(asString(input.pattern)), 80);
841
+ const path = filePath(input);
842
+ if (pattern && path)
843
+ return `\u641C\u7D22\uFF1A${pattern} in ${path}`;
844
+ return pattern ? `\u641C\u7D22\uFF1A${pattern}` : "\u641C\u7D22\u6587\u672C";
845
+ }
846
+ case "Glob": {
847
+ const pattern = compact(redact(asString(input.pattern)), 80);
848
+ return pattern ? `\u67E5\u627E\u6587\u4EF6\uFF1A${pattern}` : "\u67E5\u627E\u6587\u4EF6";
849
+ }
850
+ case "WebFetch": {
851
+ const url = compact(redact(asString(input.url)), 100);
852
+ return url ? `\u8BFB\u53D6\u7F51\u9875\uFF1A${url}` : "\u8BFB\u53D6\u7F51\u9875";
853
+ }
854
+ case "WebSearch": {
855
+ const query = compact(redact(asString(input.query)), 100);
856
+ return query ? `\u7F51\u9875\u641C\u7D22\uFF1A${query}` : "\u7F51\u9875\u641C\u7D22";
857
+ }
858
+ case "ViewImage": {
859
+ const path = filePath(input);
860
+ return path ? `\u67E5\u770B\u56FE\u7247\uFF1A${path}` : "\u67E5\u770B\u56FE\u7247";
861
+ }
862
+ case "ViewImageBatch": {
863
+ const paths = Array.isArray(input.paths) ? input.paths.filter((item) => typeof item === "string") : [];
864
+ return paths.length > 0 ? `\u6279\u91CF\u67E5\u770B\u56FE\u7247\uFF1A${paths.length} \u5F20` : "\u6279\u91CF\u67E5\u770B\u56FE\u7247";
865
+ }
866
+ case "Web":
867
+ return "\u8BBF\u95EE\u7F51\u9875";
868
+ case "ToolScript":
869
+ return "\u6267\u884C\u5DE5\u5177\u7F16\u6392";
870
+ case "TodoWrite":
871
+ return "\u66F4\u65B0\u4EFB\u52A1\u5217\u8868";
872
+ case "Patch": {
873
+ const path = filePath(input);
874
+ if (path)
875
+ return `\u5E94\u7528\u8865\u4E01\uFF1A${path}`;
876
+ const paths = Array.isArray(input.paths) ? input.paths.filter((item) => typeof item === "string") : [];
877
+ if (paths.length === 1)
878
+ return `\u5E94\u7528\u8865\u4E01\uFF1A${paths[0]}`;
879
+ if (paths.length > 1)
880
+ return `\u5E94\u7528\u8865\u4E01\uFF1A${paths[0]} \u7B49 ${paths.length} \u4E2A\u6587\u4EF6`;
881
+ return "\u5E94\u7528\u8865\u4E01";
882
+ }
883
+ default:
884
+ return `\u4F7F\u7528\u5DE5\u5177\uFF1A${toolName}`;
885
+ }
886
+ }
887
+
888
+ // ../../packages/shared/dist/schemas/relay-control.js
889
+ import { z as z12 } from "zod";
890
+
891
+ // ../../packages/shared/dist/constants/relay-errors.js
892
+ var RelayErrorCode = {
893
+ NOT_REGISTERED: "NOT_REGISTERED",
894
+ NOT_BOUND: "NOT_BOUND",
895
+ PROXY_OFFLINE: "PROXY_OFFLINE",
896
+ INVALID_MESSAGE: "INVALID_MESSAGE",
897
+ STALE_BINDING: "STALE_BINDING",
898
+ UNSUPPORTED: "UNSUPPORTED",
899
+ INVALID_RANGE: "INVALID_RANGE"
900
+ };
901
+
902
+ // ../../packages/shared/dist/schemas/relay-control.js
903
+ var RELAY_CONTROL_PROTOCOL_VERSION = 1;
904
+ var ProxyInfoSchema = z12.object({
905
+ proxyId: IdSchema,
906
+ name: z12.string().optional(),
907
+ version: z12.string().min(1).max(64),
908
+ online: z12.boolean(),
909
+ sessions: z12.array(z12.string())
910
+ });
911
+ var RelayClientInfoSchema = z12.object({
912
+ clientId: IdSchema,
913
+ proxyId: IdSchema.optional(),
914
+ connectedAt: z12.number().int().nonnegative(),
915
+ current: z12.boolean().optional(),
916
+ userAgent: z12.string().optional(),
917
+ platform: z12.string().optional(),
918
+ maxTouchPoints: z12.number().int().nonnegative().optional(),
919
+ browserName: z12.string().min(1),
920
+ osName: z12.string().min(1),
921
+ deviceKind: z12.enum(["desktop", "tablet", "phone", "unknown"]),
922
+ remoteAddress: z12.string().optional()
923
+ });
924
+ var AgentCliAvailabilitySchema = z12.object({
925
+ available: z12.boolean(),
926
+ command: z12.string().optional(),
927
+ error: z12.string().optional(),
928
+ suggestions: z12.array(z12.string()).optional()
929
+ });
930
+ var AgentCliStatusSchema = z12.object({
931
+ claude: AgentCliAvailabilitySchema,
932
+ codex: AgentCliAvailabilitySchema,
933
+ kimi: AgentCliAvailabilitySchema
934
+ });
935
+ var DirEntrySchema = z12.object({ name: z12.string(), isDir: z12.boolean() });
936
+ var FileTreeGroupSchema = z12.object({
937
+ path: z12.string(),
938
+ entries: z12.array(DirEntrySchema)
939
+ });
940
+ var CommandEntrySchema = z12.object({
941
+ name: z12.string(),
942
+ description: z12.string(),
943
+ argumentHint: z12.string().optional(),
944
+ source: z12.string()
945
+ });
946
+ var HistorySessionSchema = z12.object({
947
+ id: z12.string(),
948
+ title: z12.string(),
949
+ projectDir: z12.string(),
950
+ updatedAt: z12.number(),
951
+ provider: z12.enum(providerValues),
952
+ preferredMode: z12.enum(sessionModeValues).optional()
953
+ });
954
+ var SessionHistoryPositionShape = {
955
+ timestamp: z12.number().optional(),
956
+ cursor: z12.string().optional()
957
+ };
958
+ var SessionHistoryMessageSchema = z12.discriminatedUnion("role", [
959
+ z12.object({
960
+ role: z12.enum(["user", "assistant", "system"]),
961
+ text: z12.string(),
962
+ ...SessionHistoryPositionShape
963
+ }),
964
+ z12.object({
965
+ role: z12.literal("activity"),
966
+ text: z12.string(),
967
+ toolId: IdSchema,
968
+ toolName: z12.string(),
969
+ parameters: z12.record(z12.string(), z12.unknown()).optional(),
970
+ status: z12.enum(["running", "done", "error"]),
971
+ ...SessionHistoryPositionShape
972
+ })
973
+ ]);
974
+ var RequestIdShape = { requestId: IdSchema.optional() };
975
+ var RequiredRequestIdShape = { requestId: IdSchema };
976
+ var ControlErrorCodeSchema = z12.enum(Object.values(ControlErrorCode));
977
+ var RequestErrorShape = {
978
+ error: z12.string().optional(),
979
+ errorCode: ControlErrorCodeSchema.optional()
980
+ };
981
+ var RequiredRequestErrorShape = {
982
+ error: z12.string().min(1),
983
+ errorCode: ControlErrorCodeSchema
984
+ };
985
+ var RemoteFileDispositionSchema = z12.enum(["inline", "download"]);
986
+ var RemoteFileUploadKindSchema = z12.enum(["clipboard_image", "file"]);
987
+ function control(type, shape, directions) {
988
+ return {
989
+ type,
990
+ directions: new Set(Array.isArray(directions) ? directions : directions ? [directions] : []),
991
+ schema: z12.object({
992
+ type: z12.literal(type),
993
+ ...shape ?? {}
994
+ })
995
+ };
996
+ }
997
+ function strictControl(type, shape, directions) {
998
+ return {
999
+ type,
1000
+ directions: new Set(Array.isArray(directions) ? directions : directions ? [directions] : []),
1001
+ schema: z12.object({
1002
+ type: z12.literal(type),
1003
+ ...shape
1004
+ }).strict()
1005
+ };
1006
+ }
1007
+ function controlSchema(type, schema, directions) {
1008
+ return {
1009
+ type,
1010
+ directions: new Set(Array.isArray(directions) ? directions : directions ? [directions] : []),
1011
+ schema
1012
+ };
1013
+ }
1014
+ var ProxySelectResponseSchema = z12.discriminatedUnion("success", [
1015
+ z12.object({
1016
+ type: z12.literal("proxy_select_response"),
1017
+ ...RequestIdShape,
1018
+ success: z12.literal(true),
1019
+ proxyId: IdSchema,
1020
+ bindingId: IdSchema
1021
+ }).strict(),
1022
+ z12.object({
1023
+ type: z12.literal("proxy_select_response"),
1024
+ ...RequestIdShape,
1025
+ success: z12.literal(false),
1026
+ ...RequestErrorShape
1027
+ }).strict()
1028
+ ]);
1029
+ var ClientRegisterResponseSchema = z12.discriminatedUnion("status", [
1030
+ z12.object({
1031
+ type: z12.literal("client_register_response"),
1032
+ protocolVersion: z12.literal(RELAY_CONTROL_PROTOCOL_VERSION),
1033
+ status: z12.literal("restored"),
1034
+ proxyId: IdSchema,
1035
+ bindingId: IdSchema
1036
+ }).strict(),
1037
+ z12.object({
1038
+ type: z12.literal("client_register_response"),
1039
+ protocolVersion: z12.literal(RELAY_CONTROL_PROTOCOL_VERSION),
1040
+ status: z12.literal("proxy_offline"),
1041
+ proxyId: IdSchema,
1042
+ bindingId: IdSchema
1043
+ }).strict(),
1044
+ z12.object({
1045
+ type: z12.literal("client_register_response"),
1046
+ protocolVersion: z12.literal(RELAY_CONTROL_PROTOCOL_VERSION),
1047
+ status: z12.literal("new")
1048
+ }).strict()
1049
+ ]);
1050
+ var PreviewCreateResponseSchema = z12.discriminatedUnion("accepted", [
1051
+ z12.object({
1052
+ type: z12.literal("preview_create_response"),
1053
+ ...RequiredRequestIdShape,
1054
+ scope: PreviewScopeSchema,
1055
+ operationId: IdSchema,
1056
+ accepted: z12.literal(true),
1057
+ previewId: IdSchema
1058
+ }).strict(),
1059
+ z12.object({
1060
+ type: z12.literal("preview_create_response"),
1061
+ ...RequiredRequestIdShape,
1062
+ scope: PreviewScopeSchema,
1063
+ operationId: IdSchema,
1064
+ accepted: z12.literal(false),
1065
+ ...RequiredRequestErrorShape
1066
+ }).strict()
1067
+ ]);
1068
+ var DevicePreviewCreateResponseSchema = z12.discriminatedUnion("accepted", [
1069
+ z12.object({
1070
+ type: z12.literal("device_preview_create_response"),
1071
+ ...RequiredRequestIdShape,
1072
+ scope: PreviewScopeSchema,
1073
+ operationId: IdSchema,
1074
+ accepted: z12.literal(true),
1075
+ previewId: IdSchema
1076
+ }).strict(),
1077
+ z12.object({
1078
+ type: z12.literal("device_preview_create_response"),
1079
+ ...RequiredRequestIdShape,
1080
+ scope: PreviewScopeSchema,
1081
+ operationId: IdSchema,
1082
+ accepted: z12.literal(false),
1083
+ ...RequiredRequestErrorShape
1084
+ }).strict()
1085
+ ]);
1086
+ var PreviewCapabilityResponseSchema = z12.discriminatedUnion("success", [
1087
+ z12.object({
1088
+ type: z12.literal("preview_capability_response"),
1089
+ ...RequiredRequestIdShape,
1090
+ scope: PreviewScopeSchema,
1091
+ success: z12.literal(true),
1092
+ capability: WebPreviewCapabilitySchema
1093
+ }).strict(),
1094
+ z12.object({
1095
+ type: z12.literal("preview_capability_response"),
1096
+ ...RequiredRequestIdShape,
1097
+ scope: PreviewScopeSchema,
1098
+ success: z12.literal(false),
1099
+ ...RequiredRequestErrorShape
1100
+ }).strict()
1101
+ ]);
1102
+ var DevicePreviewCapabilityResponseSchema = z12.discriminatedUnion("success", [
1103
+ z12.object({
1104
+ type: z12.literal("device_preview_capability_response"),
1105
+ ...RequiredRequestIdShape,
1106
+ scope: PreviewScopeSchema,
1107
+ success: z12.literal(true),
1108
+ capability: DevicePreviewCapabilitySchema
1109
+ }).strict(),
1110
+ z12.object({
1111
+ type: z12.literal("device_preview_capability_response"),
1112
+ ...RequiredRequestIdShape,
1113
+ scope: PreviewScopeSchema,
1114
+ success: z12.literal(false),
1115
+ ...RequiredRequestErrorShape
1116
+ }).strict()
1117
+ ]);
1118
+ var ProxyInfoRequestSchema = z12.object({
1119
+ type: z12.literal("proxy_info_request"),
1120
+ ...RequestIdShape
1121
+ }).strict();
1122
+ var ProxyInfoResponseSchema = z12.object({
1123
+ type: z12.literal("proxy_info"),
1124
+ ...RequestIdShape,
1125
+ homePath: z12.string(),
1126
+ agentCli: AgentCliStatusSchema
1127
+ }).strict();
1128
+ var PreviewStaticInspectResponseSchema = z12.discriminatedUnion("success", [
1129
+ z12.object({
1130
+ type: z12.literal("preview_static_inspect_response"),
1131
+ ...RequiredRequestIdShape,
1132
+ scope: PreviewScopeSchema,
1133
+ success: z12.literal(true),
1134
+ entryPath: WebPreviewPathSchema.optional(),
1135
+ htmlEntries: PreviewHtmlEntriesSchema
1136
+ }).strict(),
1137
+ z12.object({
1138
+ type: z12.literal("preview_static_inspect_response"),
1139
+ ...RequiredRequestIdShape,
1140
+ scope: PreviewScopeSchema,
1141
+ success: z12.literal(false),
1142
+ ...RequiredRequestErrorShape
1143
+ }).strict()
1144
+ ]);
1145
+ var PreviewRenameResponseSchema = z12.discriminatedUnion("success", [
1146
+ z12.object({
1147
+ type: z12.literal("preview_rename_response"),
1148
+ ...RequiredRequestIdShape,
1149
+ scope: PreviewScopeSchema,
1150
+ operationId: IdSchema,
1151
+ previewId: IdSchema,
1152
+ success: z12.literal(true)
1153
+ }).strict(),
1154
+ z12.object({
1155
+ type: z12.literal("preview_rename_response"),
1156
+ ...RequiredRequestIdShape,
1157
+ scope: PreviewScopeSchema,
1158
+ operationId: IdSchema,
1159
+ previewId: IdSchema,
1160
+ success: z12.literal(false),
1161
+ ...RequiredRequestErrorShape
1162
+ }).strict()
1163
+ ]);
1164
+ var PreviewReconnectResponseSchema = z12.discriminatedUnion("success", [
1165
+ z12.object({
1166
+ type: z12.literal("preview_reconnect_response"),
1167
+ ...RequiredRequestIdShape,
1168
+ scope: PreviewScopeSchema,
1169
+ operationId: IdSchema,
1170
+ previewId: IdSchema,
1171
+ success: z12.literal(true)
1172
+ }).strict(),
1173
+ z12.object({
1174
+ type: z12.literal("preview_reconnect_response"),
1175
+ ...RequiredRequestIdShape,
1176
+ scope: PreviewScopeSchema,
1177
+ operationId: IdSchema,
1178
+ previewId: IdSchema,
1179
+ success: z12.literal(false),
1180
+ ...RequiredRequestErrorShape
1181
+ }).strict()
1182
+ ]);
1183
+ var PreviewCloseResponseSchema = z12.discriminatedUnion("success", [
1184
+ z12.object({
1185
+ type: z12.literal("preview_close_response"),
1186
+ ...RequiredRequestIdShape,
1187
+ scope: PreviewScopeSchema,
1188
+ operationId: IdSchema,
1189
+ previewId: IdSchema,
1190
+ success: z12.literal(true)
1191
+ }).strict(),
1192
+ z12.object({
1193
+ type: z12.literal("preview_close_response"),
1194
+ ...RequiredRequestIdShape,
1195
+ scope: PreviewScopeSchema,
1196
+ operationId: IdSchema,
1197
+ previewId: IdSchema,
1198
+ success: z12.literal(false),
1199
+ ...RequiredRequestErrorShape
1200
+ }).strict()
1201
+ ]);
1202
+ var DevicePreviewTargetsResponseSchema = z12.discriminatedUnion("success", [
1203
+ z12.object({
1204
+ type: z12.literal("device_preview_targets_response"),
1205
+ ...RequiredRequestIdShape,
1206
+ scope: PreviewScopeSchema,
1207
+ success: z12.literal(true),
1208
+ targets: z12.array(DevicePreviewTargetSchema).max(1024)
1209
+ }).strict(),
1210
+ z12.object({
1211
+ type: z12.literal("device_preview_targets_response"),
1212
+ ...RequiredRequestIdShape,
1213
+ scope: PreviewScopeSchema,
1214
+ success: z12.literal(false),
1215
+ ...RequiredRequestErrorShape
1216
+ }).strict()
1217
+ ]);
1218
+ var DevicePreviewRenameResponseSchema = z12.discriminatedUnion("success", [
1219
+ z12.object({
1220
+ type: z12.literal("device_preview_rename_response"),
1221
+ ...RequiredRequestIdShape,
1222
+ scope: PreviewScopeSchema,
1223
+ operationId: IdSchema,
1224
+ previewId: IdSchema,
1225
+ success: z12.literal(true)
1226
+ }).strict(),
1227
+ z12.object({
1228
+ type: z12.literal("device_preview_rename_response"),
1229
+ ...RequiredRequestIdShape,
1230
+ scope: PreviewScopeSchema,
1231
+ operationId: IdSchema,
1232
+ previewId: IdSchema,
1233
+ success: z12.literal(false),
1234
+ ...RequiredRequestErrorShape
1235
+ }).strict()
1236
+ ]);
1237
+ var DevicePreviewReconnectResponseSchema = z12.discriminatedUnion("success", [
1238
+ z12.object({
1239
+ type: z12.literal("device_preview_reconnect_response"),
1240
+ ...RequiredRequestIdShape,
1241
+ scope: PreviewScopeSchema,
1242
+ operationId: IdSchema,
1243
+ previewId: IdSchema,
1244
+ success: z12.literal(true)
1245
+ }).strict(),
1246
+ z12.object({
1247
+ type: z12.literal("device_preview_reconnect_response"),
1248
+ ...RequiredRequestIdShape,
1249
+ scope: PreviewScopeSchema,
1250
+ operationId: IdSchema,
1251
+ previewId: IdSchema,
1252
+ success: z12.literal(false),
1253
+ ...RequiredRequestErrorShape
1254
+ }).strict()
1255
+ ]);
1256
+ var DevicePreviewCloseResponseSchema = z12.discriminatedUnion("success", [
1257
+ z12.object({
1258
+ type: z12.literal("device_preview_close_response"),
1259
+ ...RequiredRequestIdShape,
1260
+ scope: PreviewScopeSchema,
1261
+ operationId: IdSchema,
1262
+ previewId: IdSchema,
1263
+ success: z12.literal(true)
1264
+ }).strict(),
1265
+ z12.object({
1266
+ type: z12.literal("device_preview_close_response"),
1267
+ ...RequiredRequestIdShape,
1268
+ scope: PreviewScopeSchema,
1269
+ operationId: IdSchema,
1270
+ previewId: IdSchema,
1271
+ success: z12.literal(false),
1272
+ ...RequiredRequestErrorShape
1273
+ }).strict()
1274
+ ]);
1275
+ var DevicePreviewStreamUrlResponseSchema = z12.discriminatedUnion("success", [
1276
+ z12.object({
1277
+ type: z12.literal("device_preview_stream_url_response"),
1278
+ ...RequiredRequestIdShape,
1279
+ scope: PreviewScopeSchema,
1280
+ previewId: IdSchema,
1281
+ success: z12.literal(true),
1282
+ url: z12.string().min(1).max(4096),
1283
+ leaseId: IdSchema,
1284
+ expiresAt: z12.number().int().nonnegative(),
1285
+ controlMode: z12.enum(["controller", "view_only"])
1286
+ }).strict(),
1287
+ z12.object({
1288
+ type: z12.literal("device_preview_stream_url_response"),
1289
+ ...RequiredRequestIdShape,
1290
+ scope: PreviewScopeSchema,
1291
+ previewId: IdSchema,
1292
+ success: z12.literal(false),
1293
+ ...RequiredRequestErrorShape
1294
+ }).strict()
1295
+ ]);
1296
+ var DevicePreviewStreamStartResponseBaseShape = {
1297
+ type: z12.literal("device_preview_stream_start_response"),
1298
+ streamId: IdSchema,
1299
+ leaseId: IdSchema,
1300
+ previewId: IdSchema
1301
+ };
1302
+ var DevicePreviewStreamStartSuccessSchema = z12.object({
1303
+ ...DevicePreviewStreamStartResponseBaseShape,
1304
+ success: z12.literal(true),
1305
+ format: DevicePreviewStreamFormatSchema,
1306
+ width: z12.number().int().positive().max(16384).optional(),
1307
+ height: z12.number().int().positive().max(16384).optional()
1308
+ }).strict().superRefine((response, context) => {
1309
+ if (response.width === void 0 === (response.height === void 0))
1310
+ return;
1311
+ context.addIssue({
1312
+ code: "custom",
1313
+ path: response.width === void 0 ? ["width"] : ["height"],
1314
+ message: "Device preview stream dimensions must include both width and height"
1315
+ });
1316
+ });
1317
+ var DevicePreviewStreamStartResponseSchema = z12.discriminatedUnion("success", [
1318
+ DevicePreviewStreamStartSuccessSchema,
1319
+ z12.object({
1320
+ ...DevicePreviewStreamStartResponseBaseShape,
1321
+ success: z12.literal(false),
1322
+ ...RequiredRequestErrorShape
1323
+ }).strict()
1324
+ ]);
1325
+ var DevicePreviewStreamCompleteSchema = z12.object({
1326
+ type: z12.literal("device_preview_stream_complete"),
1327
+ streamId: IdSchema,
1328
+ leaseId: IdSchema,
1329
+ previewId: IdSchema,
1330
+ success: z12.literal(false),
1331
+ error: z12.string().min(1)
1332
+ }).strict();
1333
+ var DevicePreviewStreamStartBaseShape = {
1334
+ type: z12.literal("device_preview_stream_start"),
1335
+ streamId: IdSchema,
1336
+ leaseId: IdSchema,
1337
+ previewId: IdSchema
1338
+ };
1339
+ var DevicePreviewStreamStartSchema = z12.discriminatedUnion("format", [
1340
+ z12.object({
1341
+ ...DevicePreviewStreamStartBaseShape,
1342
+ ...DevicePreviewJpegStreamProfileSchema.shape
1343
+ }).strict(),
1344
+ z12.object({
1345
+ ...DevicePreviewStreamStartBaseShape,
1346
+ ...DevicePreviewH264StreamProfileSchema.shape
1347
+ }).strict()
1348
+ ]);
1349
+ var DevicePreviewInputAckSchema = z12.discriminatedUnion("success", [
1350
+ z12.object({
1351
+ type: z12.literal("device_preview_input_ack"),
1352
+ scope: PreviewScopeSchema,
1353
+ leaseId: IdSchema,
1354
+ inputSeq: z12.number().int().min(0).max(4294967295),
1355
+ success: z12.literal(true)
1356
+ }).strict(),
1357
+ z12.object({
1358
+ type: z12.literal("device_preview_input_ack"),
1359
+ scope: PreviewScopeSchema,
1360
+ leaseId: IdSchema,
1361
+ inputSeq: z12.number().int().min(0).max(4294967295),
1362
+ success: z12.literal(false),
1363
+ ...RequiredRequestErrorShape
1364
+ }).strict()
1365
+ ]);
1366
+ var DevicePreviewControlClaimResponseSchema = z12.discriminatedUnion("success", [
1367
+ z12.object({
1368
+ type: z12.literal("device_preview_control_claim_response"),
1369
+ ...RequiredRequestIdShape,
1370
+ scope: PreviewScopeSchema,
1371
+ leaseId: IdSchema,
1372
+ success: z12.literal(true),
1373
+ controlMode: z12.literal("controller")
1374
+ }).strict(),
1375
+ z12.object({
1376
+ type: z12.literal("device_preview_control_claim_response"),
1377
+ ...RequiredRequestIdShape,
1378
+ scope: PreviewScopeSchema,
1379
+ leaseId: IdSchema,
1380
+ success: z12.literal(false),
1381
+ ...RequiredRequestErrorShape
1382
+ }).strict()
1383
+ ]);
1384
+ var SessionPermissionModeSchema = z12.enum([
1385
+ "default",
1386
+ "auto",
1387
+ "acceptEdits",
1388
+ "plan",
1389
+ "bypassPermissions",
1390
+ "dontAsk"
1391
+ ]);
1392
+ var AgentJsonSessionCreateSchema = z12.object({
1393
+ type: z12.literal("session_create"),
1394
+ ...RequiredRequestIdShape,
1395
+ kind: z12.literal("agent"),
1396
+ cwd: z12.string(),
1397
+ name: z12.string().optional(),
1398
+ provider: z12.enum(providerValues),
1399
+ mode: z12.literal("json"),
1400
+ resumeSessionId: z12.string().optional(),
1401
+ permissionMode: SessionPermissionModeSchema.optional()
1402
+ }).strict();
1403
+ var AgentPtySessionCreateSchema = z12.object({
1404
+ type: z12.literal("session_create"),
1405
+ ...RequiredRequestIdShape,
1406
+ kind: z12.literal("agent"),
1407
+ cwd: z12.string(),
1408
+ name: z12.string().optional(),
1409
+ provider: z12.enum(providerValues),
1410
+ mode: z12.literal("pty"),
1411
+ resumeSessionId: z12.string().optional(),
1412
+ cols: z12.number().int().positive().max(PTY_INITIAL_MAX_COLS),
1413
+ rows: z12.number().int().positive().max(PTY_INITIAL_MAX_ROWS),
1414
+ permissionMode: SessionPermissionModeSchema.optional()
1415
+ }).strict();
1416
+ var TerminalSessionCreateSchema = z12.object({
1417
+ type: z12.literal("session_create"),
1418
+ ...RequiredRequestIdShape,
1419
+ kind: z12.literal("terminal"),
1420
+ name: z12.string().optional(),
1421
+ mode: z12.literal("pty"),
1422
+ cols: z12.number().int().positive().max(PTY_INITIAL_MAX_COLS),
1423
+ rows: z12.number().int().positive().max(PTY_INITIAL_MAX_ROWS)
1424
+ }).strict();
1425
+ var SessionCreateSchema = z12.discriminatedUnion("mode", [
1426
+ AgentJsonSessionCreateSchema,
1427
+ z12.discriminatedUnion("kind", [AgentPtySessionCreateSchema, TerminalSessionCreateSchema])
1428
+ ]);
1429
+ var SessionCreateSuccessBaseShape = {
1430
+ type: z12.literal("session_create_response"),
1431
+ ...RequiredRequestIdShape,
1432
+ success: z12.literal(true),
1433
+ sessionId: IdSchema,
1434
+ cwd: z12.string(),
1435
+ lastActive: z12.number(),
1436
+ name: z12.string().optional(),
1437
+ nameLocked: z12.boolean().optional()
1438
+ };
1439
+ var SessionCreateSuccessResponseSchema = z12.discriminatedUnion("mode", [
1440
+ z12.object({
1441
+ ...SessionCreateSuccessBaseShape,
1442
+ kind: z12.literal("agent"),
1443
+ mode: z12.literal("json"),
1444
+ provider: z12.enum(providerValues)
1445
+ }).strict(),
1446
+ z12.discriminatedUnion("kind", [
1447
+ z12.object({
1448
+ ...SessionCreateSuccessBaseShape,
1449
+ kind: z12.literal("agent"),
1450
+ mode: z12.literal("pty"),
1451
+ provider: z12.enum(providerValues),
1452
+ ptyOwner: z12.enum(ptyOwnerValues)
1453
+ }).strict(),
1454
+ z12.object({
1455
+ ...SessionCreateSuccessBaseShape,
1456
+ kind: z12.literal("terminal"),
1457
+ mode: z12.literal("pty"),
1458
+ provider: z12.literal("claude"),
1459
+ ptyOwner: z12.literal("local-terminal")
1460
+ }).strict()
1461
+ ])
1462
+ ]);
1463
+ var SessionCreateResponseSchema = z12.discriminatedUnion("success", [
1464
+ SessionCreateSuccessResponseSchema,
1465
+ z12.object({
1466
+ type: z12.literal("session_create_response"),
1467
+ ...RequiredRequestIdShape,
1468
+ success: z12.literal(false),
1469
+ ...RequiredRequestErrorShape,
1470
+ activeWriterPid: z12.number().int().positive().optional()
1471
+ }).strict()
1472
+ ]);
1473
+ var relayControlDefinitions = [
1474
+ strictControl("proxy_register", {
1475
+ protocolVersion: z12.literal(RELAY_CONTROL_PROTOCOL_VERSION),
1476
+ proxyId: IdSchema,
1477
+ name: z12.string().optional(),
1478
+ proxyVersion: z12.string().min(1).max(64)
1479
+ }),
1480
+ strictControl("proxy_register_response", {
1481
+ protocolVersion: z12.literal(RELAY_CONTROL_PROTOCOL_VERSION),
1482
+ status: z12.enum(["new", "reconnected"]),
1483
+ relayVersion: z12.string().min(1).max(64),
1484
+ // Relay rotates this nonce for every successful main Proxy registration. The dedicated image
1485
+ // stream socket must present it before Relay accepts frames, so a superseded Proxy connection
1486
+ // cannot keep publishing into a newly registered Proxy with the same persistent proxyId.
1487
+ connectionId: IdSchema
1488
+ }),
1489
+ control("proxy_list_request", RequestIdShape),
1490
+ control("proxy_list_response", {
1491
+ ...RequestIdShape,
1492
+ proxies: z12.array(ProxyInfoSchema)
1493
+ }),
1494
+ control("proxy_remove", {
1495
+ ...RequiredRequestIdShape,
1496
+ proxyId: IdSchema
1497
+ }),
1498
+ control("proxy_remove_response", {
1499
+ ...RequiredRequestIdShape,
1500
+ proxyId: IdSchema,
1501
+ success: z12.boolean(),
1502
+ ...RequestErrorShape
1503
+ }),
1504
+ control("relay_client_list_request", RequestIdShape),
1505
+ control("relay_client_list_response", {
1506
+ ...RequestIdShape,
1507
+ clients: z12.array(RelayClientInfoSchema)
1508
+ }),
1509
+ control("relay_client_kick", { ...RequiredRequestIdShape, clientId: IdSchema }),
1510
+ control("relay_client_kick_response", {
1511
+ ...RequiredRequestIdShape,
1512
+ clientId: IdSchema,
1513
+ success: z12.boolean(),
1514
+ ...RequestErrorShape
1515
+ }),
1516
+ control("relay_client_kicked", {
1517
+ reason: z12.string().optional()
1518
+ }),
1519
+ control("remote_file_url_request", {
1520
+ ...RequiredRequestIdShape,
1521
+ sessionId: IdSchema,
1522
+ path: z12.string().min(1),
1523
+ disposition: RemoteFileDispositionSchema
1524
+ }),
1525
+ control("remote_file_url_response", {
1526
+ ...RequiredRequestIdShape,
1527
+ ...RequestErrorShape,
1528
+ sessionId: IdSchema,
1529
+ path: z12.string().optional(),
1530
+ success: z12.boolean(),
1531
+ url: z12.string().optional(),
1532
+ expiresAt: z12.number().int().nonnegative().optional()
1533
+ }),
1534
+ control("remote_file_metadata_request", {
1535
+ ...RequiredRequestIdShape,
1536
+ sessionId: IdSchema,
1537
+ path: z12.string().min(1)
1538
+ }),
1539
+ control("remote_file_metadata_response", {
1540
+ ...RequiredRequestIdShape,
1541
+ ...RequestErrorShape,
1542
+ sessionId: IdSchema,
1543
+ path: z12.string().optional(),
1544
+ success: z12.boolean(),
1545
+ mimeType: z12.string().optional(),
1546
+ size: z12.number().int().nonnegative().optional(),
1547
+ fileName: z12.string().optional()
1548
+ }),
1549
+ control("remote_file_stream_request", {
1550
+ streamId: IdSchema,
1551
+ sessionId: IdSchema,
1552
+ path: z12.string().min(1),
1553
+ disposition: RemoteFileDispositionSchema
1554
+ }),
1555
+ control("remote_file_stream_response", {
1556
+ ...RequestErrorShape,
1557
+ streamId: IdSchema,
1558
+ sessionId: IdSchema,
1559
+ success: z12.boolean(),
1560
+ path: z12.string().optional(),
1561
+ mimeType: z12.string().optional(),
1562
+ size: z12.number().int().nonnegative().optional(),
1563
+ fileName: z12.string().optional()
1564
+ }),
1565
+ control("remote_file_stream_complete", {
1566
+ ...RequestErrorShape,
1567
+ streamId: IdSchema,
1568
+ success: z12.boolean()
1569
+ }),
1570
+ control("remote_file_stream_cancel", {
1571
+ streamId: IdSchema
1572
+ }),
1573
+ control("remote_file_upload_url_request", {
1574
+ ...RequiredRequestIdShape,
1575
+ sessionId: IdSchema,
1576
+ kind: RemoteFileUploadKindSchema,
1577
+ fileName: z12.string().optional(),
1578
+ mimeType: z12.string().min(1),
1579
+ size: z12.number().int().nonnegative().optional()
1580
+ }),
1581
+ control("remote_file_upload_url_response", {
1582
+ ...RequiredRequestIdShape,
1583
+ ...RequestErrorShape,
1584
+ sessionId: IdSchema,
1585
+ success: z12.boolean(),
1586
+ uploadUrl: z12.string().optional(),
1587
+ expiresAt: z12.number().int().nonnegative().optional()
1588
+ }),
1589
+ control("remote_file_upload_stream_request", {
1590
+ uploadId: IdSchema,
1591
+ sessionId: IdSchema,
1592
+ kind: RemoteFileUploadKindSchema,
1593
+ fileName: z12.string().optional(),
1594
+ mimeType: z12.string().min(1),
1595
+ size: z12.number().int().nonnegative().optional()
1596
+ }),
1597
+ control("remote_file_upload_stream_complete", {
1598
+ uploadId: IdSchema
1599
+ }),
1600
+ control("remote_file_upload_stream_cancel", {
1601
+ uploadId: IdSchema
1602
+ }),
1603
+ control("remote_file_upload_stream_response", {
1604
+ ...RequestErrorShape,
1605
+ uploadId: IdSchema,
1606
+ sessionId: IdSchema,
1607
+ success: z12.boolean(),
1608
+ path: z12.string().optional()
1609
+ }),
1610
+ control("proxy_select", { ...RequestIdShape, proxyId: IdSchema }),
1611
+ controlSchema("proxy_select_response", ProxySelectResponseSchema),
1612
+ control("relay_error", {
1613
+ code: z12.enum(Object.values(RelayErrorCode)),
1614
+ message: z12.string(),
1615
+ // 可选 requestId: relay 把 client 发来 raw 的 requestId 字段透传回来,
1616
+ // client 侧 waitForMessage 据此把对应 pending request 立即拒掉而不必等到 timeout。
1617
+ requestId: IdSchema.optional()
1618
+ }),
1619
+ // Voice Pilot config is relay-local: client reads/updates the relay's stored provider settings.
1620
+ control("voice_config_request", RequestIdShape),
1621
+ control("voice_config_response", {
1622
+ ...RequestIdShape,
1623
+ ...RequestErrorShape,
1624
+ config: VoiceProviderConfigSchema.optional()
1625
+ }),
1626
+ control("voice_config_update", {
1627
+ ...RequestIdShape,
1628
+ config: VoiceConfigUpdateSchema
1629
+ }),
1630
+ control("voice_config_update_response", {
1631
+ ...RequestIdShape,
1632
+ ...RequestErrorShape,
1633
+ success: z12.boolean(),
1634
+ config: VoiceProviderConfigSchema.optional()
1635
+ }),
1636
+ control("voice_config_test", {
1637
+ ...RequestIdShape,
1638
+ config: VoiceConfigUpdateSchema.optional()
1639
+ }),
1640
+ control("voice_config_test_response", {
1641
+ ...RequestIdShape,
1642
+ ...RequestErrorShape,
1643
+ success: z12.boolean(),
1644
+ audioBase64: z12.string().optional(),
1645
+ audioSampleRate: z12.number().int().positive().optional(),
1646
+ audioEncoding: z12.literal("pcm_s16le").optional(),
1647
+ transcript: z12.string().optional()
1648
+ }),
1649
+ control("voice_capabilities_request", {
1650
+ ...RequestIdShape,
1651
+ region: z12.enum(voiceRegionValues).optional()
1652
+ }),
1653
+ control("voice_capabilities_response", {
1654
+ ...RequestIdShape,
1655
+ ...RequestErrorShape,
1656
+ capabilities: VoiceCapabilitiesSchema.optional()
1657
+ }),
1658
+ // Lightweight latency probes. These measure synthetic round-trip latency for the transport
1659
+ // segments and intentionally stay separate from PTY input echo tracing.
1660
+ control("latency_web_relay_ping", RequiredRequestIdShape),
1661
+ control("latency_web_relay_pong", {
1662
+ ...RequiredRequestIdShape,
1663
+ relayNow: z12.number().optional()
1664
+ }),
1665
+ control("latency_relay_proxy_request", RequiredRequestIdShape),
1666
+ control("latency_relay_proxy_response", {
1667
+ ...RequiredRequestIdShape,
1668
+ success: z12.boolean(),
1669
+ rttMs: z12.number().nonnegative().optional(),
1670
+ error: z12.string().optional()
1671
+ }),
1672
+ control("latency_relay_proxy_ping", {
1673
+ ...RequiredRequestIdShape,
1674
+ relayNow: z12.number().optional()
1675
+ }),
1676
+ control("latency_relay_proxy_pong", {
1677
+ ...RequiredRequestIdShape,
1678
+ proxyNow: z12.number().optional()
1679
+ }),
1680
+ control("latency_web_proxy_ping", RequiredRequestIdShape, "client_to_proxy"),
1681
+ control("latency_web_proxy_pong", { ...RequiredRequestIdShape, proxyNow: z12.number().optional() }, "proxy_to_client"),
1682
+ // Web preview is independent from Agent/terminal sessions. Relay rewrites requestId and routes
1683
+ // every response to the exact requesting WebSocket; only the two push messages are broadcast.
1684
+ strictControl("preview_capability_request", {
1685
+ ...RequiredRequestIdShape,
1686
+ scope: PreviewScopeSchema,
1687
+ refreshPath: z12.boolean()
1688
+ }, "client_to_proxy"),
1689
+ controlSchema("preview_capability_response", PreviewCapabilityResponseSchema, "proxy_to_client"),
1690
+ strictControl("preview_static_inspect_request", {
1691
+ ...RequiredRequestIdShape,
1692
+ scope: PreviewScopeSchema,
1693
+ path: WebPreviewPathSchema
1694
+ }, "client_to_proxy"),
1695
+ controlSchema("preview_static_inspect_response", PreviewStaticInspectResponseSchema, "proxy_to_client"),
1696
+ strictControl("preview_create_request", {
1697
+ ...RequiredRequestIdShape,
1698
+ scope: PreviewScopeSchema,
1699
+ operationId: IdSchema,
1700
+ source: WebPreviewSourceInputSchema,
1701
+ tunnelProvider: TunnelProviderSchema,
1702
+ name: WebPreviewNameSchema.optional()
1703
+ }, "client_to_proxy"),
1704
+ controlSchema("preview_create_response", PreviewCreateResponseSchema, "proxy_to_client"),
1705
+ strictControl("preview_list_request", { ...RequiredRequestIdShape, scope: PreviewScopeSchema }, "client_to_proxy"),
1706
+ strictControl("preview_list_response", {
1707
+ ...RequiredRequestIdShape,
1708
+ scope: PreviewScopeSchema,
1709
+ epoch: IdSchema,
1710
+ revision: z12.number().int().nonnegative(),
1711
+ previews: z12.array(PreviewSummarySchema)
1712
+ }, "proxy_to_client"),
1713
+ strictControl("preview_rename_request", {
1714
+ ...RequiredRequestIdShape,
1715
+ scope: PreviewScopeSchema,
1716
+ operationId: IdSchema,
1717
+ previewId: IdSchema,
1718
+ name: WebPreviewNameSchema
1719
+ }, "client_to_proxy"),
1720
+ controlSchema("preview_rename_response", PreviewRenameResponseSchema, "proxy_to_client"),
1721
+ strictControl("preview_reconnect_request", {
1722
+ ...RequiredRequestIdShape,
1723
+ scope: PreviewScopeSchema,
1724
+ operationId: IdSchema,
1725
+ previewId: IdSchema
1726
+ }, "client_to_proxy"),
1727
+ controlSchema("preview_reconnect_response", PreviewReconnectResponseSchema, "proxy_to_client"),
1728
+ strictControl("preview_close_request", {
1729
+ ...RequiredRequestIdShape,
1730
+ scope: PreviewScopeSchema,
1731
+ operationId: IdSchema,
1732
+ previewId: IdSchema
1733
+ }, "client_to_proxy"),
1734
+ controlSchema("preview_close_response", PreviewCloseResponseSchema, "proxy_to_client"),
1735
+ strictControl("preview_state_event", {
1736
+ epoch: IdSchema,
1737
+ revision: z12.number().int().nonnegative(),
1738
+ preview: PreviewSummarySchema
1739
+ }),
1740
+ strictControl("preview_removed_event", {
1741
+ epoch: IdSchema,
1742
+ revision: z12.number().int().nonnegative(),
1743
+ previewId: IdSchema
1744
+ }),
1745
+ strictControl("preview_state_push", {
1746
+ scope: PreviewScopeSchema,
1747
+ epoch: IdSchema,
1748
+ revision: z12.number().int().nonnegative(),
1749
+ preview: PreviewSummarySchema
1750
+ }, "proxy_to_client"),
1751
+ strictControl("preview_removed_push", {
1752
+ scope: PreviewScopeSchema,
1753
+ epoch: IdSchema,
1754
+ revision: z12.number().int().nonnegative(),
1755
+ previewId: IdSchema
1756
+ }, "proxy_to_client"),
1757
+ // Device previews are a sibling of Web previews under the product-level Preview entry, but
1758
+ // their data plane is private. Management and input use the authenticated main sockets;
1759
+ // JPEG/H.264 frames use `/proxy-stream` plus a one-use HTTP stream URL issued by Relay.
1760
+ strictControl("device_preview_capability_request", {
1761
+ ...RequiredRequestIdShape,
1762
+ scope: PreviewScopeSchema,
1763
+ refreshPath: z12.boolean()
1764
+ }, "client_to_proxy"),
1765
+ controlSchema("device_preview_capability_response", DevicePreviewCapabilityResponseSchema, "proxy_to_client"),
1766
+ strictControl("device_preview_targets_request", {
1767
+ ...RequiredRequestIdShape,
1768
+ scope: PreviewScopeSchema,
1769
+ refresh: z12.boolean()
1770
+ }, "client_to_proxy"),
1771
+ controlSchema("device_preview_targets_response", DevicePreviewTargetsResponseSchema, "proxy_to_client"),
1772
+ strictControl("device_preview_create_request", {
1773
+ ...RequiredRequestIdShape,
1774
+ scope: PreviewScopeSchema,
1775
+ operationId: IdSchema,
1776
+ targetId: IdSchema,
1777
+ name: DevicePreviewNameSchema.optional()
1778
+ }, "client_to_proxy"),
1779
+ controlSchema("device_preview_create_response", DevicePreviewCreateResponseSchema, "proxy_to_client"),
1780
+ strictControl("device_preview_list_request", { ...RequiredRequestIdShape, scope: PreviewScopeSchema }, "client_to_proxy"),
1781
+ strictControl("device_preview_list_response", {
1782
+ ...RequiredRequestIdShape,
1783
+ scope: PreviewScopeSchema,
1784
+ epoch: IdSchema,
1785
+ revision: z12.number().int().nonnegative(),
1786
+ previews: z12.array(DevicePreviewSummarySchema).max(1024)
1787
+ }, "proxy_to_client"),
1788
+ strictControl("device_preview_rename_request", {
1789
+ ...RequiredRequestIdShape,
1790
+ scope: PreviewScopeSchema,
1791
+ operationId: IdSchema,
1792
+ previewId: IdSchema,
1793
+ name: DevicePreviewNameSchema
1794
+ }, "client_to_proxy"),
1795
+ controlSchema("device_preview_rename_response", DevicePreviewRenameResponseSchema, "proxy_to_client"),
1796
+ strictControl("device_preview_reconnect_request", {
1797
+ ...RequiredRequestIdShape,
1798
+ scope: PreviewScopeSchema,
1799
+ operationId: IdSchema,
1800
+ previewId: IdSchema
1801
+ }, "client_to_proxy"),
1802
+ controlSchema("device_preview_reconnect_response", DevicePreviewReconnectResponseSchema, "proxy_to_client"),
1803
+ strictControl("device_preview_close_request", {
1804
+ ...RequiredRequestIdShape,
1805
+ scope: PreviewScopeSchema,
1806
+ operationId: IdSchema,
1807
+ previewId: IdSchema
1808
+ }, "client_to_proxy"),
1809
+ controlSchema("device_preview_close_response", DevicePreviewCloseResponseSchema, "proxy_to_client"),
1810
+ strictControl("device_preview_state_event", {
1811
+ epoch: IdSchema,
1812
+ revision: z12.number().int().nonnegative(),
1813
+ preview: DevicePreviewSummarySchema
1814
+ }),
1815
+ strictControl("device_preview_removed_event", {
1816
+ epoch: IdSchema,
1817
+ revision: z12.number().int().nonnegative(),
1818
+ previewId: IdSchema
1819
+ }),
1820
+ strictControl("device_preview_state_push", {
1821
+ scope: PreviewScopeSchema,
1822
+ epoch: IdSchema,
1823
+ revision: z12.number().int().nonnegative(),
1824
+ preview: DevicePreviewSummarySchema
1825
+ }, "proxy_to_client"),
1826
+ strictControl("device_preview_removed_push", {
1827
+ scope: PreviewScopeSchema,
1828
+ epoch: IdSchema,
1829
+ revision: z12.number().int().nonnegative(),
1830
+ previewId: IdSchema
1831
+ }, "proxy_to_client"),
1832
+ strictControl("device_preview_stream_url_request", {
1833
+ ...RequiredRequestIdShape,
1834
+ scope: PreviewScopeSchema,
1835
+ previewId: IdSchema,
1836
+ profile: DevicePreviewStreamProfileSchema
1837
+ }),
1838
+ controlSchema("device_preview_stream_url_response", DevicePreviewStreamUrlResponseSchema),
1839
+ controlSchema("device_preview_stream_start", DevicePreviewStreamStartSchema),
1840
+ controlSchema("device_preview_stream_start_response", DevicePreviewStreamStartResponseSchema),
1841
+ strictControl("device_preview_stream_stop", {
1842
+ streamId: IdSchema,
1843
+ reason: DevicePreviewStreamStopReasonSchema
1844
+ }),
1845
+ controlSchema("device_preview_stream_complete", DevicePreviewStreamCompleteSchema),
1846
+ strictControl("device_preview_input", {
1847
+ scope: PreviewScopeSchema,
1848
+ leaseId: IdSchema,
1849
+ inputSeq: z12.number().int().min(0).max(4294967295),
1850
+ input: DevicePreviewInputSchema
1851
+ }, "client_to_proxy"),
1852
+ controlSchema("device_preview_input_ack", DevicePreviewInputAckSchema, "proxy_to_client"),
1853
+ // Relay-internal ordering barrier. It is deliberately absent from both public direction sets:
1854
+ // browsers cannot abort another viewer's queued input, and Proxy never sends it to browsers.
1855
+ strictControl("device_preview_input_revoke", {
1856
+ leaseId: IdSchema,
1857
+ reason: z12.literal("control_taken_over")
1858
+ }),
1859
+ strictControl("device_preview_control_claim_request", {
1860
+ ...RequiredRequestIdShape,
1861
+ scope: PreviewScopeSchema,
1862
+ leaseId: IdSchema
1863
+ }),
1864
+ controlSchema("device_preview_control_claim_response", DevicePreviewControlClaimResponseSchema),
1865
+ strictControl("device_preview_control_revoked_push", {
1866
+ scope: PreviewScopeSchema,
1867
+ leaseId: IdSchema,
1868
+ reason: z12.enum(["taken_over", "stream_closed", "proxy_offline", "lease_expired"])
1869
+ }),
1870
+ // 客户端注册协议
1871
+ strictControl("client_register", {
1872
+ protocolVersion: z12.literal(RELAY_CONTROL_PROTOCOL_VERSION),
1873
+ clientId: IdSchema,
1874
+ userAgent: z12.string().optional(),
1875
+ platform: z12.string().optional(),
1876
+ maxTouchPoints: z12.number().int().nonnegative().optional(),
1877
+ browserName: z12.string().min(1),
1878
+ osName: z12.string().min(1),
1879
+ deviceKind: z12.enum(["desktop", "tablet", "phone", "unknown"])
1880
+ }),
1881
+ controlSchema("client_register_response", ClientRegisterResponseSchema),
1882
+ // Proxy 离线通知
1883
+ control("proxy_offline", {
1884
+ proxyId: IdSchema
1885
+ }),
1886
+ // 用户明确删除了离线 Proxy。与列表暂时缺项分开建模,客户端据此永久清理选择态。
1887
+ control("proxy_removed", {
1888
+ proxyId: IdSchema
1889
+ }),
1890
+ // Proxy 主动断开,relay 立即清理资源
1891
+ control("proxy_disconnect", {
1892
+ proxyId: IdSchema
1893
+ }),
1894
+ // Proxy 重连后通知 client 恢复
1895
+ control("proxy_online", {
1896
+ proxyId: IdSchema
1897
+ }),
1898
+ // 目录列表请求与响应
1899
+ strictControl("dir_list_request", {
1900
+ ...RequestIdShape,
1901
+ path: z12.string(),
1902
+ includeHidden: z12.boolean()
1903
+ }, "client_to_proxy"),
1904
+ control("dir_list_response", {
1905
+ ...RequestIdShape,
1906
+ ...RequestErrorShape,
1907
+ entries: z12.array(DirEntrySchema),
1908
+ path: z12.string(),
1909
+ includeHidden: z12.boolean()
1910
+ }, "proxy_to_client"),
1911
+ // 目录创建请求与响应
1912
+ control("dir_create_request", { ...RequestIdShape, path: z12.string() }, "client_to_proxy"),
1913
+ control("dir_create_response", {
1914
+ ...RequestIdShape,
1915
+ ...RequestErrorShape,
1916
+ path: z12.string(),
1917
+ success: z12.boolean()
1918
+ }, "proxy_to_client"),
1919
+ // 命令列表推送,proxy 将可用命令列表推给 client
1920
+ control("command_list_push", {
1921
+ sessionId: IdSchema,
1922
+ commands: z12.array(CommandEntrySchema)
1923
+ }, "proxy_to_client"),
1924
+ // 文件树推送: 按目录分组, 首组 path 即为 session cwd。
1925
+ // 前端把它写入普通目录树;includeHidden=true 的按需响应使用独立缓存。
1926
+ control("file_tree_push", {
1927
+ groups: z12.array(FileTreeGroupSchema)
1928
+ }, "proxy_to_client"),
1929
+ // 会话列表请求与权限模式变更
1930
+ strictControl("session_list_request", {}, "client_to_proxy"),
1931
+ control("permission_mode_change", {
1932
+ mode: z12.enum(["default", "auto_accept", "plan"]),
1933
+ // sessionId 可选:传入时 proxy 按该会话的 mode 分叉(PTY 发 Tab ANSI),未传走全局日志行为
1934
+ sessionId: IdSchema.optional()
1935
+ }, "client_to_proxy"),
1936
+ // 会话历史浏览
1937
+ control("session_history_request", RequiredRequestIdShape, "client_to_proxy"),
1938
+ control("session_history_response", {
1939
+ ...RequiredRequestIdShape,
1940
+ ...RequestErrorShape,
1941
+ success: z12.boolean(),
1942
+ sessions: z12.array(HistorySessionSchema)
1943
+ }, "proxy_to_client"),
1944
+ // PTY 语义状态,从 Envelope 迁移到 Control 层
1945
+ control("pty_state", { sessionId: IdSchema, payload: PtyStatePayloadSchema }, "proxy_to_client"),
1946
+ // Provider 语义状态,来自 Claude/Codex hook 等结构化事件,不从 PTY 字节推断
1947
+ control("agent_status", { sessionId: IdSchema, payload: AgentStatusPayloadSchema }, "proxy_to_client"),
1948
+ // 终端标题变化,proxy -> client
1949
+ control("terminal_title", { sessionId: IdSchema, title: z12.string() }, "proxy_to_client"),
1950
+ // 终端尺寸变化,proxy -> client
1951
+ control("terminal_resize", {
1952
+ sessionId: IdSchema,
1953
+ cols: z12.number().int().positive(),
1954
+ rows: z12.number().int().positive(),
1955
+ // PTY output and resize events share one ordered render sequence. The client can therefore
1956
+ // place a resize between the exact byte frames that preceded and followed it.
1957
+ outputSeq: z12.number().int().nonnegative()
1958
+ }, "proxy_to_client"),
1959
+ control("terminal_resize_request", { sessionId: IdSchema, cols: z12.number().int().positive(), rows: z12.number().int().positive() }, "client_to_proxy"),
1960
+ // 远程终止 JSON 会话,client -> proxy
1961
+ strictControl("session_terminate", { sessionId: IdSchema }, "client_to_proxy"),
1962
+ control("session_rename", { ...RequestIdShape, sessionId: IdSchema, name: z12.string() }, "client_to_proxy"),
1963
+ control("session_rename_response", {
1964
+ ...RequestIdShape,
1965
+ sessionId: IdSchema,
1966
+ success: z12.boolean(),
1967
+ name: z12.string().optional(),
1968
+ ...RequestErrorShape
1969
+ }, "proxy_to_client"),
1970
+ // 中断当前 turn,client -> proxy;JSON 由 session-worker 打断 Claude 子进程并保留会话。
1971
+ control("session_worker_abort", { sessionId: IdSchema }, "client_to_proxy"),
1972
+ // turn 完成信号,proxy -> client,对应 claude stream-json 的 result 事件
1973
+ control("turn_result", {
1974
+ sessionId: IdSchema,
1975
+ success: z12.boolean(),
1976
+ isError: z12.boolean(),
1977
+ // stream-json result.result 是本轮最终文本。assistant_message 流丢失或 CLI 未发增量时,
1978
+ // Web 用它作为 JSON 模式兜底展示,避免 turn 已结束但界面空白。
1979
+ result: z12.string().optional()
1980
+ }, "proxy_to_client"),
1981
+ // 客户端发送到 PTY 的原始字节(ANSI 序列),不追加换行
1982
+ control("remote_input_raw", { sessionId: IdSchema, data: z12.string(), traceId: IdSchema.optional() }, "client_to_proxy"),
1983
+ // 客户端询问 proxy 的环境信息 (home 路径等), client -> proxy -> response
1984
+ // FilePathPicker 用 homePath 作为 select 模式下的默认起点, 新建会话时打开即可浏览
1985
+ controlSchema("proxy_info_request", ProxyInfoRequestSchema, "client_to_proxy"),
1986
+ controlSchema("proxy_info", ProxyInfoResponseSchema, "proxy_to_client"),
1987
+ control("agent_cli_config_update", { ...RequestIdShape, provider: z12.enum(providerValues), path: z12.string().min(1) }, "client_to_proxy"),
1988
+ control("agent_cli_config_update_response", {
1989
+ ...RequestIdShape,
1990
+ provider: z12.enum(providerValues),
1991
+ agentCli: AgentCliStatusSchema.optional(),
1992
+ ...RequestErrorShape
1993
+ }, "proxy_to_client"),
1994
+ // 远程创建会话,client -> proxy -> response。PTY 初始几何是一次性的;
1995
+ // 创建后尺寸由会话端持有,浏览器刷新、重连或换设备不重排既有内容。
1996
+ controlSchema("session_create", SessionCreateSchema, "client_to_proxy"),
1997
+ controlSchema("session_create_response", SessionCreateResponseSchema, "proxy_to_client"),
1998
+ // 会话创建响应已经成功返回、页面已进入终端后,Provider 仍可能在 bootstrap 阶段
1999
+ // 非零退出。把可识别的运行时错误结构化推给 Web,避免关键错误只留在终端闪屏里。
2000
+ control("session_runtime_error", {
2001
+ sessionId: IdSchema,
2002
+ error: z12.string(),
2003
+ errorCode: ControlErrorCodeSchema,
2004
+ activeWriterPid: z12.number().int().positive().optional()
2005
+ }, "proxy_to_client"),
2006
+ // 客户端请求会话历史消息,client -> proxy
2007
+ control("session_messages_request", {
2008
+ ...RequestIdShape,
2009
+ sessionId: IdSchema,
2010
+ limit: z12.number().int().min(1).max(200).optional(),
2011
+ before: z12.string().optional()
2012
+ }, "client_to_proxy"),
2013
+ // 客户端请求会话资源(命令列表 + 文件树),client -> proxy
2014
+ control("session_resources_request", { ...RequiredRequestIdShape, sessionId: IdSchema }, "client_to_proxy"),
2015
+ control("session_resources_response", {
2016
+ ...RequiredRequestIdShape,
2017
+ ...RequestErrorShape,
2018
+ sessionId: IdSchema,
2019
+ commands: z12.array(CommandEntrySchema),
2020
+ groups: z12.array(FileTreeGroupSchema)
2021
+ }, "proxy_to_client"),
2022
+ // 客户端请求当前 provider 语义状态;不经 relay 缓存,由 proxy 返回当前值
2023
+ control("agent_status_request", { ...RequestIdShape, sessionId: IdSchema.optional() }, "client_to_proxy"),
2024
+ control("agent_status_response", {
2025
+ ...RequestIdShape,
2026
+ statuses: z12.array(z12.object({ sessionId: IdSchema, payload: AgentStatusPayloadSchema }))
2027
+ }, "proxy_to_client"),
2028
+ // 客户端确认已收到审批请求;proxy 只记录送达状态,不把它当成用户决策
2029
+ control("permission_request_delivered", { sessionId: IdSchema, requestId: IdSchema }, "client_to_proxy"),
2030
+ control("tool_approve", { sessionId: IdSchema, payload: ToolApprovePayloadSchema }, "client_to_proxy"),
2031
+ control("tool_deny", { sessionId: IdSchema, payload: ToolDenyPayloadSchema }, "client_to_proxy"),
2032
+ // proxy 确认用户决策已进入 provider/worker 路径;web 用它更新审批卡片状态
2033
+ control("permission_decision_result", {
2034
+ sessionId: IdSchema,
2035
+ requestId: IdSchema,
2036
+ outcome: z12.enum(["allow", "deny"]),
2037
+ delivered: z12.boolean(),
2038
+ message: z12.string().optional()
2039
+ }, "proxy_to_client"),
2040
+ // proxy 推送当前 pending 的工具审批列表,client 据此恢复审批卡片
2041
+ control("pending_approvals_push", {
2042
+ sessionId: IdSchema,
2043
+ approvals: z12.array(z12.object({
2044
+ requestId: IdSchema,
2045
+ toolName: z12.string(),
2046
+ input: z12.record(z12.string(), z12.unknown()),
2047
+ options: z12.array(ApprovalOptionSchema).optional()
2048
+ }))
2049
+ }, "proxy_to_client"),
2050
+ // Voice Pilot speech summaries are produced by proxy-side Claude Code so it can read project context.
2051
+ control("voice_summary_request", {
2052
+ ...RequestIdShape,
2053
+ sessionId: IdSchema,
2054
+ messageId: IdSchema,
2055
+ text: z12.string().min(1),
2056
+ reason: VoiceSummaryReasonSchema
2057
+ }, "client_to_proxy"),
2058
+ control("voice_summary_response", {
2059
+ ...RequestIdShape,
2060
+ ...RequestErrorShape,
2061
+ sessionId: IdSchema,
2062
+ messageId: IdSchema,
2063
+ success: z12.boolean(),
2064
+ summary: z12.string().min(1).optional()
2065
+ }, "proxy_to_client"),
2066
+ // 恢复会话时推送历史消息,proxy -> client
2067
+ control("session_history_messages", {
2068
+ ...RequestIdShape,
2069
+ sessionId: IdSchema,
2070
+ before: z12.string().optional(),
2071
+ messages: z12.array(SessionHistoryMessageSchema),
2072
+ hasMore: z12.boolean().optional(),
2073
+ nextBefore: z12.string().optional()
2074
+ }, "proxy_to_client"),
2075
+ // proxy 重连后同步活跃 session 列表给 relay。session_sync 由 relay 自消费(更新 proxy-session
2076
+ // 关联)不转发给 client,因此**没有** direction 标注——RelayControlDirection 只描述转发流。
2077
+ control("session_sync", {
2078
+ sessions: z12.array(createSessionIdentitySchema({
2079
+ id: z12.string(),
2080
+ cwd: z12.string(),
2081
+ name: z12.string().optional(),
2082
+ nameLocked: z12.boolean().optional(),
2083
+ state: z12.enum(sessionStateValues)
2084
+ }))
2085
+ }),
2086
+ // PTY 会话订阅,client -> proxy,触发 terminal serialize() 返回当前状态
2087
+ control("session_subscribe", { sessionId: IdSchema, requestId: IdSchema }, "client_to_proxy"),
2088
+ // PTY 会话快照,proxy -> client,serialize() 的全量终端状态
2089
+ control("session_snapshot", {
2090
+ sessionId: IdSchema,
2091
+ cols: z12.number().int().positive(),
2092
+ rows: z12.number().int().positive(),
2093
+ data: z12.string(),
2094
+ outputSeq: z12.number().int().nonnegative(),
2095
+ requestId: IdSchema
2096
+ }, "proxy_to_client")
2097
+ ];
2098
+ var relayControlSchemas = relayControlDefinitions.map((definition) => definition.schema);
2099
+ var RelayControlSchema = z12.discriminatedUnion("type", relayControlSchemas);
2100
+ var ProxyToClientRelayControlTypes = new Set(relayControlDefinitions.filter((definition) => definition.directions.has("proxy_to_client")).map((definition) => definition.type));
2101
+ var ClientToProxyRelayControlTypes = new Set(relayControlDefinitions.filter((definition) => definition.directions.has("client_to_proxy")).map((definition) => definition.type));
2102
+
2103
+ // ../../packages/shared/dist/constants/session.js
2104
+ var SessionState = {
2105
+ IDLE: "idle",
2106
+ WORKING: "working",
2107
+ COMPACTING: "compacting",
2108
+ WAITING_APPROVAL: "waiting_approval",
2109
+ ERROR: "error",
2110
+ TERMINATED: "terminated"
2111
+ };
2112
+
2113
+ // ../../packages/shared/dist/constants/session-create.js
2114
+ var SESSION_CREATE_SERVER_DEADLINE_MS = 3e4;
2115
+ var SESSION_CREATE_RESPONSE_GRACE_MS = 5e3;
2116
+ var SESSION_CREATE_CLIENT_TIMEOUT_MS = SESSION_CREATE_SERVER_DEADLINE_MS + SESSION_CREATE_RESPONSE_GRACE_MS;
2117
+
2118
+ // ../../packages/shared/dist/constants/relay-close-codes.js
2119
+ var RelayCloseCode = {
2120
+ CLIENT_KICKED: 4401,
2121
+ CLIENT_PROTOCOL_REJECTED: 4402,
2122
+ DEVICE_STREAM_PROTOCOL_REJECTED: 4403,
2123
+ DEVICE_STREAM_BINDING_REJECTED: 4404,
2124
+ PROXY_PROTOCOL_REJECTED: 4405
2125
+ };
2126
+
2127
+ // ../../packages/shared/dist/constants/wire-limits.js
2128
+ var RELAY_JSON_MESSAGE_MAX_BYTES = 8 * 1024 * 1024;
2129
+ var RELAY_BINARY_FRAME_MAX_BYTES = 10 * 1024 * 1024;
2130
+
2131
+ // ../../packages/shared/dist/binary-frame.js
2132
+ var SID_LEN_BYTES = 1;
2133
+ var SEQ_BYTES = 4;
2134
+ var HEADER_FIXED_BYTES = SID_LEN_BYTES + SEQ_BYTES;
2135
+ var FILE_STREAM_MARKER = 0;
2136
+ var FILE_STREAM_ID_LEN_BYTES = 1;
2137
+ var FILE_STREAM_HEADER_FIXED_BYTES = 1 + FILE_STREAM_ID_LEN_BYTES + SEQ_BYTES;
2138
+ function encodeBinaryFrame(sessionId, outputSeq, data) {
2139
+ const sidBytes = new TextEncoder().encode(sessionId);
2140
+ if (sidBytes.length === 0 || sidBytes.length > 255) {
2141
+ throw new RangeError(`sessionId byte length must be 1-255, got ${sidBytes.length} (sessionId=${sessionId})`);
2142
+ }
2143
+ if (!Number.isInteger(outputSeq) || outputSeq < 0 || outputSeq > 4294967295) {
2144
+ throw new RangeError(`outputSeq must be a uint32, got ${outputSeq}`);
2145
+ }
2146
+ const frame = new Uint8Array(SID_LEN_BYTES + sidBytes.length + SEQ_BYTES + data.length);
2147
+ frame[0] = sidBytes.length;
2148
+ frame.set(sidBytes, SID_LEN_BYTES);
2149
+ const seqOffset = SID_LEN_BYTES + sidBytes.length;
2150
+ new DataView(frame.buffer, frame.byteOffset + seqOffset, SEQ_BYTES).setUint32(0, outputSeq, true);
2151
+ frame.set(data, seqOffset + SEQ_BYTES);
2152
+ return frame;
2153
+ }
2154
+ function decodeBinaryFrame(view) {
2155
+ if (view.length < SID_LEN_BYTES + SEQ_BYTES)
2156
+ return null;
2157
+ const sidLen = view[0];
2158
+ if (sidLen === 0)
2159
+ return null;
2160
+ if (view.length < SID_LEN_BYTES + sidLen + SEQ_BYTES)
2161
+ return null;
2162
+ const sessionId = new TextDecoder().decode(view.subarray(SID_LEN_BYTES, SID_LEN_BYTES + sidLen));
2163
+ const seqOffset = SID_LEN_BYTES + sidLen;
2164
+ const outputSeq = new DataView(view.buffer, view.byteOffset + seqOffset, SEQ_BYTES).getUint32(0, true);
2165
+ const data = view.subarray(seqOffset + SEQ_BYTES);
2166
+ return { sessionId, outputSeq, data };
2167
+ }
2168
+ function encodeFileStreamFrame(streamId, chunkSeq, data) {
2169
+ const streamIdBytes = new TextEncoder().encode(streamId);
2170
+ if (streamIdBytes.length === 0 || streamIdBytes.length > 255) {
2171
+ throw new RangeError(`streamId byte length must be 1-255, got ${streamIdBytes.length} (streamId=${streamId})`);
2172
+ }
2173
+ if (!Number.isInteger(chunkSeq) || chunkSeq < 0 || chunkSeq > 4294967295) {
2174
+ throw new RangeError(`chunkSeq must be a uint32, got ${chunkSeq}`);
2175
+ }
2176
+ const frame = new Uint8Array(1 + FILE_STREAM_ID_LEN_BYTES + streamIdBytes.length + SEQ_BYTES + data.length);
2177
+ frame[0] = FILE_STREAM_MARKER;
2178
+ frame[1] = streamIdBytes.length;
2179
+ frame.set(streamIdBytes, 1 + FILE_STREAM_ID_LEN_BYTES);
2180
+ const seqOffset = 1 + FILE_STREAM_ID_LEN_BYTES + streamIdBytes.length;
2181
+ new DataView(frame.buffer, frame.byteOffset + seqOffset, SEQ_BYTES).setUint32(0, chunkSeq, true);
2182
+ frame.set(data, seqOffset + SEQ_BYTES);
2183
+ return frame;
2184
+ }
2185
+ function decodeFileStreamFrame(view) {
2186
+ if (view.length < FILE_STREAM_HEADER_FIXED_BYTES)
2187
+ return null;
2188
+ if (view[0] !== FILE_STREAM_MARKER)
2189
+ return null;
2190
+ const streamIdLen = view[1];
2191
+ if (streamIdLen === 0)
2192
+ return null;
2193
+ if (view.length < 1 + FILE_STREAM_ID_LEN_BYTES + streamIdLen + SEQ_BYTES)
2194
+ return null;
2195
+ const streamId = new TextDecoder().decode(view.subarray(1 + FILE_STREAM_ID_LEN_BYTES, 1 + FILE_STREAM_ID_LEN_BYTES + streamIdLen));
2196
+ const seqOffset = 1 + FILE_STREAM_ID_LEN_BYTES + streamIdLen;
2197
+ const chunkSeq = new DataView(view.buffer, view.byteOffset + seqOffset, SEQ_BYTES).getUint32(0, true);
2198
+ const data = view.subarray(seqOffset + SEQ_BYTES);
2199
+ return { streamId, chunkSeq, data };
2200
+ }
2201
+
2202
+ // ../../packages/shared/dist/device-preview-frame.js
2203
+ var STREAM_ID_LENGTH_BYTES = 1;
2204
+ var FRAME_SEQUENCE_BYTES = 4;
2205
+ var STREAM_FRAME_FIXED_HEADER_BYTES = STREAM_ID_LENGTH_BYTES + FRAME_SEQUENCE_BYTES;
2206
+ var DEVICE_PREVIEW_FRAME_MAX_BYTES = 2 * 1024 * 1024;
2207
+ var H264_PACKET_SENTINEL_BYTES = 1;
2208
+ var H264_PACKET_VERSION_BYTES = 1;
2209
+ var H264_PACKET_FLAGS_BYTES = 1;
2210
+ var H264_PACKET_DURATION_BYTES = 2;
2211
+ var H264_PACKET_PAYLOAD_LENGTH_BYTES = 4;
2212
+ var H264_PROXY_STREAM_ID_LENGTH_OFFSET = H264_PACKET_SENTINEL_BYTES + H264_PACKET_VERSION_BYTES + H264_PACKET_FLAGS_BYTES;
2213
+ var H264_PROXY_STREAM_ID_OFFSET = H264_PROXY_STREAM_ID_LENGTH_OFFSET + STREAM_ID_LENGTH_BYTES;
2214
+ var H264_HTTP_PAYLOAD_LENGTH_OFFSET = H264_PACKET_SENTINEL_BYTES + H264_PACKET_VERSION_BYTES + H264_PACKET_FLAGS_BYTES;
2215
+ var H264_HTTP_SEQUENCE_OFFSET = H264_HTTP_PAYLOAD_LENGTH_OFFSET + H264_PACKET_PAYLOAD_LENGTH_BYTES;
2216
+ var H264_HTTP_DURATION_OFFSET = H264_HTTP_SEQUENCE_OFFSET + FRAME_SEQUENCE_BYTES;
2217
+ var DEVICE_PREVIEW_H264_PACKET_SENTINEL = 0;
2218
+ var DEVICE_PREVIEW_H264_PACKET_VERSION = 1;
2219
+ var DEVICE_PREVIEW_H264_FLAG_CONFIGURATION = 1 << 0;
2220
+ var DEVICE_PREVIEW_H264_FLAG_KEYFRAME = 1 << 1;
2221
+ var H264_PACKET_KNOWN_FLAGS = DEVICE_PREVIEW_H264_FLAG_CONFIGURATION | DEVICE_PREVIEW_H264_FLAG_KEYFRAME;
2222
+ var DEVICE_PREVIEW_H264_PROXY_PACKET_FIXED_HEADER_BYTES = H264_PROXY_STREAM_ID_OFFSET + FRAME_SEQUENCE_BYTES + H264_PACKET_DURATION_BYTES;
2223
+ var DEVICE_PREVIEW_H264_HTTP_PACKET_HEADER_BYTES = H264_HTTP_DURATION_OFFSET + H264_PACKET_DURATION_BYTES;
2224
+ function isJpeg(data) {
2225
+ return data.length >= 4 && data[0] === 255 && data[1] === 216 && data[data.length - 2] === 255 && data[data.length - 1] === 217;
2226
+ }
2227
+ function assertJpeg(jpeg) {
2228
+ if (jpeg.length === 0 || jpeg.length > DEVICE_PREVIEW_FRAME_MAX_BYTES) {
2229
+ throw new RangeError(`device preview JPEG must be 1-${DEVICE_PREVIEW_FRAME_MAX_BYTES} bytes, got ${jpeg.length}`);
2230
+ }
2231
+ if (!isJpeg(jpeg))
2232
+ throw new TypeError("device preview frame is not a complete JPEG image");
2233
+ }
2234
+ function isAnnexB(data) {
2235
+ return data.length >= 4 && data[0] === 0 && data[1] === 0 && data[2] === 1 || data.length >= 5 && data[0] === 0 && data[1] === 0 && data[2] === 0 && data[3] === 1;
2236
+ }
2237
+ function assertPacketSequence(packetSequence) {
2238
+ if (!Number.isInteger(packetSequence) || packetSequence < 0 || packetSequence > 4294967295) {
2239
+ throw new RangeError(`packetSequence must be a uint32, got ${packetSequence}`);
2240
+ }
2241
+ }
2242
+ function assertPacketDuration(durationMs) {
2243
+ if (!Number.isInteger(durationMs) || durationMs < 0 || durationMs > 65535) {
2244
+ throw new RangeError(`durationMs must be a uint16, got ${durationMs}`);
2245
+ }
2246
+ }
2247
+ function assertAnnexB(annexB) {
2248
+ if (annexB.length === 0 || annexB.length > DEVICE_PREVIEW_FRAME_MAX_BYTES) {
2249
+ throw new RangeError(`device preview H.264 payload must be 1-${DEVICE_PREVIEW_FRAME_MAX_BYTES} bytes, got ${annexB.length}`);
2250
+ }
2251
+ if (!isAnnexB(annexB)) {
2252
+ throw new TypeError("device preview H.264 payload must use Annex-B start codes");
2253
+ }
2254
+ }
2255
+ function h264PacketFlags(packet) {
2256
+ if (packet.configuration && packet.keyframe) {
2257
+ throw new TypeError("device preview H.264 configuration and keyframe flags are mutually exclusive");
2258
+ }
2259
+ return (packet.configuration ? DEVICE_PREVIEW_H264_FLAG_CONFIGURATION : 0) | (packet.keyframe ? DEVICE_PREVIEW_H264_FLAG_KEYFRAME : 0);
2260
+ }
2261
+ function encodeDevicePreviewFrame(streamId, frameSequence, jpeg) {
2262
+ const streamIdBytes = new TextEncoder().encode(streamId);
2263
+ if (streamIdBytes.length === 0 || streamIdBytes.length > 255) {
2264
+ throw new RangeError(`streamId byte length must be 1-255, got ${streamIdBytes.length}`);
2265
+ }
2266
+ if (!Number.isInteger(frameSequence) || frameSequence < 0 || frameSequence > 4294967295) {
2267
+ throw new RangeError(`frameSequence must be a uint32, got ${frameSequence}`);
2268
+ }
2269
+ assertJpeg(jpeg);
2270
+ const frame = new Uint8Array(STREAM_ID_LENGTH_BYTES + streamIdBytes.length + FRAME_SEQUENCE_BYTES + jpeg.length);
2271
+ frame[0] = streamIdBytes.length;
2272
+ frame.set(streamIdBytes, STREAM_ID_LENGTH_BYTES);
2273
+ const sequenceOffset = STREAM_ID_LENGTH_BYTES + streamIdBytes.length;
2274
+ new DataView(frame.buffer, frame.byteOffset + sequenceOffset, FRAME_SEQUENCE_BYTES).setUint32(0, frameSequence, true);
2275
+ frame.set(jpeg, sequenceOffset + FRAME_SEQUENCE_BYTES);
2276
+ return frame;
2277
+ }
2278
+ function encodeDevicePreviewH264ProxyPacket(streamId, packet) {
2279
+ const streamIdBytes = new TextEncoder().encode(streamId);
2280
+ if (streamIdBytes.length === 0 || streamIdBytes.length > 255) {
2281
+ throw new RangeError(`streamId byte length must be 1-255, got ${streamIdBytes.length}`);
2282
+ }
2283
+ assertPacketSequence(packet.packetSequence);
2284
+ assertPacketDuration(packet.durationMs);
2285
+ assertAnnexB(packet.annexB);
2286
+ const sequenceOffset = H264_PROXY_STREAM_ID_OFFSET + streamIdBytes.length;
2287
+ const durationOffset = sequenceOffset + FRAME_SEQUENCE_BYTES;
2288
+ const payloadOffset = durationOffset + H264_PACKET_DURATION_BYTES;
2289
+ const encoded = new Uint8Array(payloadOffset + packet.annexB.length);
2290
+ encoded[0] = DEVICE_PREVIEW_H264_PACKET_SENTINEL;
2291
+ encoded[1] = DEVICE_PREVIEW_H264_PACKET_VERSION;
2292
+ encoded[2] = h264PacketFlags(packet);
2293
+ encoded[H264_PROXY_STREAM_ID_LENGTH_OFFSET] = streamIdBytes.length;
2294
+ encoded.set(streamIdBytes, H264_PROXY_STREAM_ID_OFFSET);
2295
+ const header = new DataView(encoded.buffer, encoded.byteOffset + sequenceOffset, FRAME_SEQUENCE_BYTES + H264_PACKET_DURATION_BYTES);
2296
+ header.setUint32(0, packet.packetSequence, true);
2297
+ header.setUint16(FRAME_SEQUENCE_BYTES, packet.durationMs, true);
2298
+ encoded.set(packet.annexB, payloadOffset);
2299
+ return encoded;
2300
+ }
2301
+
2302
+ // src/ipc/ipc-protocol.ts
2303
+ import { z as z13 } from "zod";
2304
+
2305
+ // src/ipc/line-buffer.ts
2306
+ import { Transform } from "stream";
2307
+ import { StringDecoder } from "string_decoder";
2308
+ var LineBuffer = class extends Transform {
2309
+ buffer = "";
2310
+ decoder = new StringDecoder("utf8");
2311
+ _transform(chunk, _encoding, callback) {
2312
+ this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
2313
+ const segments = this.buffer.split("\n");
2314
+ this.buffer = segments.pop();
2315
+ for (const segment of segments) {
2316
+ if (segment.length > 0) {
2317
+ this.push(segment);
2318
+ }
2319
+ }
2320
+ callback();
2321
+ }
2322
+ _flush(callback) {
2323
+ const tail = this.decoder.end();
2324
+ if (tail.length > 0) this.buffer += tail;
2325
+ if (this.buffer.length > 0) {
2326
+ this.push(this.buffer);
2327
+ this.buffer = "";
2328
+ }
2329
+ callback();
2330
+ }
2331
+ };
2332
+
2333
+ // src/ipc/ipc-protocol.ts
2334
+ var IPC_BINARY_MARKER = 0;
2335
+ var WORKER_IPC_PROTOCOL_VERSION = 1;
2336
+ var TERMINAL_IPC_PROTOCOL_VERSION = 1;
2337
+ function encodeBinaryIpcFrame(sessionId, data, outputSeq) {
2338
+ const inner = encodeBinaryFrame(sessionId, outputSeq, data);
2339
+ const frame = Buffer.alloc(1 + 4 + inner.length);
2340
+ frame[0] = IPC_BINARY_MARKER;
2341
+ frame.writeUInt32LE(inner.length, 1);
2342
+ frame.set(inner, 5);
2343
+ return frame;
2344
+ }
2345
+ var sessionStateValues2 = Object.values(SessionState);
2346
+ var ProviderHookContextSchema = z13.object({
2347
+ provider: z13.enum(["claude", "codex"]),
2348
+ sessionId: z13.string(),
2349
+ hookUrl: z13.string(),
2350
+ marker: z13.string(),
2351
+ token: z13.string()
2352
+ }).strict();
2353
+ var terminalSessionCreateFields = {
2354
+ type: z13.literal("session_create_request"),
2355
+ name: z13.string().optional(),
2356
+ mode: z13.literal("pty"),
2357
+ cwd: z13.string().min(1),
2358
+ pid: z13.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2359
+ protocolVersion: z13.literal(TERMINAL_IPC_PROTOCOL_VERSION),
2360
+ sessionId: z13.string().min(1).optional()
2361
+ };
2362
+ var TerminalSessionCreateRequestSchema = z13.discriminatedUnion("kind", [
2363
+ z13.object({
2364
+ ...terminalSessionCreateFields,
2365
+ kind: z13.literal("agent"),
2366
+ provider: z13.enum(providerValues)
2367
+ }).strict(),
2368
+ z13.object({
2369
+ ...terminalSessionCreateFields,
2370
+ kind: z13.literal("terminal"),
2371
+ provider: z13.literal("claude")
2372
+ }).strict()
2373
+ ]);
2374
+ var TerminalSessionCreateResponseSchema = z13.discriminatedUnion("success", [
2375
+ z13.object({
2376
+ type: z13.literal("session_create_response"),
2377
+ success: z13.literal(true),
2378
+ sessionId: z13.string().min(1),
2379
+ protocolVersion: z13.literal(TERMINAL_IPC_PROTOCOL_VERSION),
2380
+ hook: ProviderHookContextSchema.optional()
2381
+ }).strict(),
2382
+ z13.object({
2383
+ type: z13.literal("session_create_response"),
2384
+ success: z13.literal(false),
2385
+ protocolVersion: z13.literal(TERMINAL_IPC_PROTOCOL_VERSION),
2386
+ error: z13.string().min(1)
2387
+ }).strict()
2388
+ ]);
2389
+ var IpcMessageSchema = z13.discriminatedUnion("type", [
2390
+ // 客户端请求创建新会话,sessionId 可选用于重连时复用
2391
+ TerminalSessionCreateRequestSchema,
2392
+ // 服务端响应创建会话
2393
+ TerminalSessionCreateResponseSchema,
2394
+ // 客户端向服务端注册 PTY 会话
2395
+ z13.object({
2396
+ type: z13.literal("pty_register"),
2397
+ sessionId: z13.string(),
2398
+ pid: z13.number()
2399
+ }),
2400
+ // 客户端取消注册 PTY 会话
2401
+ z13.object({
2402
+ type: z13.literal("pty_deregister"),
2403
+ sessionId: z13.string(),
2404
+ exitCode: z13.number().int().optional(),
2405
+ errorTail: z13.string().max(2048).optional()
2406
+ }),
2407
+ // 输入,从服务端转发到客户端的 PTY stdin(手机远程输入注入)
2408
+ z13.object({
2409
+ type: z13.literal("pty_input"),
2410
+ sessionId: z13.string(),
2411
+ data: z13.string(),
2412
+ traceId: z13.string().optional()
2413
+ }),
2414
+ // serve → terminal:Web 端移除本地终端会话时,只断开远程视图,不杀本地 CLI。
2415
+ z13.object({
2416
+ type: z13.literal("pty_detach"),
2417
+ sessionId: z13.string()
2418
+ }),
2419
+ // serve → terminal worker:终止 Web 创建的纯终端进程。
2420
+ z13.object({
2421
+ type: z13.literal("pty_terminate"),
2422
+ sessionId: z13.string()
2423
+ }),
2424
+ // 错误响应
2425
+ z13.object({
2426
+ type: z13.literal("error"),
2427
+ message: z13.string(),
2428
+ code: z13.string().optional()
2429
+ }),
2430
+ // 客户端请求服务状态(含 relay 连接信息和 worker 状态)
2431
+ z13.object({
2432
+ type: z13.literal("service_status_request"),
2433
+ protocolVersion: z13.literal(TERMINAL_IPC_PROTOCOL_VERSION)
2434
+ }).strict(),
2435
+ // 服务端响应增强版服务状态
2436
+ z13.object({
2437
+ type: z13.literal("service_status_response"),
2438
+ protocolVersion: z13.literal(TERMINAL_IPC_PROTOCOL_VERSION),
2439
+ config: z13.object({
2440
+ profile: z13.string().optional(),
2441
+ version: z13.string(),
2442
+ autoUpdate: z13.boolean(),
2443
+ relayName: z13.string(),
2444
+ relayNameSource: z13.enum(["cli", "profile", "env"]),
2445
+ relayUrl: z13.string().optional(),
2446
+ relayUrlSource: z13.enum(["env", "file", "none"]),
2447
+ relayTokenSource: z13.enum(["env", "file", "none"]),
2448
+ hookPort: z13.number(),
2449
+ hookPortSource: z13.enum(["env", "file", "default"])
2450
+ }),
2451
+ relay: z13.object({
2452
+ connected: z13.boolean(),
2453
+ proxyId: z13.string(),
2454
+ reconnectAttempt: z13.number(),
2455
+ queueDepth: z13.number()
2456
+ }).nullable(),
2457
+ sessions: z13.array(
2458
+ z13.object({
2459
+ id: z13.string(),
2460
+ mode: z13.enum(["pty", "json"]),
2461
+ state: z13.enum(sessionStateValues2),
2462
+ createdAt: z13.string(),
2463
+ name: z13.string().optional(),
2464
+ hasWorker: z13.boolean()
2465
+ })
2466
+ )
2467
+ }).strict(),
2468
+ // terminal → serve:终端标题变化,由 xterm onTitleChange 触发
2469
+ z13.object({
2470
+ type: z13.literal("pty_title_change"),
2471
+ sessionId: z13.string(),
2472
+ title: z13.string()
2473
+ }),
2474
+ // terminal → serve:shell 通过 OSC 7 报告的当前工作目录
2475
+ z13.object({
2476
+ type: z13.literal("pty_cwd_change"),
2477
+ sessionId: z13.string(),
2478
+ cwd: z13.string().min(1)
2479
+ }),
2480
+ // terminal → serve:local runtime 观察到的 PTY 语义事件。
2481
+ z13.object({
2482
+ type: z13.literal("pty_semantic_event"),
2483
+ sessionId: z13.string(),
2484
+ state: z13.enum(ptySemanticStateValues),
2485
+ seq: z13.number().int().nonnegative(),
2486
+ title: z13.string().optional(),
2487
+ tool: z13.string().optional()
2488
+ }),
2489
+ // terminal → serve:终端尺寸变化
2490
+ z13.object({
2491
+ type: z13.literal("pty_resize"),
2492
+ sessionId: z13.string(),
2493
+ cols: z13.number(),
2494
+ rows: z13.number(),
2495
+ // Shares the monotonic render-event sequence used by binary PTY frames and snapshots.
2496
+ outputSeq: z13.number().int().nonnegative()
2497
+ }),
2498
+ // serve → terminal worker:Web owns pure terminal geometry, so resize requests flow down.
2499
+ z13.object({
2500
+ type: z13.literal("pty_resize_request"),
2501
+ sessionId: z13.string(),
2502
+ cols: z13.number(),
2503
+ rows: z13.number()
2504
+ }),
2505
+ // serve → terminal:请求 HeadlessTerminal serialize() 快照
2506
+ z13.object({
2507
+ type: z13.literal("pty_subscribe"),
2508
+ sessionId: z13.string(),
2509
+ requestId: z13.string()
2510
+ }),
2511
+ // terminal → serve:serialize() 结果
2512
+ z13.object({
2513
+ type: z13.literal("pty_snapshot"),
2514
+ sessionId: z13.string(),
2515
+ cols: z13.number(),
2516
+ rows: z13.number(),
2517
+ data: z13.string(),
2518
+ outputSeq: z13.number().int().nonnegative(),
2519
+ requestId: z13.string()
2520
+ }),
2521
+ // serve → terminal:relay 连接状态变更,供终端给用户显示 remote viewing 是否通畅
2522
+ z13.object({
2523
+ type: z13.literal("bridge_status"),
2524
+ connected: z13.boolean()
2525
+ })
2526
+ ]);
2527
+ var WorkerMessageSchema = z13.discriminatedUnion("type", [
2528
+ // worker → serve: every socket connection begins with this protocol and process identity.
2529
+ // Readiness is reported separately because provider bootstrap can fail after IPC negotiation.
2530
+ z13.object({
2531
+ type: z13.literal("worker_protocol_hello"),
2532
+ protocolVersion: z13.literal(WORKER_IPC_PROTOCOL_VERSION),
2533
+ sessionId: z13.string().min(1),
2534
+ provider: z13.enum(providerValues),
2535
+ pid: z13.number().int().positive().max(Number.MAX_SAFE_INTEGER)
2536
+ }).strict(),
2537
+ // serve → worker: the worker also rejects a daemon from another IPC generation.
2538
+ z13.object({
2539
+ type: z13.literal("serve_protocol_hello"),
2540
+ protocolVersion: z13.literal(WORKER_IPC_PROTOCOL_VERSION),
2541
+ sessionId: z13.string().min(1),
2542
+ pid: z13.number().int().positive().max(Number.MAX_SAFE_INTEGER)
2543
+ }).strict(),
2544
+ // serve → worker: 发送用户输入给 claude
2545
+ z13.object({
2546
+ type: z13.literal("worker_input"),
2547
+ content: z13.string()
2548
+ }),
2549
+ // serve → worker: 停止 claude 进程(终止整个 JSON 会话)
2550
+ z13.object({
2551
+ type: z13.literal("worker_stop")
2552
+ }),
2553
+ // serve → worker: 只中断当前 provider turn,worker 进程保持可复用。
2554
+ z13.object({
2555
+ type: z13.literal("worker_interrupt")
2556
+ }),
2557
+ // serve → worker: 工具审批响应
2558
+ z13.object({
2559
+ type: z13.literal("worker_approval_response"),
2560
+ requestId: z13.string(),
2561
+ behavior: z13.enum(["allow", "deny"]),
2562
+ message: z13.string().optional(),
2563
+ remember: z13.boolean().optional(),
2564
+ optionId: z13.string().optional()
2565
+ }),
2566
+ // worker → serve: provider 输出事件(带序列号)
2567
+ z13.object({
2568
+ type: z13.literal("worker_event"),
2569
+ seq: z13.number(),
2570
+ event: z13.record(z13.string(), z13.unknown())
2571
+ }),
2572
+ // worker → serve: provider 进程退出
2573
+ z13.object({
2574
+ type: z13.literal("worker_exit"),
2575
+ code: z13.number(),
2576
+ errorTail: z13.string().max(2048).optional()
2577
+ }),
2578
+ // worker → serve: 当前 turn 已中断,JSON 会话仍可继续接收后续输入。
2579
+ z13.object({
2580
+ type: z13.literal("worker_interrupted")
2581
+ }),
2582
+ // worker → serve: provider 真正开始执行一个排队中的 turn(区别于仅接收输入)。
2583
+ z13.object({
2584
+ type: z13.literal("worker_turn_started")
2585
+ }),
2586
+ // worker → serve: 工具审批请求
2587
+ z13.object({
2588
+ type: z13.literal("worker_approval_request"),
2589
+ requestId: z13.string(),
2590
+ toolName: z13.string(),
2591
+ input: z13.record(z13.string(), z13.unknown()),
2592
+ options: z13.array(ApprovalOptionSchema).optional()
2593
+ }),
2594
+ // worker → serve: worker 就绪。Claude 在进程启动后发送;Codex/Kimi 分别在
2595
+ // app-server/ACP initialize + native session start|resume 完成后发送。
2596
+ z13.object({
2597
+ type: z13.literal("worker_ready"),
2598
+ pid: z13.number(),
2599
+ nativeSession: z13.object({
2600
+ provider: z13.enum(providerValues),
2601
+ sessionId: z13.string()
2602
+ }).optional()
2603
+ }),
2604
+ // Provider 在 worker_ready 之前失败时保留一小段脱敏后的诊断;可识别错误同时携带
2605
+ // 结构化 code,serve 不再只能把它降级成笼统的 WORKER_START_FAILED。
2606
+ z13.object({
2607
+ type: z13.literal("worker_startup_error"),
2608
+ provider: z13.enum(providerValues),
2609
+ message: z13.string().max(2048),
2610
+ errorCode: z13.literal(ControlErrorCode.SESSION_ALREADY_ACTIVE).optional(),
2611
+ nativeSessionId: z13.string().optional()
2612
+ }),
2613
+ // worker → serve: provider 原生会话 ID。
2614
+ z13.object({
2615
+ type: z13.literal("worker_native_session_id"),
2616
+ provider: z13.enum(providerValues),
2617
+ sessionId: z13.string()
2618
+ }),
2619
+ // serve → worker: 将指定工具加入会话白名单,后续同名工具自动审批
2620
+ z13.object({
2621
+ type: z13.literal("worker_whitelist_add"),
2622
+ toolName: z13.string()
2623
+ })
2624
+ ]);
2625
+ function serializeWorkerMsg(msg) {
2626
+ return JSON.stringify(msg) + "\n";
2627
+ }
2628
+ function createWorkerReader(stream, onMessage, onProtocolError) {
2629
+ const lineBuffer = new LineBuffer();
2630
+ lineBuffer.on("data", (line) => {
2631
+ const str = typeof line === "string" ? line : line.toString();
2632
+ if (str.length === 0) return;
2633
+ let raw;
2634
+ try {
2635
+ raw = JSON.parse(str);
2636
+ } catch (err) {
2637
+ onProtocolError(new Error("Worker message parse error", { cause: err }), str);
2638
+ return;
2639
+ }
2640
+ const result = WorkerMessageSchema.safeParse(raw);
2641
+ if (!result.success) {
2642
+ onProtocolError(new Error(`Worker message validation failed: ${result.error.message}`), str);
2643
+ return;
2644
+ }
2645
+ onMessage(result.data);
2646
+ });
2647
+ stream.pipe(lineBuffer);
2648
+ }
2649
+ function serializeIpc(msg) {
2650
+ return JSON.stringify(msg) + "\n";
2651
+ }
2652
+ function createIpcReader(stream, onMessage, onBinaryFrame, onProtocolError) {
2653
+ let buf = Buffer.alloc(0);
2654
+ let disposed = false;
2655
+ function drain() {
2656
+ while (buf.length > 0) {
2657
+ if (buf[0] === IPC_BINARY_MARKER) {
2658
+ if (buf.length < 5) return;
2659
+ const payloadLen = buf.readUInt32LE(1);
2660
+ const totalFrameLen = 1 + 4 + payloadLen;
2661
+ if (buf.length < totalFrameLen) return;
2662
+ const decoded = decodeBinaryFrame(buf.subarray(5, totalFrameLen));
2663
+ if (decoded && onBinaryFrame) {
2664
+ onBinaryFrame(decoded.sessionId, Buffer.from(decoded.data), decoded.outputSeq);
2665
+ }
2666
+ buf = buf.subarray(totalFrameLen);
2667
+ } else {
2668
+ const newlineIdx = buf.indexOf(10);
2669
+ if (newlineIdx === -1) return;
2670
+ const line = buf.subarray(0, newlineIdx).toString("utf-8");
2671
+ buf = buf.subarray(newlineIdx + 1);
2672
+ if (line.length === 0) continue;
2673
+ let raw;
2674
+ try {
2675
+ raw = JSON.parse(line);
2676
+ } catch (err) {
2677
+ onProtocolError(new Error("IPC message parse error", { cause: err }), line);
2678
+ continue;
2679
+ }
2680
+ const result = IpcMessageSchema.safeParse(raw);
2681
+ if (!result.success) {
2682
+ onProtocolError(
2683
+ new Error(`IPC message validation failed: ${result.error.message}`),
2684
+ line
2685
+ );
2686
+ continue;
2687
+ }
2688
+ onMessage(result.data);
2689
+ }
2690
+ }
2691
+ }
2692
+ function onData(chunk) {
2693
+ if (disposed) return;
2694
+ const incoming = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2695
+ buf = Buffer.concat([buf, incoming]);
2696
+ drain();
2697
+ }
2698
+ stream.on("data", onData);
2699
+ return () => {
2700
+ disposed = true;
2701
+ stream.off("data", onData);
2702
+ };
2703
+ }
2704
+
2705
+ export {
2706
+ IdSchema,
2707
+ providerValues,
2708
+ PTY_INITIAL_MIN_COLS,
2709
+ PTY_INITIAL_MIN_ROWS,
2710
+ PTY_INITIAL_MAX_COLS,
2711
+ PTY_INITIAL_MAX_ROWS,
2712
+ MessageEnvelopeSchema,
2713
+ WebPreviewNameSchema,
2714
+ TunnelProviderSchema,
2715
+ PreviewSourceSchema,
2716
+ DevicePreviewStreamServerMessageSchema,
2717
+ buildMessage,
2718
+ serializeControl,
2719
+ isCompactCommandText,
2720
+ summarizeToolActivity,
2721
+ ControlErrorCode,
2722
+ RELAY_CONTROL_PROTOCOL_VERSION,
2723
+ RelayControlSchema,
2724
+ SessionState,
2725
+ SESSION_CREATE_SERVER_DEADLINE_MS,
2726
+ RelayCloseCode,
2727
+ RELAY_JSON_MESSAGE_MAX_BYTES,
2728
+ encodeBinaryFrame,
2729
+ encodeFileStreamFrame,
2730
+ decodeFileStreamFrame,
2731
+ DEVICE_PREVIEW_FRAME_MAX_BYTES,
2732
+ encodeDevicePreviewFrame,
2733
+ encodeDevicePreviewH264ProxyPacket,
2734
+ createFSM,
2735
+ defineFSM,
2736
+ LineBuffer,
2737
+ WORKER_IPC_PROTOCOL_VERSION,
2738
+ TERMINAL_IPC_PROTOCOL_VERSION,
2739
+ encodeBinaryIpcFrame,
2740
+ serializeWorkerMsg,
2741
+ createWorkerReader,
2742
+ serializeIpc,
2743
+ createIpcReader
2744
+ };
2745
+ //# sourceMappingURL=chunk-RN3KQK6E.js.map