@kuafucloud/developer 0.0.0-stage → 0.1.9-alpha.3

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 (75) hide show
  1. package/dist/admin/admin/extension.zip +0 -0
  2. package/dist/admin/index.d.ts +2 -0
  3. package/dist/admin/index.js +2 -0
  4. package/dist/admin/meta/admin.json +59 -0
  5. package/dist/admin/meta/extension-manifest.json +794 -0
  6. package/dist/facade/index.d.ts +241 -0
  7. package/dist/facade/index.js +11 -0
  8. package/dist/monitor/runtime-services/app/index.js +660 -0
  9. package/dist/monitor/runtime-services/app/service-module.config.json +16 -0
  10. package/dist/monitor/runtime-services/app-simulator/index.js +648 -0
  11. package/dist/monitor/runtime-services/app-simulator/service-module.config.json +12 -0
  12. package/dist/monitor/runtime-services/mini-program/index.js +653 -0
  13. package/dist/monitor/runtime-services/mini-program/service-module.config.json +12 -0
  14. package/dist/monitor/runtime-services/mini-program-simulator/index.js +648 -0
  15. package/dist/monitor/runtime-services/mini-program-simulator/service-module.config.json +12 -0
  16. package/dist/monitor/runtime-services/site/index.js +648 -0
  17. package/dist/monitor/runtime-services/site/service-module.config.json +12 -0
  18. package/dist/public/monitor/index.js +6 -0
  19. package/dist/public/monitor/runtime-services/core/index.js +552 -0
  20. package/dist/public/realtime/host/index.js +4550 -0
  21. package/dist/public/realtime/index.js +3180 -0
  22. package/dist/public/realtime/native-preview-http/index.js +148 -0
  23. package/dist/simulation/artifact/meta/database.json +43 -0
  24. package/dist/simulation/artifact/meta/manifest.json +170 -0
  25. package/dist/simulation/artifact/meta/runtime-meta.json +28 -0
  26. package/dist/simulation/artifact/meta/schema.json +41 -0
  27. package/dist/simulation/artifact/server/worker/index.js +39 -0
  28. package/dist/simulation/artifact/server/worker/monitoring-contract.json +7 -0
  29. package/dist/simulation/index.d.ts +1 -0
  30. package/dist/simulation/index.js +1 -0
  31. package/dist/types/monitor/client/index.d.ts +4 -0
  32. package/dist/types/monitor/runtime-services/app/index.d.ts +4 -0
  33. package/dist/types/monitor/runtime-services/app-simulator/index.d.ts +4 -0
  34. package/dist/types/monitor/runtime-services/core/index.d.ts +1 -0
  35. package/dist/types/monitor/runtime-services/core/monitor-browser-service.d.ts +25 -0
  36. package/dist/types/monitor/runtime-services/core/monitor-mini-program-service.d.ts +25 -0
  37. package/dist/types/monitor/runtime-services/core/monitor-native-service.d.ts +25 -0
  38. package/dist/types/monitor/runtime-services/core/monitor-service.d.ts +35 -0
  39. package/dist/types/monitor/runtime-services/mini-program/index.d.ts +4 -0
  40. package/dist/types/monitor/runtime-services/mini-program-simulator/index.d.ts +4 -0
  41. package/dist/types/monitor/runtime-services/site/index.d.ts +4 -0
  42. package/dist/types/realtime/agent-chat-model.d.ts +216 -0
  43. package/dist/types/realtime/agent-question.d.ts +24 -0
  44. package/dist/types/realtime/developer-realtime.d.ts +158 -0
  45. package/dist/types/realtime/host/index.d.ts +28 -0
  46. package/dist/types/realtime/host-channels.d.ts +52 -0
  47. package/dist/types/realtime/host-connection.d.ts +131 -0
  48. package/dist/types/realtime/native-preview-http/index.d.ts +6 -0
  49. package/dist/types/realtime/native-source-codec.d.ts +21 -0
  50. package/dist/types/realtime/payload-fragments.d.ts +21 -0
  51. package/dist/types/realtime/preview-device.d.ts +9 -0
  52. package/dist/types/realtime/product-preview-cache.d.ts +69 -0
  53. package/dist/types/realtime/product-preview-clients.d.ts +7 -0
  54. package/dist/types/realtime/product-preview-host.d.ts +50 -0
  55. package/dist/types/realtime/product-preview-http-runtime.d.ts +9 -0
  56. package/dist/types/realtime/product-preview-protocol.d.ts +167 -0
  57. package/dist/types/realtime/product-preview-socket-source.d.ts +24 -0
  58. package/dist/types/realtime/product-preview-viewer-http.d.ts +41 -0
  59. package/dist/types/realtime/product-preview-viewer.d.ts +44 -0
  60. package/dist/types/realtime/project-workspaces.d.ts +43 -0
  61. package/dist/types/realtime/viewer/index.d.ts +22 -0
  62. package/dist/types/realtime/websocket-transport.d.ts +12 -0
  63. package/dist/types/realtime/workspace-agent-history.d.ts +46 -0
  64. package/dist/types/realtime/workspace-agent-input.d.ts +38 -0
  65. package/dist/types/realtime/workspace-agent-member.d.ts +15 -0
  66. package/dist/types/realtime/workspace-agent-view.d.ts +22 -0
  67. package/dist/types/realtime/workspace-cache-store.d.ts +38 -0
  68. package/dist/types/realtime/workspace-cache.d.ts +72 -0
  69. package/dist/types/realtime/workspace-chat-stream.d.ts +6 -0
  70. package/dist/types/realtime/workspace-file-view.d.ts +9 -0
  71. package/dist/types/realtime/workspace-status-view.d.ts +8 -0
  72. package/dist/types/realtime/workspace-viewer.d.ts +100 -0
  73. package/extension-manifest.json +457 -0
  74. package/package.json +112 -4
  75. package/README.md +0 -3
@@ -0,0 +1,4550 @@
1
+ // ../developer-realtime.ts
2
+ var DEVELOPER_REALTIME_VERSION = 1;
3
+ var DEVELOPER_REALTIME_LIMITS = {
4
+ frameBytes: 256 * 1024,
5
+ subscriptionsPerViewer: 8,
6
+ viewersPerHost: 32,
7
+ requestsPerViewer: 4,
8
+ requestTimeoutMs: 3e4,
9
+ socketBufferedBytes: 1024 * 1024,
10
+ productsPerWorkspace: 256
11
+ };
12
+ function emptyDeveloperWorkspaceView(phase = "offline", generation = null) {
13
+ return { phase, generation, streamId: null, sequence: -1, content: null };
14
+ }
15
+ function developerWorkspaceUnavailable(state) {
16
+ return state.phase === "offline" || state.phase === "connecting";
17
+ }
18
+ function reduceDeveloperWorkspaceView(state, subscriptionId, frame, applyEvent) {
19
+ if (frame.type === "ready" || frame.type === "host-state") {
20
+ return emptyDeveloperWorkspaceView(frame.generation ? "connecting" : "offline", frame.generation);
21
+ }
22
+ if (frame.type === "error" && (!frame.subscriptionId || frame.subscriptionId === subscriptionId) && !frame.requestId) {
23
+ const phase = frame.code === "developer.workspace_removed" ? "missing" : frame.code === "developer.workspace_forbidden" || frame.code === "developer.authorization_expired" ? "forbidden" : "failed";
24
+ return { ...emptyDeveloperWorkspaceView(phase, state.generation), errorCode: frame.code };
25
+ }
26
+ if (frame.type !== "snapshot" && frame.type !== "event" || frame.subscriptionId !== subscriptionId || frame.generation !== state.generation) return state;
27
+ if (frame.type === "snapshot") {
28
+ if (frame.streamId === state.streamId && frame.sequence <= state.sequence) return state;
29
+ return { phase: "ready", generation: frame.generation, streamId: frame.streamId, sequence: frame.sequence, content: frame.payload };
30
+ }
31
+ if (state.phase !== "ready" || frame.streamId !== state.streamId || frame.sequence <= state.sequence) return state;
32
+ if (frame.sequence !== state.sequence + 1) return emptyDeveloperWorkspaceView("connecting", state.generation);
33
+ try {
34
+ return { ...state, sequence: frame.sequence, content: applyEvent(state.content, frame.payload) };
35
+ } catch {
36
+ return { ...emptyDeveloperWorkspaceView("failed", state.generation), errorCode: "developer.content_invalid" };
37
+ }
38
+ }
39
+
40
+ // ../host-channels.ts
41
+ import { normalizeWorkspaceId as normalizeWorkspaceId2 } from "@kuafucloud/product-runtime-protocol";
42
+
43
+ // ../product-preview-protocol.ts
44
+ import { buildApiPath } from "@kuafucloud/product-runtime-protocol";
45
+ import { normalizeWorkspaceCodebasePath, normalizeWorkspaceId, normalizeWorkspaceRepositoryId, parsePersistentWorkspacePublicPath, isProductPreviewStaticRuntimePath } from "@kuafucloud/product-runtime-protocol";
46
+ var PRODUCT_PREVIEW_LIMITS = {
47
+ chunkBytes: 64 * 1024,
48
+ windowChunks: 2,
49
+ streamsPerSession: 4,
50
+ streamsPerHost: 16,
51
+ requestBodyBytes: 1024 * 1024,
52
+ headerBytes: 16 * 1024,
53
+ attachmentBytes: 8 * 1024,
54
+ openTimeoutMs: 3e4,
55
+ prepareTimeoutMs: 15 * 6e4,
56
+ serviceSocketFrameBytes: 32 * 1024
57
+ };
58
+ var previewFailureCodes = /* @__PURE__ */ new Set([
59
+ "developer.preview_prepare_failed",
60
+ "developer.preview_forbidden",
61
+ "developer.preview_invalid",
62
+ "developer.preview_limit",
63
+ "developer.channel_timeout",
64
+ "developer.channel_capacity",
65
+ "developer.channel_cancelled",
66
+ "developer.channel_disconnected",
67
+ "developer.channel_forbidden",
68
+ "developer.channel_unavailable",
69
+ "developer.workspace_removed",
70
+ "developer.control_replaced",
71
+ "developer.host_offline",
72
+ "developer.transport_unavailable",
73
+ "developer.preview_open_timeout",
74
+ "workspace.codebase_unprepared",
75
+ "workspace.codebase_runtime_not_ready",
76
+ "workspace.preview_cache_outdated",
77
+ "workspace.preview_build_failed",
78
+ "workspace.preview_build_pending"
79
+ ]);
80
+ function readProductPreviewFailureCode(error) {
81
+ const value = error && typeof error === "object" ? error : {};
82
+ return [value.code, value.message].find((code) => typeof code === "string" && previewFailureCodes.has(code)) ?? "developer.preview_prepare_failed";
83
+ }
84
+ function buildProductPreviewSocketUrl(origin, input) {
85
+ const base = new URL(origin), target = readProductPreviewTarget(input.target);
86
+ if (!["https:", "wss:"].includes(base.protocol) || base.username || base.password || base.search || base.hash || base.pathname !== "/" || !/^[1-9]\d*$/u.test(input.projectId) || !Number.isSafeInteger(Number(input.projectId)) || !/^[A-Za-z0-9_-]{1,160}$/u.test(input.hostDeviceId)) return invalid();
87
+ base.protocol = "wss:";
88
+ base.pathname = buildApiPath({ projectId: input.projectId, projectEnvKey: "prod", extensionId: "developer" }, "/runtime/developer/socket");
89
+ for (const [key, value] of Object.entries({ hostDeviceId: input.hostDeviceId, ...target })) base.searchParams.set(key, value);
90
+ return base.href;
91
+ }
92
+ function readProductPreviewSocketUrl(text2) {
93
+ const url = new URL(text2), match = /^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/socket$/u.exec(url.pathname);
94
+ if (!["https:", "wss:"].includes(url.protocol) || url.username || url.password || url.hash || !match || text2.length > 4096) return invalid();
95
+ const keys = [...url.searchParams.keys()];
96
+ if (new Set(keys).size !== keys.length || keys.some((key) => !["hostDeviceId", "workspaceId", "repositoryId", "codebasePath", "productId", "kind", "surface", "platform"].includes(key))) return invalid();
97
+ const { hostDeviceId, ...raw } = Object.fromEntries(url.searchParams), target = readProductPreviewTarget(raw);
98
+ if (!hostDeviceId || !/^[A-Za-z0-9_-]{1,160}$/u.test(hostDeviceId) || !Number.isSafeInteger(Number(match[1]))) return invalid();
99
+ return { projectId: match[1], hostDeviceId, target };
100
+ }
101
+ var invalid = () => {
102
+ throw new Error("developer.preview_invalid");
103
+ };
104
+ var PRODUCT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
105
+ function isValidProductId(value) {
106
+ return typeof value === "string" && PRODUCT_ID_PATTERN.test(value);
107
+ }
108
+ function isSafePathSegment(segment) {
109
+ if (!segment || segment === "." || segment === ".." || /%(?:2e|2f|5c)/iu.test(segment)) {
110
+ return false;
111
+ }
112
+ let decoded;
113
+ try {
114
+ decoded = decodeURIComponent(segment);
115
+ } catch {
116
+ return false;
117
+ }
118
+ return Boolean(decoded) && decoded !== "." && decoded !== ".." && !/%(?:2e|2f|5c)/iu.test(decoded) && !/[\\/\u0000-\u001f\u007f]/u.test(decoded);
119
+ }
120
+ function hasValidSubpathSegments(subpath) {
121
+ return Boolean(subpath) && subpath.split("/").every(isSafePathSegment);
122
+ }
123
+ function isValidExtensionArtifactPath(pathname, projectId, workspaceId) {
124
+ const prefix = "/preview/artifacts/extensions/";
125
+ if (!pathname.startsWith(prefix)) return false;
126
+ const parts = pathname.slice(prefix.length).split("/");
127
+ if (parts.length < 6) return false;
128
+ const [extId, routeProjectId, runtimeKey, scene, channel, ...rest] = parts;
129
+ return isValidProductId(extId) && routeProjectId === projectId && runtimeKey === `preview-workspace-${workspaceId}` && scene === "browser" && channel === "current" && rest.every(isSafePathSegment);
130
+ }
131
+ function readProductPreviewVersion(raw) {
132
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
133
+ const value = raw;
134
+ if (Object.keys(value).some((key) => !["status", "buildId", "metadataDigest"].includes(key)) || !["building", "ready", "failed"].includes(String(value.status)) || value.buildId !== void 0 && (typeof value.buildId !== "string" || !value.buildId || value.buildId.length > 1024 || /[\u0000-\u001f\u007f]/u.test(value.buildId)) || value.metadataDigest !== void 0 && (value.status !== "ready" || typeof value.buildId !== "string" || typeof value.metadataDigest !== "string" || !/^[a-f0-9]{64}$/u.test(value.metadataDigest))) return invalid();
135
+ return {
136
+ status: value.status,
137
+ ...value.buildId ? { buildId: value.buildId } : {},
138
+ ...value.metadataDigest ? { metadataDigest: value.metadataDigest } : {}
139
+ };
140
+ }
141
+ function readProductPreviewTarget(raw) {
142
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
143
+ const value = raw;
144
+ if (Object.keys(value).some((key) => !["workspaceId", "repositoryId", "codebasePath", "productId", "kind", "surface", "platform"].includes(key)) || typeof value.workspaceId !== "string" || typeof value.repositoryId !== "string" || typeof value.codebasePath !== "string" || value.codebasePath.length > 1024 || !isValidProductId(value.productId) || typeof value.kind !== "string" || !["app", "site", "mini-program", "extension", "desktop"].includes(value.kind) || typeof value.surface !== "string" || !["browser", "native"].includes(value.surface)) return invalid();
145
+ if (value.surface === "native" ? value.kind !== "app" || typeof value.platform !== "string" || !["ios", "android"].includes(value.platform) : value.platform !== void 0) return invalid();
146
+ return {
147
+ workspaceId: normalizeWorkspaceId(value.workspaceId),
148
+ repositoryId: normalizeWorkspaceRepositoryId(value.repositoryId),
149
+ codebasePath: normalizeWorkspaceCodebasePath(value.codebasePath),
150
+ productId: value.productId,
151
+ kind: value.kind,
152
+ surface: value.surface,
153
+ ...value.platform ? { platform: value.platform } : {}
154
+ };
155
+ }
156
+ function encodeProductPreviewChunk(streamId, sequence, payload) {
157
+ if (!validStream(streamId) || !validSequence(sequence) || !payload.byteLength || payload.byteLength > PRODUCT_PREVIEW_LIMITS.chunkBytes) return invalid();
158
+ const buffer = new ArrayBuffer(10 + payload.byteLength), header = new DataView(buffer);
159
+ header.setUint8(0, 75);
160
+ header.setUint8(1, 1);
161
+ header.setUint32(2, streamId);
162
+ header.setUint32(6, sequence);
163
+ new Uint8Array(buffer, 10).set(payload);
164
+ return buffer;
165
+ }
166
+ function decodeProductPreviewChunk(raw) {
167
+ if (!(raw instanceof ArrayBuffer) || raw.byteLength <= 10 || raw.byteLength > PRODUCT_PREVIEW_LIMITS.chunkBytes + 10) return invalid();
168
+ const header = new DataView(raw), streamId = header.getUint32(2), sequence = header.getUint32(6);
169
+ if (header.getUint8(0) !== 75 || header.getUint8(1) !== 1 || !validStream(streamId)) return invalid();
170
+ return { streamId, sequence, payload: new Uint8Array(raw, 10) };
171
+ }
172
+ function validStream(value) {
173
+ return Number.isInteger(value) && Number(value) > 0 && Number(value) <= 4294967295;
174
+ }
175
+ function validSequence(value) {
176
+ return Number.isInteger(value) && Number(value) >= 0 && Number(value) <= 4294967295;
177
+ }
178
+ function productPreviewHeaders(headers, response = false, productCredentials = false) {
179
+ const result = [];
180
+ const cookieReader = headers.getSetCookie;
181
+ for (const [rawName, value] of headers) {
182
+ const name = rawName.toLowerCase();
183
+ const runtimeAuthScope = !response && name === "x-kuafu-runtime-auth-scope" && (value === "account" || value === "admin");
184
+ const storyRunHeader = !response && name === "x-kuafu-story-run" && /^[a-zA-Z0-9._-]{1,128}$/u.test(value);
185
+ const documentVersion = response && name === "x-kuafu-preview-document-version" && /^[a-f0-9]{64}$/u.test(value);
186
+ if (/^(?:host|connection|upgrade|proxy-.*|keep-alive|transfer-encoding|te|trailer|sec-websocket-.*)$/u.test(name) || !productCredentials && (name === "authorization" || name === "cookie") || name.startsWith("x-kuafu-") && !runtimeAuthScope && !storyRunHeader && !documentVersion || name.startsWith("x-platform-") || name.startsWith("x-project-") || name === "x-devmanager-auth-profile" || name === "set-cookie" && (!response || typeof cookieReader === "function")) continue;
187
+ result.push([name, value]);
188
+ }
189
+ if (response && typeof cookieReader === "function") for (const value of cookieReader.call(headers)) result.push(["set-cookie", value]);
190
+ if (new TextEncoder().encode(JSON.stringify(result)).byteLength > PRODUCT_PREVIEW_LIMITS.headerBytes) return invalid();
191
+ return result;
192
+ }
193
+ function assertProductPreviewRequest(input) {
194
+ const { session, projectId, hostDeviceId, method, path } = input;
195
+ if (typeof path !== "string" || path.length > 8192 || !path.startsWith("/") || path.startsWith("//") || path.includes("\\") || /[\u0000-\u0020\u007f]/u.test(path) || path.split(/[?#]/, 1)[0].split("/").some((part) => /^(?:\.|%2e){1,2}$/iu.test(part)) || !["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].includes(method)) return invalid();
196
+ const url = new URL(path, session.publicOrigin), scope = parsePersistentWorkspacePublicPath(url), target = session.target;
197
+ if (!scope || scope.projectId !== projectId || scope.envKey !== "prod" || scope.workspaceId !== target.workspaceId || scope.codebaseRuntime?.repositoryId !== target.repositoryId || scope.codebaseRuntime.relativePath !== target.codebasePath || url.hash) return invalid();
198
+ if (session.stableTarget) {
199
+ const remote = scope.remoteProduct;
200
+ if (!remote || remote.hostDeviceId !== hostDeviceId || remote.kind !== target.kind || remote.productId !== target.productId || remote.surface !== target.surface || remote.platform !== target.platform) return invalid();
201
+ } else if (scope.remotePreview?.hostDeviceId !== hostDeviceId || scope.remotePreview.sessionId !== session.sessionId) return invalid();
202
+ const route = new URL(scope.runtimePath, "https://preview.invalid"), pathname = route.pathname;
203
+ if (scope.runtimePath.startsWith("//") || route.origin !== "https://preview.invalid") return invalid();
204
+ if (!route.search && (method === "GET" && pathname === "/runtime/services/im/v1/socket" || ["POST", "OPTIONS"].includes(method) && /^\/runtime\/services\/im\/v1\/(?:access|command|history|snapshot|sync|directory|member|message|readers)$/u.test(pathname))) return;
205
+ const read = method === "GET" || method === "HEAD";
206
+ if (read && !route.search && target.surface === "browser" && (target.kind === "site" || target.kind === "mini-program") && isProductPreviewStaticRuntimePath(pathname, { ...target, kind: target.kind })) return;
207
+ const productPath = `/${target.kind}/${encodeURIComponent(target.productId)}`;
208
+ const folder = target.kind === "desktop" ? "desktops" : target.kind === "app" ? "apps" : target.kind === "site" ? "sites" : target.kind === "mini-program" ? "mini-programs" : "extensions";
209
+ const artifactPrefix = `/preview/artifacts/${folder}/${encodeURIComponent(target.productId)}/`;
210
+ if (read && (pathname === productPath || pathname.startsWith(`${productPath}/`) || target.kind !== "extension" && pathname.startsWith(artifactPrefix) && hasValidSubpathSegments(pathname.slice(artifactPrefix.length)) || target.kind === "extension" && isValidExtensionArtifactPath(pathname, projectId, target.workspaceId) || target.kind === "extension" && (pathname === "/admin-simulator/" || pathname.startsWith("/admin-simulator/") && hasValidSubpathSegments(pathname.slice("/admin-simulator/".length))) || ["/assets/", "/preview/browser/"].some((prefix) => pathname.startsWith(prefix)) || pathname === "/products/nav")) return;
211
+ if (read && pathname === "/preview/status" && route.searchParams.getAll("observe").length === 1 && route.searchParams.get("observe") === "1" && route.searchParams.getAll("productKind").length === 1 && route.searchParams.get("productKind") === target.kind && route.searchParams.getAll("scene").length === 1 && route.searchParams.get("scene") === target.surface && route.searchParams.getAll("productId").length === 1 && !route.searchParams.has("rebuild") && !route.searchParams.has("complete") && (target.kind === "extension" ? target.surface === "browser" && isValidProductId(route.searchParams.get("productId")) : route.searchParams.get("productId") === target.productId)) return;
212
+ if (pathname.startsWith(buildApiPath({ projectId, projectEnvKey: "test000000", extensionId: "" }, "").slice(0, -1)) && !pathname.slice(buildApiPath({ projectId, projectEnvKey: "test000000", extensionId: "" }, "").slice(0, -1).length).split("/").some((part) => !part || part === "." || part === "..")) return;
213
+ if (read && ["/auth/profiles", "/auth/current"].includes(pathname) || method === "POST" && pathname === "/auth/select") return;
214
+ if (target.surface === "browser" || target.surface === "native") {
215
+ if (read && (pathname === "/story/catalog" || pathname === "/story/status" || /^\/story\/bundles\/[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+\.mjs$/u.test(pathname) || /^\/story\/runs\/[a-zA-Z0-9._-]+$/u.test(pathname))) return;
216
+ if (method === "POST" && (pathname === "/story/runs" || /^\/story\/runs\/[a-zA-Z0-9._-]+\/(?:heartbeat|reset|report|cancel)$/u.test(pathname))) return;
217
+ if (pathname === "/story-env/" || pathname.startsWith("/story-env/") && hasValidSubpathSegments(pathname.slice("/story-env/".length).replace(/\/$/u, ""))) return;
218
+ }
219
+ return invalid();
220
+ }
221
+
222
+ // ../host-channels.ts
223
+ var DEVELOPER_CHANNEL_LIMITS = {
224
+ businessChannels: 16,
225
+ streams: 16,
226
+ queuedBytes: 64 * 1024 * 1024,
227
+ handshakeMs: 15e3,
228
+ idleMs: 3e4
229
+ };
230
+ function readDeveloperChannelTarget(raw) {
231
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("developer.channel_invalid");
232
+ const value = raw;
233
+ if (value.kind === "workspace-events" && Object.keys(value).sort().join(",") === "kind,workspaceId" && typeof value.workspaceId === "string")
234
+ return { kind: value.kind, workspaceId: normalizeWorkspaceId2(value.workspaceId) };
235
+ if (value.kind === "product-preview" && Object.keys(value).sort().join(",") === "kind,product")
236
+ return { kind: value.kind, product: readProductPreviewTarget(value.product) };
237
+ throw new Error("developer.channel_invalid");
238
+ }
239
+ function developerChannelKey(target) {
240
+ return JSON.stringify(readDeveloperChannelTarget(target));
241
+ }
242
+ function developerChannelWorkspace(target) {
243
+ return target.kind === "workspace-events" ? target.workspaceId : target.product.workspaceId;
244
+ }
245
+ function readDeveloperChannelGrant(raw) {
246
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("developer.channel_invalid");
247
+ const value = raw;
248
+ if (![value.controlEpoch, value.channelId].every((value2) => typeof value2 === "string" && uuid(value2)) || typeof value.nonce !== "string" || !/^[a-f0-9]{32}$/u.test(value.nonce)) throw new Error("developer.channel_invalid");
249
+ return { controlEpoch: value.controlEpoch, channelId: value.channelId, nonce: value.nonce, target: readDeveloperChannelTarget(value.target) };
250
+ }
251
+ function uuid(value) {
252
+ return /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u.test(value);
253
+ }
254
+ var DeveloperHostBudget = class {
255
+ channels = 0;
256
+ streams = 0;
257
+ bytes = 0;
258
+ acquireChannel() {
259
+ return this.take("channels", 1, DEVELOPER_CHANNEL_LIMITS.businessChannels);
260
+ }
261
+ acquireStream() {
262
+ return this.take("streams", 1, DEVELOPER_CHANNEL_LIMITS.streams);
263
+ }
264
+ acquireBytes(bytes) {
265
+ if (!Number.isSafeInteger(bytes) || bytes < 0) throw new Error("developer.channel_budget_invalid");
266
+ return this.take("bytes", bytes, DEVELOPER_CHANNEL_LIMITS.queuedBytes);
267
+ }
268
+ snapshot() {
269
+ return { channels: this.channels, streams: this.streams, bytes: this.bytes };
270
+ }
271
+ take(key, count, maximum) {
272
+ if (this[key] + count > maximum) throw new Error("developer.channel_capacity");
273
+ this[key] += count;
274
+ let released = false;
275
+ return () => {
276
+ if (!released) {
277
+ released = true;
278
+ this[key] -= count;
279
+ }
280
+ };
281
+ }
282
+ };
283
+
284
+ // ../product-preview-host.ts
285
+ import { buildPersistentWorkspacePublicOrigin as buildPersistentWorkspacePublicOrigin2, isProductPreviewStaticRuntimePath as isProductPreviewStaticRuntimePath2, parsePersistentWorkspacePublicPath as parsePersistentWorkspacePublicPath2 } from "@kuafucloud/product-runtime-protocol";
286
+
287
+ // ../native-source-codec.ts
288
+ import { buildPersistentWorkspacePublicOrigin } from "@kuafucloud/product-runtime-protocol";
289
+ function readDeveloperNativePreviewSource(raw, context) {
290
+ const fail = () => {
291
+ throw new Error("developer.native_preview_source_invalid");
292
+ };
293
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return fail();
294
+ const value = raw, { session, projectId, hostDeviceId } = context, target = session.target;
295
+ const keys = ["sourceId", "indexUrl", "indexDigest", "previewBaseUrl", "projectId", "workspaceId", "repositoryId", "codebasePath", "productId", "release", "environmentKey", "buildVariant"];
296
+ if (Object.keys(value).length !== keys.length || keys.some((key) => typeof value[key] !== "string" || !value[key]) || target.kind !== "app" || target.surface !== "native" || !target.platform || value.projectId !== projectId || value.workspaceId !== target.workspaceId || value.repositoryId !== target.repositoryId || value.codebasePath !== target.codebasePath || value.productId !== target.productId || value.environmentKey !== "test000000" || value.buildVariant !== target.platform || !/^preview-[a-z0-9._-]{1,120}$/u.test(value.sourceId) || value.sourceId.includes("..") || !/^[a-f0-9]{64}$/u.test(value.indexDigest) || !/^0\.0\.0-preview\.[a-z0-9.-]{1,160}$/u.test(value.release)) return fail();
297
+ const base = buildPersistentWorkspacePublicOrigin(session.publicOrigin, {
298
+ projectId,
299
+ envKey: "prod",
300
+ workspaceId: target.workspaceId,
301
+ codebaseRuntime: { repositoryId: target.repositoryId, relativePath: target.codebasePath },
302
+ ...session.stableTarget ? { remoteProduct: { hostDeviceId, kind: target.kind, productId: target.productId, surface: target.surface, platform: target.platform } } : { remotePreview: { hostDeviceId, sessionId: session.sessionId } }
303
+ });
304
+ if (value.previewBaseUrl !== base) return fail();
305
+ const index = new URL(value.indexUrl), prefix = `${base}/preview/artifacts/apps/${encodeURIComponent(target.productId)}/${projectId}/preview-workspace-${target.workspaceId}/app/versions/`;
306
+ if (index.protocol !== "https:" || index.href !== value.indexUrl || index.search || index.hash || index.username || index.password || !index.href.startsWith(prefix) || !/^[a-f0-9]{64}\/[a-f0-9]{32}\/source-index\.json$/u.test(index.href.slice(prefix.length))) return fail();
307
+ return {
308
+ sourceId: value.sourceId,
309
+ indexUrl: index.href,
310
+ indexDigest: value.indexDigest,
311
+ previewBaseUrl: base,
312
+ projectId,
313
+ workspaceId: target.workspaceId,
314
+ repositoryId: target.repositoryId,
315
+ codebasePath: target.codebasePath,
316
+ productId: target.productId,
317
+ release: value.release,
318
+ environmentKey: "test000000",
319
+ buildVariant: target.platform
320
+ };
321
+ }
322
+
323
+ // ../product-preview-socket-source.ts
324
+ var ProductPreviewSocketSource = class {
325
+ constructor(ports) {
326
+ this.ports = ports;
327
+ }
328
+ sockets = /* @__PURE__ */ new Map();
329
+ receive(frame) {
330
+ if (frame.type === "preview.socket.open") {
331
+ if (!validStream(frame.streamId) || this.sockets.has(frame.streamId)) throw new Error("developer.preview_invalid");
332
+ if ([...this.sockets.values()].filter((entry3) => entry3.sessionId === frame.sessionId).length >= PRODUCT_PREVIEW_LIMITS.streamsPerSession) throw new Error("developer.preview_limit");
333
+ const release = this.ports.budget.acquireStream();
334
+ const entry2 = {
335
+ sessionId: frame.sessionId,
336
+ generation: frame.generation,
337
+ opened: false,
338
+ release,
339
+ timer: setTimeout(() => this.finish(frame.streamId, 1013), PRODUCT_PREVIEW_LIMITS.openTimeoutMs)
340
+ };
341
+ this.sockets.set(frame.streamId, entry2);
342
+ void this.ports.open(frame).then((socket) => {
343
+ if (this.sockets.get(frame.streamId) !== entry2) {
344
+ socket.close(1e3, "preview closed");
345
+ return;
346
+ }
347
+ entry2.socket = socket;
348
+ const opened = () => {
349
+ if (this.sockets.get(frame.streamId) !== entry2) return;
350
+ if (socket.protocol !== "kuafu.im.v1") {
351
+ this.finish(frame.streamId, 1002);
352
+ return;
353
+ }
354
+ entry2.opened = true;
355
+ clearTimeout(entry2.timer);
356
+ this.ports.send({ type: "preview.socket.opened", generation: entry2.generation, streamId: frame.streamId, protocol: socket.protocol });
357
+ };
358
+ const message = (event) => {
359
+ if (this.sockets.get(frame.streamId) !== entry2) return;
360
+ if (!entry2.opened || !validServiceSocketText(event.data)) {
361
+ this.finish(frame.streamId, 1009);
362
+ return;
363
+ }
364
+ this.ports.send({ type: "preview.socket.data", generation: entry2.generation, streamId: frame.streamId, data: event.data });
365
+ };
366
+ const closed = () => this.finish(frame.streamId, 1012);
367
+ socket.addEventListener("open", opened);
368
+ socket.addEventListener("message", message);
369
+ socket.addEventListener("close", closed);
370
+ socket.addEventListener("error", closed);
371
+ entry2.detach = () => {
372
+ socket.removeEventListener("open", opened);
373
+ socket.removeEventListener("message", message);
374
+ socket.removeEventListener("close", closed);
375
+ socket.removeEventListener("error", closed);
376
+ };
377
+ if (socket.readyState === 1) opened();
378
+ else if (socket.readyState !== 0) this.finish(frame.streamId, 1012);
379
+ }, () => this.finish(frame.streamId, 1011)).catch(() => this.finish(frame.streamId, 1011));
380
+ return;
381
+ }
382
+ const entry = this.sockets.get(frame.streamId);
383
+ if (!entry || frame.generation !== entry.generation) return;
384
+ if (frame.type === "preview.socket.close") {
385
+ this.finish(frame.streamId, 1e3, false);
386
+ return;
387
+ }
388
+ if (!entry.opened || !validServiceSocketText(frame.data) || !entry.socket || entry.socket.readyState !== 1 || entry.socket.bufferedAmount > PRODUCT_PREVIEW_LIMITS.serviceSocketFrameBytes * 2) {
389
+ this.finish(frame.streamId, 1009);
390
+ return;
391
+ }
392
+ try {
393
+ entry.socket.send(frame.data);
394
+ } catch {
395
+ this.finish(frame.streamId, 1011);
396
+ }
397
+ }
398
+ close(sessionId) {
399
+ for (const [id3, entry] of [...this.sockets]) if (!sessionId || entry.sessionId === sessionId) this.finish(id3, 1e3);
400
+ }
401
+ finish(id3, code, notify = true) {
402
+ const entry = this.sockets.get(id3);
403
+ if (!entry) return;
404
+ this.sockets.delete(id3);
405
+ clearTimeout(entry.timer);
406
+ entry.detach?.();
407
+ entry.release();
408
+ try {
409
+ entry.socket?.close(1e3, "preview closed");
410
+ } catch {
411
+ this.ports.diagnostic("developer.preview_socket_release_failed");
412
+ }
413
+ if (notify) try {
414
+ this.ports.send({ type: "preview.socket.close", generation: entry.generation, streamId: id3, code });
415
+ } catch {
416
+ this.ports.diagnostic("developer.preview_socket_notification_failed");
417
+ }
418
+ }
419
+ };
420
+ function validServiceSocketText(value) {
421
+ return typeof value === "string" && value.length <= PRODUCT_PREVIEW_LIMITS.serviceSocketFrameBytes && new TextEncoder().encode(value).byteLength <= PRODUCT_PREVIEW_LIMITS.serviceSocketFrameBytes;
422
+ }
423
+
424
+ // ../product-preview-host.ts
425
+ var DeveloperProductPreviewHost = class {
426
+ constructor(ports) {
427
+ this.ports = ports;
428
+ this.budget = ports.budget ?? new DeveloperHostBudget();
429
+ this.serviceSockets = new ProductPreviewSocketSource({
430
+ budget: this.budget,
431
+ send: (frame) => ports.send(frame),
432
+ diagnostic: ports.diagnostic,
433
+ open: async (frame) => {
434
+ const session = this.sessions.get(frame.sessionId);
435
+ if (!session || !this.current(session)) throw new Error("developer.preview_closed");
436
+ assertProductPreviewRequest({ session: session.value, ...this.ports, method: "GET", path: frame.path });
437
+ const scope = parsePersistentWorkspacePublicPath2(new URL(frame.path, session.value.publicOrigin));
438
+ if (scope?.runtimePath !== "/runtime/services/im/v1/socket") throw new Error("developer.preview_invalid");
439
+ const lease = await session.lease;
440
+ if (!this.current(session) || !lease.openServiceSocket) throw new Error("developer.preview_closed");
441
+ return lease.openServiceSocket(frame.path, frame.protocols);
442
+ }
443
+ });
444
+ }
445
+ generation;
446
+ sessions = /* @__PURE__ */ new Map();
447
+ streams = /* @__PURE__ */ new Map();
448
+ cleanup = /* @__PURE__ */ new Set();
449
+ budget;
450
+ serviceSockets;
451
+ resources = /* @__PURE__ */ new Map();
452
+ resourceCleanup = /* @__PURE__ */ new Set();
453
+ resume() {
454
+ for (const id3 of [...this.streams.keys()]) this.cancel(id3);
455
+ }
456
+ reset(generation) {
457
+ this.serviceSockets.close();
458
+ this.generation = generation;
459
+ const work = [...this.sessions.values()].flatMap((session) => [...session.work]);
460
+ for (const id3 of [...this.sessions.keys()]) this.releaseSession(id3);
461
+ const resources = [...this.resources.values()];
462
+ this.resources.clear();
463
+ for (const resource of resources) {
464
+ resource.abort.abort();
465
+ let pending;
466
+ const release = () => {
467
+ if (!pending) {
468
+ pending = Promise.allSettled(work).then(() => resource.lease).then((lease) => lease.release(), () => {
469
+ });
470
+ void pending.then(() => this.resourceCleanup.delete(release), () => {
471
+ pending = void 0;
472
+ });
473
+ }
474
+ return pending;
475
+ };
476
+ this.resourceCleanup.add(release);
477
+ void release().catch(() => this.ports.diagnostic("developer.preview_release_failed"));
478
+ }
479
+ }
480
+ async close() {
481
+ this.reset();
482
+ const results = await Promise.allSettled([...this.cleanup, ...this.resourceCleanup].map((release) => release()));
483
+ const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
484
+ if (errors.length) throw new AggregateError(errors, "developer.preview_release_failed");
485
+ }
486
+ /** 返回false时由原Developer协议处理;preview帧不能降级为普通Agent输入。 */
487
+ receive(raw) {
488
+ if (raw instanceof ArrayBuffer) {
489
+ const frame2 = decodeProductPreviewChunk(raw), stream = this.streams.get(frame2.streamId);
490
+ if (!stream) return true;
491
+ if (stream.started || frame2.sequence !== stream.sequence || stream.received + frame2.payload.byteLength > stream.expected) {
492
+ this.cancel(frame2.streamId);
493
+ return true;
494
+ }
495
+ stream.sequence++;
496
+ stream.received += frame2.payload.byteLength;
497
+ stream.chunks.push(frame2.payload);
498
+ if (stream.received < stream.expected) this.ports.send({ type: "preview.http.credit", streamId: frame2.streamId, chunks: 1 });
499
+ return true;
500
+ }
501
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || !("type" in raw) || typeof raw.type !== "string" || !raw.type.startsWith("preview.")) return false;
502
+ const frame = raw;
503
+ if (frame.type === "preview.socket.open" || frame.type === "preview.socket.data" || frame.type === "preview.socket.close") {
504
+ if (frame.generation === this.generation) this.serviceSockets.receive(frame);
505
+ return true;
506
+ }
507
+ if (frame.type === "preview.prepare") {
508
+ if (frame.generation !== this.generation) return true;
509
+ const target = readProductPreviewTarget(frame.session?.target), url = new URL(frame.session.publicOrigin);
510
+ if (!this.ports.ownsWorkspace(target.workspaceId) || url.protocol !== "https:" || url.origin !== frame.session.publicOrigin || !/^[0-9a-f-]{36}$/u.test(frame.session.sessionId)) throw new Error("developer.preview_forbidden");
511
+ const previous = this.sessions.get(frame.session.sessionId);
512
+ if (previous) {
513
+ if (JSON.stringify(previous.value) !== JSON.stringify(frame.session)) throw new Error("developer.preview_scope_changed");
514
+ this.prepared(frame.generation, previous);
515
+ return true;
516
+ }
517
+ if (this.sessions.size >= 32) throw new Error("developer.preview_limit");
518
+ const abort = new AbortController(), value = { ...frame.session, target };
519
+ const resourceKey = value.mode === "observe" ? "observe" : "prepare";
520
+ let resource = this.resources.get(resourceKey);
521
+ if ([...this.resources.values()].some((item) => JSON.stringify(item.value.target) !== JSON.stringify(target))) throw new Error("developer.preview_scope_changed");
522
+ if (!resource) {
523
+ const resourceAbort = new AbortController();
524
+ resource = { value, abort: resourceAbort, lease: Promise.resolve().then(() => this.ports.prepare(value, resourceAbort.signal)).then(async (lease) => {
525
+ try {
526
+ return this.sharedLease(lease);
527
+ } catch (error) {
528
+ await lease.release();
529
+ throw error;
530
+ }
531
+ }) };
532
+ this.resources.set(resourceKey, resource);
533
+ const created = resource;
534
+ void resource.lease.catch(() => {
535
+ if (this.resources.get(resourceKey) === created) {
536
+ this.resources.delete(resourceKey);
537
+ resourceAbort.abort();
538
+ }
539
+ });
540
+ }
541
+ const session = { value, abort, lease: resource.lease.then((lease) => this.sessionLease(resource.value, value, lease)), work: /* @__PURE__ */ new Set() };
542
+ this.sessions.set(value.sessionId, session);
543
+ this.prepared(frame.generation, session);
544
+ return true;
545
+ }
546
+ if (frame.type === "preview.release") {
547
+ if (frame.generation === this.generation) this.releaseSession(frame.sessionId);
548
+ return true;
549
+ }
550
+ if (frame.type === "preview.http.open") {
551
+ if (frame.generation !== this.generation) return true;
552
+ const session = this.sessions.get(frame.sessionId);
553
+ if (!session || this.streams.has(frame.streamId) || !validStream(frame.streamId) || this.streams.size >= PRODUCT_PREVIEW_LIMITS.streamsPerHost || [...this.streams.values()].filter((item) => item.session === session).length >= PRODUCT_PREVIEW_LIMITS.streamsPerSession || !Number.isInteger(frame.bodyBytes) || frame.bodyBytes < 0 || frame.bodyBytes > PRODUCT_PREVIEW_LIMITS.requestBodyBytes) throw new Error("developer.preview_limit");
554
+ assertProductPreviewRequest({ session: session.value, ...this.ports, method: frame.method, path: frame.path });
555
+ let streamBudget, byteBudget;
556
+ try {
557
+ streamBudget = this.budget.acquireStream();
558
+ byteBudget = this.budget.acquireBytes(frame.bodyBytes);
559
+ } catch {
560
+ streamBudget?.();
561
+ byteBudget?.();
562
+ this.ports.send({ type: "preview.http.response", generation: this.generation, streamId: frame.streamId, status: 429, headers: [] });
563
+ this.ports.send({ type: "preview.http.end", streamId: frame.streamId });
564
+ return true;
565
+ }
566
+ const stream = {
567
+ session,
568
+ abort: new AbortController(),
569
+ expected: frame.bodyBytes,
570
+ received: 0,
571
+ sequence: 0,
572
+ chunks: [],
573
+ credits: 0,
574
+ started: false,
575
+ finished: false,
576
+ frame,
577
+ releaseBudget: () => {
578
+ streamBudget?.();
579
+ byteBudget?.();
580
+ }
581
+ };
582
+ this.streams.set(frame.streamId, stream);
583
+ if (!frame.bodyBytes) this.run(stream);
584
+ else this.ports.send({ type: "preview.http.credit", streamId: frame.streamId, chunks: PRODUCT_PREVIEW_LIMITS.windowChunks });
585
+ return true;
586
+ }
587
+ if (frame.type === "preview.http.credit") {
588
+ const stream = this.streams.get(frame.streamId);
589
+ if (stream) {
590
+ if (!Number.isInteger(frame.chunks) || frame.chunks < 1 || stream.credits + frame.chunks > PRODUCT_PREVIEW_LIMITS.windowChunks) {
591
+ this.cancel(frame.streamId);
592
+ return true;
593
+ }
594
+ stream.credits += frame.chunks;
595
+ stream.wake?.();
596
+ stream.wake = void 0;
597
+ }
598
+ return true;
599
+ }
600
+ if (frame.type === "preview.http.end") {
601
+ const stream = this.streams.get(frame.streamId);
602
+ if (stream && !stream.started) {
603
+ if (stream.received !== stream.expected) this.cancel(frame.streamId);
604
+ else this.run(stream);
605
+ }
606
+ return true;
607
+ }
608
+ if (frame.type === "preview.http.cancel") {
609
+ this.cancel(frame.streamId);
610
+ return true;
611
+ }
612
+ throw new Error("developer.preview_invalid");
613
+ }
614
+ sharedLease(lease) {
615
+ if (!lease.subscribe) return lease;
616
+ const listeners = /* @__PURE__ */ new Set();
617
+ let latest;
618
+ const stop = lease.subscribe((value) => {
619
+ latest = readProductPreviewVersion(value);
620
+ for (const listener of listeners) listener(latest);
621
+ });
622
+ return {
623
+ ...lease,
624
+ get nativeSource() {
625
+ return lease.nativeSource;
626
+ },
627
+ subscribe: (listener) => {
628
+ listeners.add(listener);
629
+ if (latest) listener(latest);
630
+ return () => {
631
+ listeners.delete(listener);
632
+ };
633
+ },
634
+ release: async () => {
635
+ stop();
636
+ listeners.clear();
637
+ await lease.release();
638
+ }
639
+ };
640
+ }
641
+ sessionLease(source, session, lease) {
642
+ const base = (value) => buildPersistentWorkspacePublicOrigin2(value.publicOrigin, {
643
+ projectId: this.ports.projectId,
644
+ envKey: "prod",
645
+ workspaceId: value.target.workspaceId,
646
+ codebaseRuntime: { repositoryId: value.target.repositoryId, relativePath: value.target.codebasePath },
647
+ ...value.stableTarget ? { remoteProduct: {
648
+ hostDeviceId: this.ports.hostDeviceId,
649
+ kind: value.target.kind,
650
+ productId: value.target.productId,
651
+ surface: value.target.surface,
652
+ ...value.target.platform ? { platform: value.target.platform } : {}
653
+ } } : { remotePreview: { hostDeviceId: this.ports.hostDeviceId, sessionId: value.sessionId } }
654
+ });
655
+ const from = base(source), to = base(session), forward = (text2) => text2.split(from).join(to);
656
+ const path = (text2) => {
657
+ const url = new URL(text2, source.publicOrigin);
658
+ return forward(url.href).slice(session.publicOrigin.length);
659
+ };
660
+ return {
661
+ entryPath: path(lease.entryPath),
662
+ ...lease.statusPath ? { statusPath: path(lease.statusPath) } : {},
663
+ get nativeSource() {
664
+ return lease.nativeSource ? JSON.parse(forward(JSON.stringify(lease.nativeSource))) : void 0;
665
+ },
666
+ release: async () => {
667
+ },
668
+ ...lease.subscribe ? { subscribe: lease.subscribe.bind(lease) } : {},
669
+ ...lease.openServiceSocket ? { openServiceSocket: (requestPath, protocols) => {
670
+ const url = new URL(requestPath, session.publicOrigin);
671
+ if (!url.href.startsWith(`${to}/`)) throw new Error("developer.preview_forbidden");
672
+ const projected = new URL(from + url.href.slice(to.length));
673
+ return lease.openServiceSocket(projected.pathname + projected.search, protocols);
674
+ } } : {},
675
+ fetch: async (request) => {
676
+ const url = new URL(request.url);
677
+ if (!url.href.startsWith(`${to}/`)) throw new Error("developer.preview_forbidden");
678
+ const response = await lease.fetch(new Request(from + url.href.slice(to.length), request));
679
+ if (from === to) return response;
680
+ if ((session.target.kind === "site" || session.target.kind === "mini-program") && !url.search && isProductPreviewStaticRuntimePath2(url.pathname.slice(new URL(to).pathname.length), { ...session.target, kind: session.target.kind })) return response;
681
+ const headers = new Headers(response.headers), location = headers.get("location");
682
+ if (location) headers.set("location", forward(location));
683
+ const cookies = response.headers.getSetCookie();
684
+ if (cookies.length) {
685
+ headers.delete("set-cookie");
686
+ for (const cookie of cookies) headers.append("set-cookie", cookie.split(new URL(from).pathname).join(new URL(to).pathname));
687
+ }
688
+ const type = headers.get("content-type") ?? "";
689
+ if (!response.body || !/(?:text\/html|application\/json)/u.test(type)) return new Response(response.body, { status: response.status, headers });
690
+ const reader = response.body.getReader(), chunks = [];
691
+ let size = 0;
692
+ const abort = () => {
693
+ void reader.cancel(request.signal.reason).catch(() => {
694
+ });
695
+ };
696
+ request.signal.addEventListener("abort", abort, { once: true });
697
+ try {
698
+ for (; ; ) {
699
+ const part = await reader.read();
700
+ if (part.done) break;
701
+ size += part.value.byteLength;
702
+ if (size > 2 * 1024 * 1024) throw new Error("developer.preview_metadata_limit");
703
+ chunks.push(part.value);
704
+ }
705
+ } finally {
706
+ request.signal.removeEventListener("abort", abort);
707
+ await reader.cancel();
708
+ }
709
+ request.signal.throwIfAborted();
710
+ const bytes = new Uint8Array(size);
711
+ let offset = 0;
712
+ for (const chunk of chunks) {
713
+ bytes.set(chunk, offset);
714
+ offset += chunk.byteLength;
715
+ }
716
+ headers.delete("content-length");
717
+ headers.delete("content-encoding");
718
+ headers.delete("etag");
719
+ return new Response(forward(new TextDecoder().decode(bytes)), { status: response.status, headers });
720
+ }
721
+ };
722
+ }
723
+ prepared(generation, session) {
724
+ void session.lease.then(async (lease) => {
725
+ if (!this.current(session)) return;
726
+ for (const path of [lease.entryPath, lease.statusPath].filter((path2) => path2 !== void 0))
727
+ assertProductPreviewRequest({ session: session.value, ...this.ports, method: "GET", path });
728
+ if (!session.observing && lease.subscribe) {
729
+ session.observing = true;
730
+ let initialized;
731
+ session.initial = new Promise((resolve) => {
732
+ initialized = resolve;
733
+ });
734
+ const unsubscribe = lease.subscribe((value) => {
735
+ if (!this.current(session)) return;
736
+ try {
737
+ const version = readProductPreviewVersion(value);
738
+ if (JSON.stringify(version) === JSON.stringify(session.version)) return;
739
+ session.version = version;
740
+ initialized();
741
+ if (session.published) this.ports.send({
742
+ type: "preview.changed",
743
+ generation,
744
+ sessionId: session.value.sessionId,
745
+ version,
746
+ ...lease.nativeSource ? { nativeSource: readDeveloperNativePreviewSource(lease.nativeSource, { session: session.value, ...this.ports }) } : {}
747
+ });
748
+ } catch {
749
+ this.ports.diagnostic("developer.preview_version_invalid");
750
+ }
751
+ });
752
+ if (!this.current(session)) {
753
+ unsubscribe();
754
+ return;
755
+ }
756
+ session.unsubscribe = unsubscribe;
757
+ }
758
+ if (session.initial) await awaitInitialVersion(session.initial, session.abort.signal);
759
+ if (!this.current(session)) return;
760
+ this.ports.send({
761
+ type: "preview.prepared",
762
+ generation,
763
+ sessionId: session.value.sessionId,
764
+ ok: true,
765
+ entryPath: lease.entryPath,
766
+ ...lease.statusPath ? { statusPath: lease.statusPath } : {},
767
+ ...session.version ? { version: session.version } : {},
768
+ ...lease.nativeSource ? { nativeSource: readDeveloperNativePreviewSource(lease.nativeSource, { session: session.value, ...this.ports }) } : {}
769
+ });
770
+ session.published = true;
771
+ this.publishConnections();
772
+ }).catch((error) => {
773
+ if (!this.current(session)) return;
774
+ this.ports.send({ type: "preview.prepared", generation, sessionId: session.value.sessionId, ok: false, code: readProductPreviewFailureCode(error) });
775
+ this.releaseSession(session.value.sessionId);
776
+ });
777
+ }
778
+ run(stream) {
779
+ const work = this.execute(stream);
780
+ stream.session.work.add(work);
781
+ void work.then(() => stream.session.work.delete(work), () => stream.session.work.delete(work));
782
+ }
783
+ async execute(stream) {
784
+ stream.started = true;
785
+ const { frame } = stream;
786
+ let reader;
787
+ try {
788
+ const lease = await stream.session.lease;
789
+ if (!this.current(stream.session) || stream.abort.signal.aborted) return;
790
+ let body;
791
+ if (stream.expected) {
792
+ const bytes = new Uint8Array(stream.expected);
793
+ let offset = 0;
794
+ for (const chunk of stream.chunks) {
795
+ bytes.set(chunk, offset);
796
+ offset += chunk.byteLength;
797
+ }
798
+ body = bytes.buffer;
799
+ }
800
+ stream.chunks = [];
801
+ const headers = new Headers(productPreviewHeaders(new Headers(frame.headers.map(([name, value]) => [name, value])), false, true));
802
+ headers.set("accept-encoding", "identity");
803
+ const response = await lease.fetch(new Request(new URL(frame.path, stream.session.value.publicOrigin), {
804
+ method: frame.method,
805
+ headers,
806
+ signal: stream.abort.signal,
807
+ ...body ? { body } : {},
808
+ redirect: "manual"
809
+ }));
810
+ if (stream.abort.signal.aborted) {
811
+ await response.body?.cancel();
812
+ return;
813
+ }
814
+ this.ports.send({
815
+ type: "preview.http.response",
816
+ generation: this.generation,
817
+ streamId: frame.streamId,
818
+ status: response.status,
819
+ headers: productPreviewHeaders(response.headers, true)
820
+ });
821
+ reader = response.body?.getReader();
822
+ let sequence = 0;
823
+ if (reader) for (; ; ) {
824
+ while (stream.credits === 0 && !stream.abort.signal.aborted) await new Promise((resolve) => {
825
+ stream.wake = resolve;
826
+ });
827
+ stream.abort.signal.throwIfAborted();
828
+ const next = await reader.read();
829
+ if (next.done) break;
830
+ for (let offset = 0; offset < next.value.byteLength; offset += PRODUCT_PREVIEW_LIMITS.chunkBytes) {
831
+ while (stream.credits === 0 && !stream.abort.signal.aborted) await new Promise((resolve) => {
832
+ stream.wake = resolve;
833
+ });
834
+ stream.abort.signal.throwIfAborted();
835
+ stream.credits--;
836
+ const bytes = encodeProductPreviewChunk(frame.streamId, sequence++, next.value.subarray(offset, offset + PRODUCT_PREVIEW_LIMITS.chunkBytes));
837
+ const release = this.budget.acquireBytes(bytes.byteLength);
838
+ try {
839
+ await this.ports.sendBinary(bytes, stream.abort.signal);
840
+ } finally {
841
+ release();
842
+ }
843
+ }
844
+ }
845
+ if (!stream.abort.signal.aborted) this.ports.send({ type: "preview.http.end", streamId: frame.streamId });
846
+ } catch {
847
+ if (!stream.abort.signal.aborted) this.ports.send({ type: "preview.http.cancel", streamId: frame.streamId });
848
+ } finally {
849
+ stream.finished = true;
850
+ if (this.streams.get(frame.streamId) === stream) this.streams.delete(frame.streamId);
851
+ stream.releaseBudget();
852
+ try {
853
+ await reader?.cancel();
854
+ } catch {
855
+ this.ports.diagnostic("developer.preview_reader_release_failed");
856
+ }
857
+ }
858
+ }
859
+ cancel(id3) {
860
+ const stream = this.streams.get(id3);
861
+ if (!stream) return;
862
+ this.streams.delete(id3);
863
+ stream.abort.abort();
864
+ stream.wake?.();
865
+ stream.chunks = [];
866
+ stream.releaseBudget();
867
+ if (!stream.finished) this.ports.send({ type: "preview.http.cancel", streamId: id3 });
868
+ }
869
+ current(session) {
870
+ return !session.abort.signal.aborted && this.sessions.get(session.value.sessionId) === session;
871
+ }
872
+ publishConnections() {
873
+ this.ports.connections?.([...this.sessions.values()].filter((value) => value.published && value.value.mode !== "observe").map((value) => value.value));
874
+ }
875
+ releaseSession(id3) {
876
+ const session = this.sessions.get(id3);
877
+ if (!session) return;
878
+ this.sessions.delete(id3);
879
+ session.abort.abort();
880
+ this.publishConnections();
881
+ this.serviceSockets.close(id3);
882
+ try {
883
+ session.unsubscribe?.();
884
+ } catch {
885
+ this.ports.diagnostic("developer.preview_observer_release_failed");
886
+ }
887
+ for (const [streamId, stream] of this.streams) if (stream.session === session) this.cancel(streamId);
888
+ let pending;
889
+ const release = () => {
890
+ if (!pending) {
891
+ pending = Promise.allSettled([...session.work]).then(() => session.lease).then((lease) => lease.release(), () => {
892
+ });
893
+ void pending.then(() => this.cleanup.delete(release), () => {
894
+ pending = void 0;
895
+ });
896
+ }
897
+ return pending;
898
+ };
899
+ this.cleanup.add(release);
900
+ void release().catch(() => this.ports.diagnostic("developer.preview_release_failed"));
901
+ }
902
+ };
903
+ async function awaitInitialVersion(initial, signal) {
904
+ signal.throwIfAborted();
905
+ let timer, aborted;
906
+ try {
907
+ await Promise.race([initial, new Promise((_resolve, reject) => {
908
+ aborted = () => reject(new Error("developer.preview_version_unavailable"));
909
+ signal.addEventListener("abort", aborted, { once: true });
910
+ timer = setTimeout(aborted, PRODUCT_PREVIEW_LIMITS.openTimeoutMs);
911
+ })]);
912
+ } finally {
913
+ clearTimeout(timer);
914
+ signal.removeEventListener("abort", aborted);
915
+ }
916
+ }
917
+
918
+ // ../product-preview-clients.ts
919
+ function readProductPreviewClient(raw) {
920
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("developer.preview_client_invalid");
921
+ const value = raw;
922
+ if (Object.keys(value).sort().join(",") !== "deviceId,label,platform" || typeof value.deviceId !== "string" || !/^[A-Za-z0-9_-]{1,160}$/u.test(value.deviceId) || !["ios", "android", "desktop", "web"].includes(String(value.platform)) || typeof value.label !== "string" || !value.label.trim() || value.label.length > 96 || /[\u0000-\u001f\u007f]/u.test(value.label)) throw new Error("developer.preview_client_invalid");
923
+ return { deviceId: value.deviceId, platform: value.platform, label: value.label };
924
+ }
925
+
926
+ // ../product-preview-http-runtime.ts
927
+ var standardProductPreviewHttpRuntime = {
928
+ get Request() {
929
+ return globalThis.Request;
930
+ },
931
+ get Response() {
932
+ return globalThis.Response;
933
+ },
934
+ get ReadableStream() {
935
+ return globalThis.ReadableStream;
936
+ },
937
+ requestBody: (request) => request.body
938
+ };
939
+ function throwIfProductPreviewAborted(signal) {
940
+ if (signal.aborted) throw signal.reason ?? new Error("developer.preview_request_cancelled");
941
+ }
942
+
943
+ // ../product-preview-viewer-http.ts
944
+ var DeveloperProductPreviewViewerHttp = class {
945
+ constructor(ports) {
946
+ this.ports = ports;
947
+ this.runtime = ports.httpRuntime ?? standardProductPreviewHttpRuntime;
948
+ }
949
+ streams = /* @__PURE__ */ new Map();
950
+ pending = [];
951
+ serial = 0;
952
+ closed = false;
953
+ draining = false;
954
+ runtime;
955
+ fetch(request) {
956
+ if (this.closed) return Promise.reject(failure("closed"));
957
+ let session;
958
+ try {
959
+ const current = this.ports.current();
960
+ if (!current || !current.generation || !current.sessionId) throw failure("unavailable");
961
+ session = { ...current, target: { ...current.target } };
962
+ this.assertRequest(session, request);
963
+ if (request.signal.aborted) throw failure("request_cancelled");
964
+ if (this.streams.size >= PRODUCT_PREVIEW_LIMITS.streamsPerSession && this.pending.length >= PRODUCT_PREVIEW_LIMITS.streamsPerHost) throw failure("queue_limit");
965
+ if (this.serial >= 4294967295) throw failure("stream_limit");
966
+ } catch (error) {
967
+ return Promise.reject(error);
968
+ }
969
+ return new Promise((resolve, reject) => {
970
+ const id3 = ++this.serial, abort = new AbortController();
971
+ const cancel = () => this.finish(job, failure("request_cancelled"), true);
972
+ const job = {
973
+ id: id3,
974
+ request,
975
+ session,
976
+ identity: identity(session),
977
+ abort,
978
+ timer: setTimeout(() => this.finish(job, failure("request_timeout"), true), PRODUCT_PREVIEW_LIMITS.openTimeoutMs),
979
+ removeAbort: () => request.signal.removeEventListener("abort", cancel),
980
+ resolve,
981
+ reject,
982
+ state: "queued",
983
+ opened: false,
984
+ responded: false,
985
+ bodyless: false,
986
+ responseCredits: PRODUCT_PREVIEW_LIMITS.windowChunks,
987
+ responseSequence: 0,
988
+ uploadCredits: 0,
989
+ uploadDone: false
990
+ };
991
+ request.signal.addEventListener("abort", cancel, { once: true });
992
+ this.pending.push(job);
993
+ if (request.signal.aborted) cancel();
994
+ else this.pump();
995
+ });
996
+ }
997
+ receive(raw) {
998
+ if (raw instanceof ArrayBuffer) {
999
+ try {
1000
+ const frame2 = decodeProductPreviewChunk(raw), job2 = this.streams.get(frame2.streamId);
1001
+ if (!job2 || !this.current(job2)) return true;
1002
+ if (!job2.opened || !job2.responded || job2.bodyless || job2.responseCredits < 1 || frame2.sequence !== job2.responseSequence) {
1003
+ this.finish(job2, failure("invalid_frame"), true);
1004
+ return true;
1005
+ }
1006
+ job2.responseSequence++;
1007
+ job2.responseCredits--;
1008
+ job2.responseController.enqueue(frame2.payload);
1009
+ this.progress(job2);
1010
+ } catch {
1011
+ this.drain(failure("invalid_frame"));
1012
+ }
1013
+ return true;
1014
+ }
1015
+ let frame;
1016
+ try {
1017
+ frame = JSON.parse(raw);
1018
+ } catch {
1019
+ return false;
1020
+ }
1021
+ if (!frame || typeof frame !== "object" || typeof frame.type !== "string" || !frame.type.startsWith("preview.http.")) return false;
1022
+ if (!("streamId" in frame) || !validStream(frame.streamId)) {
1023
+ this.drain(failure("invalid_frame"));
1024
+ return true;
1025
+ }
1026
+ const job = this.streams.get(frame.streamId);
1027
+ if (!job || !this.current(job)) return true;
1028
+ try {
1029
+ if (!job.opened) throw failure("invalid_frame");
1030
+ if (frame.type === "preview.http.response") {
1031
+ if (typeof frame.generation !== "string") throw failure("invalid_frame");
1032
+ if (frame.generation !== job.session.generation) return true;
1033
+ if (job.responded || !Number.isInteger(frame.status) || frame.status < 200 || frame.status > 599 || !validHeaders(frame.headers)) throw failure("invalid_frame");
1034
+ const headers = productPreviewHeaders(frame.headers, true);
1035
+ job.bodyless = job.request.method === "HEAD" || [204, 205, 304].includes(frame.status);
1036
+ const body = job.bodyless ? null : new this.runtime.ReadableStream({
1037
+ start: (controller) => {
1038
+ job.responseController = controller;
1039
+ },
1040
+ pull: () => {
1041
+ this.progress(job);
1042
+ this.credit(job);
1043
+ },
1044
+ cancel: () => this.finish(job, failure("request_cancelled"), true)
1045
+ }, { highWaterMark: PRODUCT_PREVIEW_LIMITS.windowChunks });
1046
+ const response = new this.runtime.Response(body, { status: frame.status, headers });
1047
+ job.responded = true;
1048
+ this.progress(job);
1049
+ job.resolve(response);
1050
+ } else if (frame.type === "preview.http.credit") {
1051
+ if (job.uploadDone) return true;
1052
+ if (!Number.isInteger(frame.chunks) || frame.chunks < 1 || job.uploadCredits + frame.chunks > PRODUCT_PREVIEW_LIMITS.windowChunks) throw failure("invalid_frame");
1053
+ job.uploadCredits += frame.chunks;
1054
+ job.wake?.();
1055
+ job.wake = void 0;
1056
+ } else if (frame.type === "preview.http.end") {
1057
+ if (!job.responded) throw failure("invalid_frame");
1058
+ this.finish(job);
1059
+ } else if (frame.type === "preview.http.cancel") this.finish(job, failure("remote_cancelled"));
1060
+ else throw failure("invalid_frame");
1061
+ } catch (error) {
1062
+ this.finish(job, error instanceof Error ? error : failure("invalid_frame"), true);
1063
+ }
1064
+ return true;
1065
+ }
1066
+ reset() {
1067
+ this.drain(failure("reset"));
1068
+ }
1069
+ close() {
1070
+ this.closed = true;
1071
+ this.drain(failure("closed"));
1072
+ }
1073
+ assertRequest(session, request) {
1074
+ const url = new URL(request.url);
1075
+ if (url.origin !== session.publicOrigin || url.protocol !== "https:" || url.username || url.password || url.hash) throw failure("forbidden");
1076
+ assertProductPreviewRequest({
1077
+ session,
1078
+ projectId: session.projectId,
1079
+ hostDeviceId: session.hostDeviceId,
1080
+ method: request.method,
1081
+ path: url.pathname + url.search
1082
+ });
1083
+ productPreviewHeaders(request.headers, false, true);
1084
+ }
1085
+ pump() {
1086
+ if (this.draining || this.closed) return;
1087
+ while (this.streams.size < PRODUCT_PREVIEW_LIMITS.streamsPerSession && this.pending.length) {
1088
+ const job = this.pending.shift();
1089
+ job.state = "active";
1090
+ this.streams.set(job.id, job);
1091
+ void this.start(job).catch((error) => this.finish(job, error instanceof Error ? error : failure("transport_failed"), true));
1092
+ }
1093
+ }
1094
+ current(job) {
1095
+ if (job.state === "done") return false;
1096
+ const value = this.ports.current();
1097
+ if (!value || value.socket !== job.session.socket || identity(value) !== job.identity) {
1098
+ this.finish(job, failure("session_changed"));
1099
+ return false;
1100
+ }
1101
+ return true;
1102
+ }
1103
+ send(job, frame) {
1104
+ if (!this.current(job)) throw failure("session_changed");
1105
+ job.session.socket.send(JSON.stringify(frame));
1106
+ }
1107
+ async start(job) {
1108
+ if (!this.current(job)) return;
1109
+ this.assertRequest(job.session, job.request);
1110
+ const body = await this.readBody(job);
1111
+ if (!this.current(job)) return;
1112
+ if (body.byteLength && !job.session.socket.sendBinary) throw failure("transport_unavailable");
1113
+ job.opened = true;
1114
+ this.send(job, {
1115
+ type: "preview.http.open",
1116
+ generation: job.session.generation,
1117
+ sessionId: job.session.sessionId,
1118
+ streamId: job.id,
1119
+ method: job.request.method,
1120
+ path: new URL(job.request.url).pathname + new URL(job.request.url).search,
1121
+ headers: productPreviewHeaders(job.request.headers, false, true),
1122
+ bodyBytes: body.byteLength
1123
+ });
1124
+ this.send(job, { type: "preview.http.credit", streamId: job.id, chunks: PRODUCT_PREVIEW_LIMITS.windowChunks });
1125
+ if (!body.byteLength) {
1126
+ job.uploadDone = true;
1127
+ return;
1128
+ }
1129
+ let sequence = 0;
1130
+ for (let offset = 0; offset < body.byteLength; offset += PRODUCT_PREVIEW_LIMITS.chunkBytes) {
1131
+ while (!job.uploadCredits && this.current(job)) await new Promise((resolve) => {
1132
+ job.wake = resolve;
1133
+ });
1134
+ if (!this.current(job)) return;
1135
+ if (!job.session.socket.sendBinary) throw failure("transport_unavailable");
1136
+ job.uploadCredits--;
1137
+ await job.session.socket.sendBinary(encodeProductPreviewChunk(job.id, sequence++, body.subarray(offset, offset + PRODUCT_PREVIEW_LIMITS.chunkBytes)), job.abort.signal);
1138
+ if (!this.current(job)) return;
1139
+ this.progress(job);
1140
+ }
1141
+ job.uploadDone = true;
1142
+ this.send(job, { type: "preview.http.end", streamId: job.id });
1143
+ }
1144
+ async readBody(job) {
1145
+ const declared = job.request.headers.get("content-length");
1146
+ if (declared && Number(declared) > PRODUCT_PREVIEW_LIMITS.requestBodyBytes) throw failure("body_limit");
1147
+ job.uploadBody = this.runtime.requestBody(job.request);
1148
+ if (!job.uploadBody) return new Uint8Array();
1149
+ const reader = job.uploadBody.getReader();
1150
+ job.uploadReader = reader;
1151
+ const chunks = [];
1152
+ let bytes = 0;
1153
+ try {
1154
+ for (; ; ) {
1155
+ if (!this.current(job)) throw failure("session_changed");
1156
+ const next = await reader.read();
1157
+ if (next.done) break;
1158
+ bytes += next.value.byteLength;
1159
+ if (bytes > PRODUCT_PREVIEW_LIMITS.requestBodyBytes) throw failure("body_limit");
1160
+ chunks.push(next.value);
1161
+ }
1162
+ } finally {
1163
+ reader.releaseLock();
1164
+ job.uploadReader = void 0;
1165
+ }
1166
+ const body = new Uint8Array(bytes);
1167
+ let offset = 0;
1168
+ for (const chunk of chunks) {
1169
+ body.set(chunk, offset);
1170
+ offset += chunk.byteLength;
1171
+ }
1172
+ return body;
1173
+ }
1174
+ credit(job) {
1175
+ if (!this.current(job) || !job.responded || job.bodyless) return;
1176
+ const chunks = Math.max(0, Math.min(PRODUCT_PREVIEW_LIMITS.windowChunks, job.responseController.desiredSize ?? 0) - job.responseCredits);
1177
+ if (!chunks) return;
1178
+ job.responseCredits += chunks;
1179
+ try {
1180
+ this.send(job, { type: "preview.http.credit", streamId: job.id, chunks });
1181
+ } catch {
1182
+ this.finish(job, failure("transport_failed"), true);
1183
+ }
1184
+ }
1185
+ progress(job) {
1186
+ if (!job.responded || job.state === "done") return;
1187
+ clearTimeout(job.timer);
1188
+ job.timer = setTimeout(() => this.finish(job, failure("request_timeout"), true), PRODUCT_PREVIEW_LIMITS.openTimeoutMs);
1189
+ }
1190
+ finish(job, error, notify = false) {
1191
+ if (job.state === "done") return;
1192
+ if (notify && job.opened) {
1193
+ const value = this.ports.current();
1194
+ if (value?.socket === job.session.socket && identity(value) === job.identity) {
1195
+ try {
1196
+ job.session.socket.send(JSON.stringify({ type: "preview.http.cancel", streamId: job.id }));
1197
+ } catch {
1198
+ }
1199
+ }
1200
+ }
1201
+ job.state = "done";
1202
+ this.streams.delete(job.id);
1203
+ const pending = this.pending.indexOf(job);
1204
+ if (pending >= 0) this.pending.splice(pending, 1);
1205
+ clearTimeout(job.timer);
1206
+ job.removeAbort();
1207
+ job.abort.abort();
1208
+ job.wake?.();
1209
+ job.wake = void 0;
1210
+ if (job.uploadReader) void job.uploadReader.cancel().catch(() => {
1211
+ });
1212
+ else {
1213
+ const body = job.uploadBody ?? job.request.body;
1214
+ if (body && !body.locked) void body.cancel().catch(() => {
1215
+ });
1216
+ }
1217
+ if (error) {
1218
+ job.reject(error);
1219
+ try {
1220
+ job.responseController?.error(error);
1221
+ } catch {
1222
+ }
1223
+ } else try {
1224
+ job.responseController?.close();
1225
+ } catch {
1226
+ }
1227
+ this.pump();
1228
+ }
1229
+ drain(error) {
1230
+ this.draining = true;
1231
+ for (const job of [...this.streams.values(), ...this.pending]) this.finish(job, error, true);
1232
+ this.draining = false;
1233
+ }
1234
+ };
1235
+ function failure(code) {
1236
+ return new Error(`developer.preview_${code}`);
1237
+ }
1238
+ function identity(value) {
1239
+ const target = value.target;
1240
+ return JSON.stringify([
1241
+ value.generation,
1242
+ value.sessionId,
1243
+ value.publicOrigin,
1244
+ value.projectId,
1245
+ value.hostDeviceId,
1246
+ target.workspaceId,
1247
+ target.repositoryId,
1248
+ target.codebasePath,
1249
+ target.productId,
1250
+ target.kind,
1251
+ target.surface,
1252
+ target.platform ?? null
1253
+ ]);
1254
+ }
1255
+ function validHeaders(value) {
1256
+ return Array.isArray(value) && value.every((entry) => Array.isArray(entry) && entry.length === 2 && entry.every((part) => typeof part === "string")) && new TextEncoder().encode(JSON.stringify(value)).byteLength <= PRODUCT_PREVIEW_LIMITS.headerBytes;
1257
+ }
1258
+
1259
+ // ../product-preview-viewer.ts
1260
+ var DeveloperProductPreviewViewer = class {
1261
+ constructor(target, ports) {
1262
+ this.ports = ports;
1263
+ this.target = readProductPreviewTarget(target);
1264
+ const entry = readProductPreviewSocketUrl(ports.socketUrl);
1265
+ if (entry.hostDeviceId !== ports.hostDeviceId || JSON.stringify(entry.target) !== JSON.stringify(this.target)) throw new Error("developer.preview_invalid");
1266
+ this.http = new DeveloperProductPreviewViewerHttp({ httpRuntime: ports.httpRuntime, current: () => {
1267
+ const current = this.current;
1268
+ if (!current || !this.active(current) || !current.socket || !current.generation || !current.sessionId || !current.prepared) return void 0;
1269
+ const endpoint = new URL(this.ports.socketUrl);
1270
+ const projectId = /^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/socket$/u.exec(endpoint.pathname)?.[1];
1271
+ if (!projectId) return void 0;
1272
+ endpoint.protocol = "https:";
1273
+ return {
1274
+ socket: current.socket,
1275
+ generation: current.generation,
1276
+ sessionId: current.sessionId,
1277
+ stableTarget: true,
1278
+ publicOrigin: endpoint.origin,
1279
+ projectId,
1280
+ hostDeviceId: this.ports.hostDeviceId,
1281
+ target: this.target
1282
+ };
1283
+ } });
1284
+ }
1285
+ current;
1286
+ closed = false;
1287
+ retryTimer;
1288
+ openingTimer;
1289
+ attempt = 0;
1290
+ descriptor;
1291
+ listeners = /* @__PURE__ */ new Set();
1292
+ first;
1293
+ target;
1294
+ http;
1295
+ /** 资源与业务请求复用当前Viewer Socket,不回落到Gateway HTTP。 */
1296
+ fetch(request) {
1297
+ return this.http.fetch(request);
1298
+ }
1299
+ start() {
1300
+ if (this.closed) return Promise.reject(new Error("developer.preview_closed"));
1301
+ if (!this.first) {
1302
+ let resolve, reject;
1303
+ const promise = new Promise((done, fail) => {
1304
+ resolve = done;
1305
+ reject = fail;
1306
+ });
1307
+ this.first = { promise, resolve, reject };
1308
+ this.openingTimer = setTimeout(() => {
1309
+ this.first?.reject(new Error("developer.preview_open_timeout"));
1310
+ this.close("developer.preview_open_timeout");
1311
+ }, PRODUCT_PREVIEW_LIMITS.prepareTimeoutMs);
1312
+ void this.connect();
1313
+ }
1314
+ return this.first.promise;
1315
+ }
1316
+ subscribe(listener) {
1317
+ this.listeners.add(listener);
1318
+ if (this.descriptor) listener(this.descriptor);
1319
+ return () => {
1320
+ this.listeners.delete(listener);
1321
+ };
1322
+ }
1323
+ close(errorCode) {
1324
+ if (this.closed) return;
1325
+ this.closed = true;
1326
+ clearTimeout(this.retryTimer);
1327
+ clearTimeout(this.openingTimer);
1328
+ this.ports.state?.("offline", errorCode);
1329
+ this.http.close();
1330
+ const current = this.current;
1331
+ this.current = void 0;
1332
+ if (current?.sessionId && current.socket) {
1333
+ try {
1334
+ current.socket.send(JSON.stringify({ type: "preview.close", sessionId: current.sessionId }));
1335
+ } catch {
1336
+ }
1337
+ }
1338
+ current?.abort.abort();
1339
+ current?.socket?.close();
1340
+ this.listeners.clear();
1341
+ this.first?.reject(new Error("developer.preview_closed"));
1342
+ }
1343
+ async connect() {
1344
+ if (this.closed) return;
1345
+ const current = { abort: new AbortController(), requestId: this.ports.newId(), early: [], bytes: 0, opened: false };
1346
+ this.current = current;
1347
+ this.ports.state?.("connecting");
1348
+ try {
1349
+ const socket = await this.ports.open(this.ports.socketUrl, {
1350
+ message: (raw) => {
1351
+ if (!this.active(current)) return;
1352
+ const bytes = typeof raw === "string" ? new TextEncoder().encode(raw).byteLength : raw instanceof ArrayBuffer ? raw.byteLength : Infinity;
1353
+ if (bytes > (typeof raw === "string" ? 256 * 1024 : PRODUCT_PREVIEW_LIMITS.chunkBytes + 10)) {
1354
+ this.failed(current);
1355
+ return;
1356
+ }
1357
+ if (!current.socket) {
1358
+ current.bytes += bytes;
1359
+ if (current.bytes > 1024 * 1024 || current.early.length >= 64) {
1360
+ this.failed(current);
1361
+ return;
1362
+ }
1363
+ current.early.push(raw);
1364
+ return;
1365
+ }
1366
+ this.receive(current, raw);
1367
+ },
1368
+ failed: () => this.failed(current),
1369
+ closed: () => this.failed(current)
1370
+ }, current.abort.signal);
1371
+ if (!this.active(current)) {
1372
+ socket.close();
1373
+ return;
1374
+ }
1375
+ current.socket = socket;
1376
+ const early = current.early;
1377
+ current.early = [];
1378
+ current.bytes = 0;
1379
+ for (const frame of early) this.receive(current, frame);
1380
+ } catch (error) {
1381
+ if (!this.active(current)) return;
1382
+ const failure2 = error;
1383
+ if (failure2?.status === 401 || failure2?.status === 403 || failure2?.code === "forbidden") {
1384
+ this.first?.reject(new Error("developer.preview_forbidden"));
1385
+ this.close("developer.preview_forbidden");
1386
+ } else this.failed(current);
1387
+ }
1388
+ }
1389
+ receive(current, raw) {
1390
+ if (!this.active(current)) return;
1391
+ try {
1392
+ if (this.http.receive(raw)) return;
1393
+ if (typeof raw !== "string") throw new Error("developer.preview_invalid");
1394
+ const frame = JSON.parse(raw);
1395
+ if (frame.type === "ready" || frame.type === "host-state") {
1396
+ const resuming = frame.type === "ready" && current.opened && current.sessionId !== void 0 && current.generation === frame.generation;
1397
+ if (frame.type === "ready" || current.generation !== (frame.generation ?? void 0)) {
1398
+ this.http.reset();
1399
+ current.prepared = false;
1400
+ current.generation = frame.generation ?? void 0;
1401
+ }
1402
+ if (!frame.generation) {
1403
+ this.ports.state?.("offline", "developer.host_offline");
1404
+ return;
1405
+ }
1406
+ if (!current.prepared && !resuming) this.ports.state?.("connecting");
1407
+ if (!current.opened) {
1408
+ current.opened = true;
1409
+ current.socket.send(JSON.stringify({ type: "preview.open", requestId: current.requestId, target: this.target, client: readProductPreviewClient(this.ports.client) }));
1410
+ }
1411
+ return;
1412
+ }
1413
+ if (frame.type === "preview.failed") {
1414
+ if (frame.requestId && frame.requestId !== current.requestId || frame.sessionId && current.sessionId && frame.sessionId !== current.sessionId) return;
1415
+ if (frame.code === "developer.host_offline") {
1416
+ this.http.reset();
1417
+ current.prepared = false;
1418
+ this.ports.state?.("offline", frame.code);
1419
+ current.opened = false;
1420
+ return;
1421
+ }
1422
+ const code = readProductPreviewFailureCode(frame);
1423
+ this.first?.reject(Object.assign(new Error(code), { code }));
1424
+ this.close(code);
1425
+ return;
1426
+ }
1427
+ if (frame.type === "preview.changed") {
1428
+ if (!current.prepared || current.sessionId !== frame.sessionId || current.generation !== frame.generation || !this.descriptor) return;
1429
+ const version = readProductPreviewVersion(frame.version);
1430
+ if (JSON.stringify(this.descriptor.version) === JSON.stringify(version)) return;
1431
+ const endpoint = new URL(this.ports.socketUrl);
1432
+ endpoint.protocol = "https:";
1433
+ const projectId2 = /^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/socket$/u.exec(endpoint.pathname)?.[1];
1434
+ if (!projectId2) throw new Error("developer.preview_invalid");
1435
+ this.descriptor = { ...this.descriptor, version, ...frame.nativeSource ? { nativeSource: readDeveloperNativePreviewSource(
1436
+ frame.nativeSource,
1437
+ { projectId: projectId2, hostDeviceId: this.ports.hostDeviceId, session: { sessionId: frame.sessionId, target: this.target, publicOrigin: endpoint.origin, stableTarget: true } }
1438
+ ) } : {} };
1439
+ for (const listener of this.listeners) listener(this.descriptor);
1440
+ return;
1441
+ }
1442
+ if (frame.type !== "preview.opened") throw new Error("developer.preview_invalid");
1443
+ if (frame.requestId !== current.requestId && !(frame.requestId === "resume" && frame.sessionId === current.sessionId)) return;
1444
+ const origin = new URL(this.ports.socketUrl);
1445
+ origin.protocol = "https:";
1446
+ const projectId = /^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/socket$/u.exec(origin.pathname)?.[1];
1447
+ if (!projectId) throw new Error("developer.preview_invalid");
1448
+ for (const text2 of [frame.url, frame.statusUrl].filter((value) => value !== void 0)) {
1449
+ const url = new URL(text2);
1450
+ if (url.protocol !== "https:" || url.origin !== origin.origin || url.username || url.password) throw new Error("developer.preview_invalid");
1451
+ assertProductPreviewRequest({
1452
+ session: { sessionId: frame.sessionId, target: this.target, publicOrigin: origin.origin, stableTarget: true },
1453
+ projectId,
1454
+ hostDeviceId: this.ports.hostDeviceId,
1455
+ method: "GET",
1456
+ path: url.pathname + url.search
1457
+ });
1458
+ }
1459
+ current.sessionId = frame.sessionId;
1460
+ current.prepared = true;
1461
+ this.attempt = 0;
1462
+ clearTimeout(this.openingTimer);
1463
+ const descriptor = {
1464
+ sessionId: frame.sessionId,
1465
+ url: frame.url,
1466
+ ...frame.statusUrl ? { statusUrl: frame.statusUrl } : {},
1467
+ ...frame.version ? { version: readProductPreviewVersion(frame.version) } : {},
1468
+ ...frame.nativeSource ? { nativeSource: readDeveloperNativePreviewSource(
1469
+ frame.nativeSource,
1470
+ { projectId, hostDeviceId: this.ports.hostDeviceId, session: { sessionId: frame.sessionId, target: this.target, publicOrigin: origin.origin, stableTarget: true } }
1471
+ ) } : {}
1472
+ };
1473
+ this.descriptor = descriptor;
1474
+ this.ports.state?.("ready");
1475
+ this.first?.resolve(descriptor);
1476
+ for (const listener of this.listeners) listener(descriptor);
1477
+ } catch {
1478
+ this.failed(current);
1479
+ }
1480
+ }
1481
+ failed(current) {
1482
+ if (!this.active(current)) return;
1483
+ this.http.reset();
1484
+ this.current = void 0;
1485
+ current.abort.abort();
1486
+ current.socket?.close();
1487
+ this.ports.state?.("connecting", "developer.transport_unavailable");
1488
+ this.retryTimer = setTimeout(() => {
1489
+ this.retryTimer = void 0;
1490
+ void this.connect();
1491
+ }, Math.min(8e3, 500 * 2 ** Math.min(4, this.attempt++)));
1492
+ }
1493
+ active(current) {
1494
+ return !this.closed && this.current === current && !current.abort.signal.aborted;
1495
+ }
1496
+ };
1497
+
1498
+ // ../product-preview-cache.ts
1499
+ import { PRODUCT_PREVIEW_STATIC_FILE_LIMIT, buildPersistentWorkspacePublicOrigin as buildPersistentWorkspacePublicOrigin3, isProductPreviewStaticFile, parsePersistentWorkspacePublicPath as parsePersistentWorkspacePublicPath3 } from "@kuafucloud/product-runtime-protocol";
1500
+ var PRODUCT_PREVIEW_CACHE_LIMITS = { assetBytes: 16 * 1024 * 1024, productBytes: 128 * 1024 * 1024, statusBytes: 2 * 1024 * 1024 };
1501
+ var EXTENSIONS = { json: "application/json", js: "application/javascript", mjs: "application/javascript", cjs: "application/javascript", css: "text/css", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", svg: "image/svg+xml", ico: "image/x-icon", bmp: "image/bmp", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", eot: "application/vnd.ms-fontobject", wasm: "application/wasm", zip: "application/zip", mp3: "audio/mpeg", mp4: "video/mp4", webm: "video/webm", ogg: "audio/ogg", wav: "audio/wav" };
1502
+ var ProductPreviewResourceCache = class {
1503
+ constructor(scope, ports) {
1504
+ this.scope = scope;
1505
+ this.ports = ports;
1506
+ if (ports.maxAssetBytes !== void 0 && (!Number.isSafeInteger(ports.maxAssetBytes) || ports.maxAssetBytes < 0 || ports.maxAssetBytes > PRODUCT_PREVIEW_CACHE_LIMITS.assetBytes)) throw new Error("developer.preview_cache_budget_invalid");
1507
+ }
1508
+ descriptor;
1509
+ generation = 0;
1510
+ inventory = /* @__PURE__ */ new Map();
1511
+ metadataDigest;
1512
+ snapshot;
1513
+ setDescriptor(value) {
1514
+ this.validate(value.url, "GET", value);
1515
+ if (value.statusUrl) this.validate(value.statusUrl, "GET", value);
1516
+ const currentDigest = this.metadataDigest ?? this.descriptor?.version?.metadataDigest;
1517
+ if (!this.descriptor || value.url !== this.descriptor.url || value.statusUrl !== this.descriptor.statusUrl || value.version?.status === "ready" && value.version.metadataDigest && value.version.metadataDigest !== currentDigest) this.invalidate();
1518
+ this.descriptor = value;
1519
+ }
1520
+ close() {
1521
+ this.invalidate();
1522
+ this.descriptor = void 0;
1523
+ }
1524
+ /** 只持久化已验证公开字节事实;稳定目标重开不把临时连接当作缓存授权。 */
1525
+ snapshotInventory() {
1526
+ return this.snapshot && structuredClone(this.snapshot);
1527
+ }
1528
+ async restoreInventory(value) {
1529
+ if (!this.descriptor) throw new Error("developer.preview_cache_closed");
1530
+ await this.installInventory(value, this.descriptor);
1531
+ }
1532
+ async fetch(request) {
1533
+ const descriptor = this.descriptor;
1534
+ if (!descriptor) throw new Error("developer.preview_cache_closed");
1535
+ this.validate(request.url, request.method, descriptor);
1536
+ const generation = this.generation, url = new URL(request.url);
1537
+ const eligible = request.method === "GET" && !["range", "if-range", "if-match", "if-none-match", "if-modified-since", "if-unmodified-since"].some((name) => request.headers.has(name));
1538
+ const asset = eligible ? this.inventory.get(url.pathname) : void 0;
1539
+ if (asset) {
1540
+ const blob = await this.ports.blobs.read(asset.sha256);
1541
+ this.current(generation, request.signal);
1542
+ if (blob) {
1543
+ if (blob.bytes.byteLength === asset.size && await this.ports.sha256(blob.bytes) === asset.sha256) {
1544
+ this.current(generation, request.signal);
1545
+ const contentType2 = !asset.contentType || blob.contentType.split(";", 1)[0]?.trim() === asset.contentType ? blob.contentType : asset.contentType;
1546
+ return new (this.ports.httpRuntime ?? standardProductPreviewHttpRuntime).Response(new Uint8Array(blob.bytes).buffer, { headers: { "content-type": contentType2, "content-length": String(asset.size), "cache-control": "no-store" } });
1547
+ }
1548
+ await this.ports.blobs.remove(asset.sha256);
1549
+ }
1550
+ }
1551
+ const response = await this.ports.fetch(request);
1552
+ this.current(generation, request.signal);
1553
+ if (request.method === "GET" && request.url === descriptor.statusUrl && response.status === 200) {
1554
+ let bytes2;
1555
+ try {
1556
+ bytes2 = await readBounded(response.clone(), PRODUCT_PREVIEW_CACHE_LIMITS.statusBytes, request.signal);
1557
+ } catch (error) {
1558
+ void response.body?.cancel().catch(() => {
1559
+ });
1560
+ throw error;
1561
+ }
1562
+ this.current(generation, request.signal);
1563
+ if (bytes2) {
1564
+ let value;
1565
+ try {
1566
+ value = JSON.parse(new TextDecoder().decode(bytes2));
1567
+ } catch {
1568
+ throw new Error("developer.preview_inventory_invalid");
1569
+ }
1570
+ await this.observeStatus(value, descriptor);
1571
+ } else this.invalidate();
1572
+ return response;
1573
+ }
1574
+ if (!asset || response.status !== 200 || response.headers.has("content-range")) return response;
1575
+ const bytes = await readBounded(response, asset.size, request.signal);
1576
+ this.current(generation, request.signal);
1577
+ if (!bytes || bytes.byteLength !== asset.size || await this.ports.sha256(bytes) !== asset.sha256) throw new Error("developer.preview_asset_digest_mismatch");
1578
+ this.current(generation, request.signal);
1579
+ const contentType = response.headers.get("content-type") || asset.contentType || "application/octet-stream";
1580
+ await this.ports.blobs.write(asset.sha256, { bytes, contentType });
1581
+ this.current(generation, request.signal);
1582
+ return new (this.ports.httpRuntime ?? standardProductPreviewHttpRuntime).Response(new Uint8Array(bytes).buffer, { status: response.status, statusText: response.statusText, headers: response.headers });
1583
+ }
1584
+ async observeStatus(raw, descriptor) {
1585
+ const value = record(raw), data = record(value?.data);
1586
+ if (value?.ok !== true || data?.status !== "ready") {
1587
+ this.invalidate();
1588
+ return;
1589
+ }
1590
+ const inventory = record(data.assetInventory), target = this.scope.target;
1591
+ if (!inventory) {
1592
+ this.invalidate();
1593
+ return;
1594
+ }
1595
+ if (String(data.projectId) !== this.scope.projectId || data.productId !== target.productId || data.productKind !== target.kind || data.environmentKey !== `preview-workspace-${target.workspaceId}` || data.runtimeRef !== `workspace-${target.workspaceId}` || data.scene !== "browser" || inventory.buildId !== data.buildId) throw new Error("developer.preview_inventory_invalid");
1596
+ await this.installInventory({ ...inventory, artifactUrl: data.artifactUrl }, descriptor);
1597
+ }
1598
+ async installInventory(raw, descriptor) {
1599
+ const inventory = record(raw), target = this.scope.target;
1600
+ if (!inventory || Object.keys(inventory).some((key) => !["schemaVersion", "buildId", "metadataDigest", "artifactUrl", "files"].includes(key)) || inventory.schemaVersion !== 1 || typeof inventory.buildId !== "string" || !inventory.buildId || typeof inventory.metadataDigest !== "string" || !/^[a-f0-9]{64}$/u.test(inventory.metadataDigest) || typeof inventory.artifactUrl !== "string" || !Array.isArray(inventory.files) || inventory.files.length > PRODUCT_PREVIEW_STATIC_FILE_LIMIT) throw new Error("developer.preview_inventory_invalid");
1601
+ if (this.metadataDigest !== void 0 && inventory.metadataDigest !== this.metadataDigest) this.invalidate();
1602
+ else this.inventory.clear();
1603
+ if (descriptor.version?.status === "ready" && (descriptor.version.metadataDigest && descriptor.version.metadataDigest !== inventory.metadataDigest || descriptor.version.buildId && descriptor.version.buildId !== inventory.buildId)) return;
1604
+ this.validate(inventory.artifactUrl, "GET", descriptor);
1605
+ const artifact = new URL(inventory.artifactUrl), route = parsePersistentWorkspacePublicPath3(artifact);
1606
+ const folder = target.kind === "desktop" ? "desktops" : target.kind === "app" ? "apps" : target.kind === "site" ? "sites" : target.kind === "mini-program" ? "mini-programs" : "extensions";
1607
+ if (!route.runtimePath.startsWith(`/preview/artifacts/${folder}/${target.productId}/${this.scope.projectId}/preview-workspace-${target.workspaceId}/browser/current/`) || artifact.search || artifact.hash || !artifact.pathname.endsWith(target.kind === "extension" ? "/manifest.json" : "/index.html")) throw new Error("developer.preview_inventory_invalid");
1608
+ const root = new URL(".", artifact), assets = /* @__PURE__ */ new Map(), files = [];
1609
+ let total = 0;
1610
+ const seenPaths = /* @__PURE__ */ new Set();
1611
+ for (const entry of inventory.files) {
1612
+ const file = record(entry), relativePath = file?.relativePath;
1613
+ if (typeof relativePath !== "string" || relativePath.length > 1024 || /[\\%:?#\u0000-\u001f\u007f]/u.test(relativePath) || relativePath.split("/").some((part) => !part || part.startsWith(".")) || !Number.isSafeInteger(file?.size) || Number(file?.size) < 0 || typeof file?.sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(file.sha256)) throw new Error("developer.preview_inventory_invalid");
1614
+ if (!isProductPreviewStaticFile(relativePath) || target.kind === "extension" && relativePath !== "manifest.json" && !relativePath.startsWith("admin/")) throw new Error("developer.preview_inventory_invalid");
1615
+ const contentType = EXTENSIONS[relativePath.split(".").at(-1).toLowerCase()];
1616
+ const path = new URL(relativePath, root).pathname;
1617
+ if (seenPaths.has(path)) throw new Error("developer.preview_inventory_invalid");
1618
+ seenPaths.add(path);
1619
+ const size = Number(file.size);
1620
+ files.push({ relativePath, size, sha256: file.sha256 });
1621
+ if (size > Math.min(PRODUCT_PREVIEW_CACHE_LIMITS.assetBytes, this.ports.maxAssetBytes ?? PRODUCT_PREVIEW_CACHE_LIMITS.assetBytes) || total + size > PRODUCT_PREVIEW_CACHE_LIMITS.productBytes) continue;
1622
+ total += size;
1623
+ assets.set(path, { size, sha256: file.sha256, contentType });
1624
+ }
1625
+ files.sort((a, b) => a.relativePath < b.relativePath ? -1 : a.relativePath > b.relativePath ? 1 : 0);
1626
+ if (target.kind === "site" || target.kind === "mini-program") {
1627
+ const generation = this.generation;
1628
+ const closureHash = await this.ports.sha256(new TextEncoder().encode(JSON.stringify(files)));
1629
+ if (generation !== this.generation || !this.descriptor) throw new Error("developer.preview_cache_scope_changed");
1630
+ const base = buildPersistentWorkspacePublicOrigin3(artifact.origin, route);
1631
+ for (const file of files) {
1632
+ const asset = assets.get(new URL(file.relativePath, root).pathname);
1633
+ if (asset) assets.set(new URL(`${base}/preview/static/${target.kind}/${target.productId}/${closureHash}/${file.relativePath}`).pathname, asset);
1634
+ }
1635
+ }
1636
+ this.inventory = assets;
1637
+ this.metadataDigest = inventory.metadataDigest;
1638
+ this.snapshot = { schemaVersion: 1, buildId: inventory.buildId, metadataDigest: inventory.metadataDigest, artifactUrl: artifact.href, files };
1639
+ }
1640
+ validate(text2, method, descriptor) {
1641
+ const url = new URL(text2), source = new URL(descriptor.url), scope = parsePersistentWorkspacePublicPath3(source);
1642
+ if (source.protocol !== "https:" || source.username || source.password || source.hash || !scope || !scope.remotePreview && !scope.remoteProduct || url.protocol !== "https:" || url.origin !== source.origin || url.username || url.password || url.hash) throw new Error("developer.preview_cache_scope_invalid");
1643
+ assertProductPreviewRequest({
1644
+ session: {
1645
+ publicOrigin: source.origin,
1646
+ sessionId: scope.remotePreview?.sessionId ?? "",
1647
+ target: this.scope.target,
1648
+ ...scope.remoteProduct ? { stableTarget: true } : {}
1649
+ },
1650
+ projectId: this.scope.projectId,
1651
+ hostDeviceId: this.scope.hostDeviceId,
1652
+ method,
1653
+ path: url.pathname + url.search
1654
+ });
1655
+ }
1656
+ invalidate() {
1657
+ this.generation++;
1658
+ this.inventory.clear();
1659
+ this.metadataDigest = void 0;
1660
+ this.snapshot = void 0;
1661
+ }
1662
+ current(generation, signal) {
1663
+ throwIfProductPreviewAborted(signal);
1664
+ if (generation !== this.generation || !this.descriptor) throw new Error("developer.preview_cache_scope_changed");
1665
+ }
1666
+ };
1667
+ function record(value) {
1668
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1669
+ }
1670
+ async function readBounded(response, limit, signal) {
1671
+ if (!response.body) return new Uint8Array();
1672
+ const reader = response.body.getReader(), chunks = [];
1673
+ let size = 0;
1674
+ const abort = () => {
1675
+ void reader.cancel(signal.reason).catch(() => {
1676
+ });
1677
+ };
1678
+ signal.addEventListener("abort", abort, { once: true });
1679
+ try {
1680
+ while (true) {
1681
+ throwIfProductPreviewAborted(signal);
1682
+ const next = await reader.read();
1683
+ throwIfProductPreviewAborted(signal);
1684
+ if (next.done) break;
1685
+ size += next.value.byteLength;
1686
+ if (size > limit) {
1687
+ void reader.cancel();
1688
+ return void 0;
1689
+ }
1690
+ chunks.push(next.value);
1691
+ }
1692
+ } finally {
1693
+ signal.removeEventListener("abort", abort);
1694
+ reader.releaseLock();
1695
+ }
1696
+ const bytes = new Uint8Array(size);
1697
+ let offset = 0;
1698
+ for (const chunk of chunks) {
1699
+ bytes.set(chunk, offset);
1700
+ offset += chunk.byteLength;
1701
+ }
1702
+ return bytes;
1703
+ }
1704
+
1705
+ // ../payload-fragments.ts
1706
+ var chunkCharacters = 24 * 1024;
1707
+ var maxAssemblyBytes = 64 * 1024 * 1024;
1708
+ function* fragmentDeveloperPayload(payload, id3) {
1709
+ const text2 = JSON.stringify(payload);
1710
+ if (text2 === void 0) throw new Error("developer.payload_invalid");
1711
+ if (text2.length <= chunkCharacters) {
1712
+ yield { payload };
1713
+ return;
1714
+ }
1715
+ if (new TextEncoder().encode(text2).length > maxAssemblyBytes) throw new Error("developer.assembly_limit");
1716
+ const count = Math.ceil(text2.length / chunkCharacters);
1717
+ for (let index = 0; index < count; index++) yield {
1718
+ payload: text2.slice(index * chunkCharacters, (index + 1) * chunkCharacters),
1719
+ fragment: { id: id3, index, count }
1720
+ };
1721
+ }
1722
+ function validDeveloperPayloadPart(value) {
1723
+ const part = value.fragment;
1724
+ return part === void 0 || !!part && typeof part.id === "string" && part.id.length > 0 && part.id.length <= 160 && Number.isSafeInteger(part.index) && Number.isSafeInteger(part.count) && part.count > 1 && part.count <= maxAssemblyBytes / chunkCharacters + 1 && part.index >= 0 && part.index < part.count && typeof value.payload === "string" && value.payload.length <= chunkCharacters;
1725
+ }
1726
+ var DeveloperPayloadAssembly = class {
1727
+ pending;
1728
+ clear() {
1729
+ this.pending = void 0;
1730
+ }
1731
+ accept(value, sequence = 0, type = "result") {
1732
+ if (!validDeveloperPayloadPart(value)) {
1733
+ this.clear();
1734
+ throw new Error("developer.invalid_fragment");
1735
+ }
1736
+ const fragment = value.fragment;
1737
+ if (!fragment) {
1738
+ if (this.pending) {
1739
+ this.clear();
1740
+ throw new Error("developer.fragment_incomplete");
1741
+ }
1742
+ return { payload: value.payload, firstSequence: sequence };
1743
+ }
1744
+ if (!this.pending && fragment.index === 0) this.pending = {
1745
+ id: fragment.id,
1746
+ count: fragment.count,
1747
+ next: 0,
1748
+ bytes: 0,
1749
+ parts: [],
1750
+ firstSequence: sequence,
1751
+ type
1752
+ };
1753
+ const pending = this.pending;
1754
+ if (!pending || pending.id !== fragment.id || pending.count !== fragment.count || pending.next !== fragment.index || pending.type !== type || type !== "result" && sequence !== pending.firstSequence + fragment.index) {
1755
+ this.clear();
1756
+ throw new Error("developer.fragment_order");
1757
+ }
1758
+ const text2 = value.payload;
1759
+ pending.bytes += new TextEncoder().encode(text2).length;
1760
+ if (pending.bytes > maxAssemblyBytes) {
1761
+ this.clear();
1762
+ throw new Error("developer.assembly_limit");
1763
+ }
1764
+ pending.parts.push(text2);
1765
+ pending.next++;
1766
+ if (pending.next !== pending.count) return null;
1767
+ this.clear();
1768
+ return { payload: JSON.parse(pending.parts.join("")), firstSequence: pending.firstSequence };
1769
+ }
1770
+ };
1771
+
1772
+ // ../workspace-viewer.ts
1773
+ var DeveloperRealtimeClientError = class extends Error {
1774
+ constructor(code, outcome, details) {
1775
+ super(code);
1776
+ this.code = code;
1777
+ this.outcome = outcome;
1778
+ this.details = details;
1779
+ }
1780
+ };
1781
+ var DeveloperWorkspaceViewer = class {
1782
+ constructor(binding, ports) {
1783
+ this.binding = binding;
1784
+ this.ports = ports;
1785
+ if (![binding.workspaceId, binding.conversationId, binding.hostDeviceId].every(id)) throw new DeveloperRealtimeClientError("developer.binding_invalid");
1786
+ this.views = {
1787
+ agent: { id: this.nextId(), listeners: /* @__PURE__ */ new Set(), state: emptyDeveloperWorkspaceView(), assembly: new DeveloperPayloadAssembly() },
1788
+ products: { id: this.nextId(), listeners: /* @__PURE__ */ new Set(), state: emptyDeveloperWorkspaceView(), assembly: new DeveloperPayloadAssembly() }
1789
+ };
1790
+ }
1791
+ views;
1792
+ connectionListeners = /* @__PURE__ */ new Set();
1793
+ connectionState = { connecting: true, hostOffline: false };
1794
+ getConnectionSnapshot = () => this.connectionState;
1795
+ subscribeConnection = (listener) => {
1796
+ if (this.closed) throw new DeveloperRealtimeClientError("developer.viewer_closed");
1797
+ this.connectionListeners.add(listener);
1798
+ if (!this.connection && !this.retryTimer) void this.connect();
1799
+ return () => {
1800
+ this.connectionListeners.delete(listener);
1801
+ if (!this.observed()) {
1802
+ this.clearRetry();
1803
+ this.disconnect();
1804
+ this.reset("offline");
1805
+ }
1806
+ };
1807
+ };
1808
+ setConnectionState(connecting, hostOffline) {
1809
+ if (this.connectionState.connecting === connecting && this.connectionState.hostOffline === hostOffline) return;
1810
+ this.connectionState = { connecting, hostOffline };
1811
+ for (const listener of [...this.connectionListeners]) {
1812
+ try {
1813
+ listener();
1814
+ } catch {
1815
+ this.connectionListeners.delete(listener);
1816
+ this.ports.diagnostic?.("developer.observer_failed");
1817
+ }
1818
+ }
1819
+ }
1820
+ pending = /* @__PURE__ */ new Map();
1821
+ connection;
1822
+ retryTimer;
1823
+ attempt = 0;
1824
+ serial = 0;
1825
+ closed = false;
1826
+ missing = false;
1827
+ getSnapshot(kind) {
1828
+ return this.views[kind].state;
1829
+ }
1830
+ /** 分页响应只可归并到发起时的连接流;其间新增实时事件由归并器保留。 */
1831
+ updateContent(kind, expected, update) {
1832
+ const view = this.views[kind], current = view.state;
1833
+ if (this.closed || current.phase !== "ready" || current.generation !== expected.generation || current.streamId !== expected.streamId) return false;
1834
+ view.state = { ...current, content: update(current.content) };
1835
+ this.notify(view);
1836
+ return true;
1837
+ }
1838
+ subscribe(kind, listener) {
1839
+ if (this.closed) throw new DeveloperRealtimeClientError("developer.viewer_closed");
1840
+ const view = this.views[kind];
1841
+ if (!view.listeners.size && this.connection?.ready) view.state = emptyDeveloperWorkspaceView(this.connection.generation ? "connecting" : "offline", this.connection.generation);
1842
+ view.listeners.add(listener);
1843
+ if (!this.connection && !this.retryTimer) void this.connect();
1844
+ else this.subscribeView(kind);
1845
+ let released = false;
1846
+ return () => {
1847
+ if (released) return;
1848
+ released = true;
1849
+ view.listeners.delete(listener);
1850
+ if (!view.listeners.size) {
1851
+ const current = this.connection;
1852
+ if (current?.sent.delete(view.id)) this.send({ type: "unsubscribe", subscriptionId: view.id });
1853
+ view.state = emptyDeveloperWorkspaceView();
1854
+ view.assembly.clear();
1855
+ view.assemblyStream = void 0;
1856
+ }
1857
+ if (!this.observed()) {
1858
+ this.clearRetry();
1859
+ this.disconnect();
1860
+ this.reset("offline");
1861
+ }
1862
+ };
1863
+ }
1864
+ /** 输入从不自动重放;结果未知时调用方只能按原业务clientMessageId查询receipt。 */
1865
+ async request(operation, input, signal) {
1866
+ if (this.views.agent.state.phase === "missing" || this.views.products.state.phase === "missing") throw new DeveloperRealtimeClientError("developer.workspace_removed");
1867
+ if (this.closed || !this.connection?.ready || !this.connection.generation) return Promise.reject(new DeveloperRealtimeClientError("developer.host_offline"));
1868
+ if (signal?.aborted) return Promise.reject(new DeveloperRealtimeClientError("developer.request_cancelled"));
1869
+ if (this.pending.size >= DEVELOPER_REALTIME_LIMITS.requestsPerViewer) return Promise.reject(new DeveloperRealtimeClientError("developer.request_limit"));
1870
+ const connection = this.connection;
1871
+ let inputTicket;
1872
+ if ((operation === "send" || operation === "receipt") && this.ports.authorizeInput) {
1873
+ const inputAbort = new AbortController(), cancel = () => inputAbort.abort();
1874
+ signal?.addEventListener("abort", cancel, { once: true });
1875
+ connection.abort.signal.addEventListener("abort", cancel, { once: true });
1876
+ try {
1877
+ inputTicket = await this.ports.authorizeInput(this.binding, inputAbort.signal);
1878
+ } finally {
1879
+ signal?.removeEventListener("abort", cancel);
1880
+ connection.abort.signal.removeEventListener("abort", cancel);
1881
+ }
1882
+ }
1883
+ if (this.connection !== connection || signal?.aborted || connection.abort.signal.aborted) throw new DeveloperRealtimeClientError("developer.request_cancelled");
1884
+ if (this.pending.size >= DEVELOPER_REALTIME_LIMITS.requestsPerViewer) throw new DeveloperRealtimeClientError("developer.request_limit");
1885
+ const requestId = this.nextId();
1886
+ const frame = { type: "request", requestId, workspaceId: this.binding.workspaceId, operation, input, ...inputTicket ? { inputTicket } : {} };
1887
+ try {
1888
+ if (new TextEncoder().encode(JSON.stringify(frame)).length > DEVELOPER_REALTIME_LIMITS.frameBytes) throw new Error();
1889
+ } catch {
1890
+ return Promise.reject(new DeveloperRealtimeClientError("developer.payload_invalid"));
1891
+ }
1892
+ if (this.pending.has(requestId)) return Promise.reject(new DeveloperRealtimeClientError("developer.identity_invalid"));
1893
+ return new Promise((resolve, reject) => {
1894
+ const cancel = () => this.finishRequest(requestId, this.requestError(operation, "developer.result_unknown"));
1895
+ const timer = setTimeout(cancel, DEVELOPER_REALTIME_LIMITS.requestTimeoutMs);
1896
+ const entry = { operation, resolve, reject, assembly: new DeveloperPayloadAssembly(), cleanup: () => {
1897
+ clearTimeout(timer);
1898
+ signal?.removeEventListener("abort", cancel);
1899
+ } };
1900
+ this.pending.set(requestId, entry);
1901
+ signal?.addEventListener("abort", cancel, { once: true });
1902
+ if (!this.send(frame)) {
1903
+ this.finishRequest(requestId, this.requestError(operation, "developer.result_unknown"));
1904
+ }
1905
+ });
1906
+ }
1907
+ retry() {
1908
+ this.missing = false;
1909
+ if (this.closed || !this.observed()) return;
1910
+ this.clearRetry();
1911
+ this.disconnect();
1912
+ this.attempt = 0;
1913
+ void this.connect();
1914
+ }
1915
+ close() {
1916
+ if (this.closed) return;
1917
+ this.closed = true;
1918
+ this.clearRetry();
1919
+ this.disconnect();
1920
+ this.reset("offline");
1921
+ for (const view of Object.values(this.views)) view.listeners.clear();
1922
+ this.connectionListeners.clear();
1923
+ }
1924
+ async connect() {
1925
+ if (this.missing) return;
1926
+ if (this.closed || !this.observed() || this.connection) return;
1927
+ const current = { id: ++this.serial, abort: new AbortController(), ready: false, generation: null, sent: /* @__PURE__ */ new Set() };
1928
+ this.connection = current;
1929
+ this.reset("connecting");
1930
+ if (!this.current(current) || !this.observed()) return;
1931
+ try {
1932
+ const events = {
1933
+ message: (data) => this.receive(current, data),
1934
+ closed: () => this.failed(current),
1935
+ failed: () => this.failed(current)
1936
+ };
1937
+ let socket;
1938
+ if ("connect" in this.ports) {
1939
+ current.preview = this.ports.preview;
1940
+ current.handshake = setTimeout(() => this.failed(current), 1e4);
1941
+ socket = await this.ports.connect(events, current.abort.signal);
1942
+ } else {
1943
+ const ticket = await this.ports.authorize(this.binding, current.abort.signal);
1944
+ if (!this.current(current)) return;
1945
+ if (typeof ticket.socketUrl !== "string" || !ticket.socketUrl || typeof ticket.ticket !== "string" || !ticket.ticket || ticket.ticket.length > 7600 || !Number.isSafeInteger(ticket.expiresAt) || ticket.expiresAt <= Date.now()) throw new DeveloperRealtimeClientError("developer.ticket_invalid");
1946
+ const endpoint = new URL(ticket.socketUrl), source = /^\/api\/project\/([1-9]\d*)\/env\/prod\/ext\/developer\/runtime\/developer\/socket$/u.exec(endpoint.pathname);
1947
+ if (source && endpoint.protocol === "wss:" && !endpoint.username && !endpoint.password && !endpoint.search && !endpoint.hash) {
1948
+ endpoint.protocol = "https:";
1949
+ current.preview = { origin: endpoint.origin, projectId: source[1], hostDeviceId: this.binding.hostDeviceId, workspaceId: this.binding.workspaceId };
1950
+ }
1951
+ current.handshake = setTimeout(() => this.failed(current), 1e4);
1952
+ socket = await this.ports.open(ticket, events, current.abort.signal);
1953
+ }
1954
+ if (!this.current(current)) {
1955
+ socket.close(1e3, "developer.viewer_released");
1956
+ return;
1957
+ }
1958
+ current.socket = socket;
1959
+ if (current.ready) for (const kind of this.kinds()) this.subscribeView(kind);
1960
+ } catch (error) {
1961
+ if (!this.current(current)) return;
1962
+ if (forbidden(error)) {
1963
+ this.disconnect();
1964
+ this.reset("forbidden", "developer.workspace_forbidden");
1965
+ } else this.failed(current);
1966
+ }
1967
+ }
1968
+ receive(current, raw) {
1969
+ if (!this.current(current)) return;
1970
+ let frame;
1971
+ try {
1972
+ frame = decodeDeveloperViewerFrame(raw);
1973
+ } catch {
1974
+ this.disconnect();
1975
+ this.reset("failed", "developer.invalid_frame");
1976
+ return;
1977
+ }
1978
+ if (frame.type === "ready") {
1979
+ if (frame.generation === null) this.failRequests();
1980
+ current.ready = true;
1981
+ current.generation = frame.generation;
1982
+ current.sent.clear();
1983
+ this.attempt = 0;
1984
+ clearTimeout(current.handshake);
1985
+ current.handshake = void 0;
1986
+ this.setConnectionState(false, frame.generation === null);
1987
+ for (const kind of this.kinds()) this.apply(kind, frame);
1988
+ if (current.socket) for (const kind of this.kinds()) this.subscribeView(kind);
1989
+ return;
1990
+ }
1991
+ if (!current.ready) {
1992
+ this.disconnect();
1993
+ this.reset("failed", "developer.ready_required");
1994
+ return;
1995
+ }
1996
+ if (frame.type === "host-state") {
1997
+ if (frame.generation === null) this.failRequests();
1998
+ current.generation = frame.generation;
1999
+ this.setConnectionState(false, frame.generation === null);
2000
+ for (const kind of this.kinds()) this.apply(kind, frame);
2001
+ return;
2002
+ }
2003
+ if (frame.type === "error" && frame.code === "developer.workspace_removed") {
2004
+ this.missing = true;
2005
+ this.clearRetry();
2006
+ this.disconnect();
2007
+ this.setConnectionState(false, false);
2008
+ this.reset("missing", frame.code);
2009
+ return;
2010
+ }
2011
+ if (frame.type === "result") {
2012
+ const pending = this.pending.get(frame.requestId);
2013
+ if (!pending) return;
2014
+ try {
2015
+ const complete = pending.assembly.accept(frame);
2016
+ if (!complete) return;
2017
+ frame = { ...frame, payload: complete.payload };
2018
+ } catch {
2019
+ this.disconnect();
2020
+ this.reset("failed", "developer.invalid_fragment");
2021
+ return;
2022
+ }
2023
+ this.pending.delete(frame.requestId);
2024
+ pending.cleanup();
2025
+ if (frame.ok) pending.resolve(frame.payload);
2026
+ else {
2027
+ const failure2 = frame.payload && typeof frame.payload === "object" ? frame.payload : {};
2028
+ pending.reject(new DeveloperRealtimeClientError(
2029
+ id(failure2.code) ? failure2.code : "developer.request_rejected",
2030
+ failure2.outcome === "unknown" && (pending.operation === "send" || pending.operation === "receipt") ? "unknown" : void 0,
2031
+ frame.payload
2032
+ ));
2033
+ }
2034
+ return;
2035
+ }
2036
+ if (frame.type === "error" && frame.requestId) {
2037
+ const pending = this.pending.get(frame.requestId);
2038
+ if (pending) this.finishRequest(frame.requestId, frame.code === "developer.result_unknown" ? this.requestError(pending.operation, frame.code) : new DeveloperRealtimeClientError(frame.code));
2039
+ return;
2040
+ }
2041
+ if (frame.type === "error" && ["developer.workspace_forbidden", "developer.authorization_expired"].includes(frame.code) && (!frame.subscriptionId || Object.values(this.views).some((view) => view.id === frame.subscriptionId && view.listeners.size))) {
2042
+ this.disconnect();
2043
+ this.reset("forbidden", frame.code);
2044
+ return;
2045
+ }
2046
+ for (const kind of this.kinds()) this.apply(kind, frame);
2047
+ }
2048
+ apply(kind, frame) {
2049
+ const view = this.views[kind];
2050
+ if (!view.listeners.size) return;
2051
+ let previous = view.state;
2052
+ try {
2053
+ if (frame.type === "ready" || frame.type === "host-state" || frame.type === "error") {
2054
+ view.assembly.clear();
2055
+ view.assemblyStream = void 0;
2056
+ }
2057
+ if ((frame.type === "snapshot" || frame.type === "event") && frame.subscriptionId === view.id && frame.generation === previous.generation) {
2058
+ if (frame.streamId === previous.streamId && frame.sequence <= previous.sequence) return;
2059
+ if (view.assemblyStream !== frame.streamId) {
2060
+ view.assembly.clear();
2061
+ view.assemblyStream = frame.streamId;
2062
+ }
2063
+ const complete = view.assembly.accept(frame, frame.sequence, frame.type);
2064
+ if (!complete) {
2065
+ this.send({ type: "ack", generation: frame.generation, streamId: frame.streamId, subscriptionId: view.id, sequence: frame.sequence });
2066
+ return;
2067
+ }
2068
+ if (frame.type === "event" && previous.sequence + 1 === complete.firstSequence) previous = { ...previous, sequence: frame.sequence - 1 };
2069
+ frame = { ...frame, payload: complete.payload };
2070
+ }
2071
+ const effective = frame.type === "snapshot" && frame.subscriptionId === view.id && frame.generation === previous.generation && !(frame.streamId === previous.streamId && frame.sequence <= previous.sequence) ? { ...frame, payload: this.ports.snapshot(kind, frame.payload, previous.phase === "ready" && frame.streamId === previous.streamId ? previous.content : void 0) } : frame;
2072
+ view.state = reduceDeveloperWorkspaceView(previous, view.id, effective, (content, event) => this.ports.event(kind, content, event));
2073
+ if (kind === "products" && view.state.phase === "ready") {
2074
+ const content = view.state.content;
2075
+ if (content && typeof content === "object" && Array.isArray(content.products)) view.state = { ...view.state, content: {
2076
+ ...content,
2077
+ products: content.products.map((item) => {
2078
+ if (!item || typeof item !== "object" || Array.isArray(item)) return item;
2079
+ const { preview: _untrusted, ...product } = item;
2080
+ return this.connection?.preview ? { ...product, preview: this.connection.preview } : product;
2081
+ })
2082
+ } };
2083
+ }
2084
+ } catch {
2085
+ view.state = { ...emptyDeveloperWorkspaceView("failed", previous.generation), errorCode: "developer.content_invalid" };
2086
+ }
2087
+ if (view.state !== previous) this.notify(view);
2088
+ if (view.state.phase === "failed" && this.connection?.sent.delete(view.id)) this.send({ type: "unsubscribe", subscriptionId: view.id });
2089
+ if ((frame.type === "snapshot" || frame.type === "event") && frame.subscriptionId === view.id) {
2090
+ if (view.state.phase === "ready" && view.state.generation === frame.generation && view.state.streamId === frame.streamId && view.state.sequence === frame.sequence) {
2091
+ this.send({ type: "ack", generation: frame.generation, streamId: frame.streamId, subscriptionId: view.id, sequence: frame.sequence });
2092
+ } else if (previous.phase === "ready" && view.state.phase === "connecting") {
2093
+ this.send({ type: "unsubscribe", subscriptionId: view.id });
2094
+ this.connection?.sent.delete(view.id);
2095
+ this.subscribeView(kind);
2096
+ }
2097
+ }
2098
+ }
2099
+ subscribeView(kind) {
2100
+ const current = this.connection, view = this.views[kind];
2101
+ if (!current?.ready || !current.socket || !view.listeners.size || current.sent.has(view.id)) return;
2102
+ current.sent.add(view.id);
2103
+ if (!this.send({ type: "subscribe", subscriptionId: view.id, workspaceId: this.binding.workspaceId, kind })) current.sent.delete(view.id);
2104
+ }
2105
+ send(frame) {
2106
+ const current = this.connection;
2107
+ if (!current?.ready || !current.socket) return false;
2108
+ let text2;
2109
+ try {
2110
+ text2 = JSON.stringify(frame);
2111
+ if (new TextEncoder().encode(text2).length > DEVELOPER_REALTIME_LIMITS.frameBytes) return false;
2112
+ } catch {
2113
+ return false;
2114
+ }
2115
+ try {
2116
+ current.socket.send(text2);
2117
+ return true;
2118
+ } catch {
2119
+ this.failed(current);
2120
+ return false;
2121
+ }
2122
+ }
2123
+ failed(current) {
2124
+ if (!this.current(current)) return;
2125
+ this.disconnect();
2126
+ this.reset("connecting", "developer.transport_unavailable");
2127
+ if (!this.closed && this.observed()) this.retryTimer = setTimeout(() => {
2128
+ this.retryTimer = void 0;
2129
+ void this.connect();
2130
+ }, Math.min(8e3, 500 * 2 ** Math.min(this.attempt++, 4)));
2131
+ }
2132
+ disconnect() {
2133
+ const current = this.connection;
2134
+ this.connection = void 0;
2135
+ this.failRequests();
2136
+ if (!current) return;
2137
+ current.abort.abort();
2138
+ clearTimeout(current.handshake);
2139
+ try {
2140
+ current.socket?.close(1e3, "developer.viewer_released");
2141
+ } catch {
2142
+ this.ports.diagnostic?.("developer.socket_release_failed");
2143
+ }
2144
+ }
2145
+ reset(phase, errorCode) {
2146
+ this.setConnectionState(phase === "connecting", phase === "forbidden" ? false : this.connectionState.hostOffline);
2147
+ for (const view of Object.values(this.views)) {
2148
+ view.assembly.clear();
2149
+ view.assemblyStream = void 0;
2150
+ view.state = { ...emptyDeveloperWorkspaceView(phase), ...errorCode ? { errorCode } : {} };
2151
+ this.notify(view);
2152
+ }
2153
+ }
2154
+ notify(view) {
2155
+ let failed = false;
2156
+ for (const listener of [...view.listeners]) {
2157
+ try {
2158
+ listener();
2159
+ } catch {
2160
+ failed = true;
2161
+ view.listeners.delete(listener);
2162
+ this.ports.diagnostic?.("developer.observer_failed");
2163
+ }
2164
+ }
2165
+ if (failed && !view.listeners.size) {
2166
+ if (this.connection?.sent.delete(view.id)) this.send({ type: "unsubscribe", subscriptionId: view.id });
2167
+ view.state = emptyDeveloperWorkspaceView();
2168
+ if (!this.observed()) {
2169
+ this.clearRetry();
2170
+ this.disconnect();
2171
+ for (const current of Object.values(this.views)) current.state = emptyDeveloperWorkspaceView();
2172
+ }
2173
+ }
2174
+ }
2175
+ finishRequest(id3, error) {
2176
+ const pending = this.pending.get(id3);
2177
+ if (!pending) return;
2178
+ this.pending.delete(id3);
2179
+ pending.cleanup();
2180
+ pending.reject(error);
2181
+ }
2182
+ failRequests() {
2183
+ for (const [id3, request] of this.pending) this.finishRequest(id3, this.requestError(request.operation, "developer.result_unknown"));
2184
+ }
2185
+ requestError(operation, code) {
2186
+ return new DeveloperRealtimeClientError(code, operation === "send" || operation === "receipt" ? "unknown" : void 0);
2187
+ }
2188
+ observed() {
2189
+ return this.connectionListeners.size > 0 || this.kinds().some((kind) => this.views[kind].listeners.size > 0);
2190
+ }
2191
+ current(connection) {
2192
+ return this.connection === connection && !connection.abort.signal.aborted && !this.closed;
2193
+ }
2194
+ clearRetry() {
2195
+ clearTimeout(this.retryTimer);
2196
+ this.retryTimer = void 0;
2197
+ }
2198
+ kinds() {
2199
+ return ["agent", "products"];
2200
+ }
2201
+ nextId() {
2202
+ const value = this.ports.newId();
2203
+ if (!id(value)) throw new DeveloperRealtimeClientError("developer.identity_invalid");
2204
+ return value;
2205
+ }
2206
+ };
2207
+ function id(value) {
2208
+ return typeof value === "string" && value.length > 0 && value.length <= 160 && !/[\u0000-\u0020\u007f]/u.test(value);
2209
+ }
2210
+ function forbidden(error) {
2211
+ if (!error || typeof error !== "object") return false;
2212
+ const value = error;
2213
+ return value.status === 401 || value.status === 403 || value.code === "developer.forbidden" || value.code === "developer.workspace_forbidden";
2214
+ }
2215
+ function decodeDeveloperViewerFrame(raw) {
2216
+ const invalid4 = () => {
2217
+ throw new DeveloperRealtimeClientError("developer.invalid_frame");
2218
+ };
2219
+ if (typeof raw !== "string" || new TextEncoder().encode(raw).length > DEVELOPER_REALTIME_LIMITS.frameBytes) return invalid4();
2220
+ let frame;
2221
+ try {
2222
+ frame = JSON.parse(raw);
2223
+ } catch {
2224
+ return invalid4();
2225
+ }
2226
+ if (!frame || typeof frame !== "object" || Array.isArray(frame)) return invalid4();
2227
+ if (!validDeveloperPayloadPart(frame)) return invalid4();
2228
+ if (frame.type === "ready" && frame.version === 1 && (frame.generation === null || id(frame.generation))) return frame;
2229
+ if (frame.type === "host-state" && (frame.state === "offline" && frame.generation === null || frame.state === "online" && id(frame.generation))) return frame;
2230
+ if ((frame.type === "snapshot" || frame.type === "event") && id(frame.generation) && id(frame.subscriptionId) && id(frame.streamId) && Number.isSafeInteger(frame.sequence) && Number(frame.sequence) >= 0 && "payload" in frame) return frame;
2231
+ if (frame.type === "result" && id(frame.requestId) && typeof frame.ok === "boolean" && "payload" in frame) return frame;
2232
+ if (frame.type === "error" && id(frame.code) && (frame.requestId === void 0 || id(frame.requestId)) && (frame.subscriptionId === void 0 || id(frame.subscriptionId))) return frame;
2233
+ return invalid4();
2234
+ }
2235
+
2236
+ // ../websocket-transport.ts
2237
+ function openWorkspaceReadWebSocket(socketUrl, binding, events, signal, create = (url, protocols) => new WebSocket(url, protocols)) {
2238
+ let url;
2239
+ try {
2240
+ url = new URL(socketUrl);
2241
+ if (url.protocol !== "wss:" || url.username || url.password || url.search || url.hash || !/^\/api\/project\/[1-9]\d*\/env\/prod\/ext\/developer\/runtime\/developer\/socket$/u.test(url.pathname)) throw new Error();
2242
+ for (const key of ["hostDeviceId", "workspaceId", "conversationId"]) {
2243
+ const value = binding[key];
2244
+ if (!value || value.length > 160 || /[\u0000-\u0020]/u.test(value)) throw new Error();
2245
+ url.searchParams.set(key, value);
2246
+ }
2247
+ } catch {
2248
+ return Promise.reject(new DeveloperRealtimeClientError("developer.endpoint_invalid"));
2249
+ }
2250
+ return openSocket(url.href, ["kuafu.developer.v1"], "kuafu.developer.v1", events, signal, create);
2251
+ }
2252
+ function openDeveloperWebSocket(ticket, events, signal, create = (url, protocols) => new WebSocket(url, protocols)) {
2253
+ if (signal.aborted) return Promise.reject(new DeveloperRealtimeClientError("developer.request_cancelled"));
2254
+ let url;
2255
+ try {
2256
+ url = new URL(ticket.socketUrl);
2257
+ } catch {
2258
+ return Promise.reject(new DeveloperRealtimeClientError("developer.endpoint_invalid"));
2259
+ }
2260
+ if (url.protocol !== "wss:" || url.username || url.password || url.search || url.hash || ticket.socketUrl.length > 2048 || !/^\/api\/project\/[1-9][0-9]*\/env\/[a-z0-9][a-z0-9_-]{0,62}\/ext\/developer\/runtime\/developer\/socket$/u.test(url.pathname) || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u.test(ticket.ticket) || ticket.ticket.length > 7600 || !Number.isSafeInteger(ticket.expiresAt) || ticket.expiresAt <= Date.now()) {
2261
+ return Promise.reject(new DeveloperRealtimeClientError("developer.endpoint_invalid"));
2262
+ }
2263
+ return openSocket(url.href, ["kuafu.developer.v1", `ticket.${ticket.ticket}`], "kuafu.developer.v1", events, signal, create);
2264
+ }
2265
+ function openProductPreviewWebSocket(socketUrl, events, signal, create = (url, protocols) => new WebSocket(url, protocols)) {
2266
+ try {
2267
+ if (new URL(socketUrl).protocol !== "wss:") throw new Error();
2268
+ readProductPreviewSocketUrl(socketUrl);
2269
+ } catch {
2270
+ return Promise.reject(new DeveloperRealtimeClientError("developer.endpoint_invalid"));
2271
+ }
2272
+ return openSocket(socketUrl, ["kuafu.product-preview.v1"], "kuafu.product-preview.v1", events, signal, create);
2273
+ }
2274
+ function openSocket(url, protocols, protocol, events, signal, create) {
2275
+ if (signal.aborted) return Promise.reject(new DeveloperRealtimeClientError("developer.request_cancelled"));
2276
+ return new Promise((resolve, reject) => {
2277
+ let socket;
2278
+ try {
2279
+ socket = create(url, protocols);
2280
+ } catch {
2281
+ reject(new DeveloperRealtimeClientError("developer.transport_unavailable"));
2282
+ return;
2283
+ }
2284
+ let opened = false, closed = false, heartbeat;
2285
+ const cleanup = () => {
2286
+ clearInterval(heartbeat);
2287
+ heartbeat = void 0;
2288
+ signal.removeEventListener("abort", abort);
2289
+ socket.removeEventListener("open", open);
2290
+ socket.removeEventListener("message", message);
2291
+ socket.removeEventListener("error", failed);
2292
+ socket.removeEventListener("close", ended);
2293
+ };
2294
+ const release = () => {
2295
+ if (closed) return;
2296
+ closed = true;
2297
+ cleanup();
2298
+ try {
2299
+ socket.close(1e3, "developer.viewer_released");
2300
+ } catch {
2301
+ }
2302
+ };
2303
+ const abort = () => {
2304
+ release();
2305
+ if (!opened) reject(new DeveloperRealtimeClientError("developer.request_cancelled"));
2306
+ };
2307
+ const failed = () => {
2308
+ if (closed) return;
2309
+ release();
2310
+ if (opened) events.failed();
2311
+ else reject(new DeveloperRealtimeClientError("developer.transport_unavailable"));
2312
+ };
2313
+ const ended = () => {
2314
+ if (closed) return;
2315
+ closed = true;
2316
+ cleanup();
2317
+ if (opened) events.closed();
2318
+ else reject(new DeveloperRealtimeClientError("developer.transport_unavailable"));
2319
+ };
2320
+ const message = (event) => {
2321
+ if (!closed && opened) events.message(event.data);
2322
+ };
2323
+ const open = () => {
2324
+ if (closed) return;
2325
+ if (signal.aborted) {
2326
+ abort();
2327
+ return;
2328
+ }
2329
+ if (socket.protocol !== protocol) {
2330
+ failed();
2331
+ return;
2332
+ }
2333
+ opened = true;
2334
+ if (typeof socket.sendControlPing === "function") heartbeat = setInterval(() => {
2335
+ if (closed || socket.readyState !== 1) return;
2336
+ try {
2337
+ socket.sendControlPing();
2338
+ } catch {
2339
+ failed();
2340
+ }
2341
+ }, 3e4);
2342
+ resolve({
2343
+ send(text2) {
2344
+ if (closed || socket.readyState !== 1 || new TextEncoder().encode(text2).length + socket.bufferedAmount > DEVELOPER_REALTIME_LIMITS.socketBufferedBytes) {
2345
+ throw new DeveloperRealtimeClientError("developer.transport_unavailable");
2346
+ }
2347
+ socket.send(text2);
2348
+ },
2349
+ async sendBinary(bytes, transferSignal) {
2350
+ while (!closed && !transferSignal.aborted && socket.readyState === 1 && socket.bufferedAmount + bytes.byteLength > DEVELOPER_REALTIME_LIMITS.socketBufferedBytes / 2)
2351
+ await new Promise((done) => setTimeout(done, 8));
2352
+ if (closed || transferSignal.aborted || socket.readyState !== 1 || bytes.byteLength > 64 * 1024 + 10)
2353
+ throw new DeveloperRealtimeClientError("developer.transport_unavailable");
2354
+ socket.send(bytes);
2355
+ },
2356
+ close: release
2357
+ });
2358
+ };
2359
+ socket.addEventListener("open", open);
2360
+ socket.addEventListener("message", message);
2361
+ socket.addEventListener("error", failed);
2362
+ socket.addEventListener("close", ended);
2363
+ signal.addEventListener("abort", abort, { once: true });
2364
+ if (signal.aborted) abort();
2365
+ });
2366
+ }
2367
+
2368
+ // ../host-connection.ts
2369
+ var DeveloperHostConnection = class {
2370
+ constructor(ports) {
2371
+ this.ports = ports;
2372
+ this.budget = ports.budget ?? new DeveloperHostBudget();
2373
+ }
2374
+ current;
2375
+ children = /* @__PURE__ */ new Map();
2376
+ closing = /* @__PURE__ */ new Set();
2377
+ cleanup = /* @__PURE__ */ new Set();
2378
+ stopped = true;
2379
+ retryTimer;
2380
+ attempt = 0;
2381
+ budget;
2382
+ workspaces = /* @__PURE__ */ new Set();
2383
+ start() {
2384
+ this.stopped = false;
2385
+ if (!this.current && !this.retryTimer) void this.connect();
2386
+ }
2387
+ stop() {
2388
+ this.stopped = true;
2389
+ clearTimeout(this.retryTimer);
2390
+ this.retryTimer = void 0;
2391
+ this.disconnect();
2392
+ }
2393
+ retry() {
2394
+ if (this.stopped) return;
2395
+ clearTimeout(this.retryTimer);
2396
+ this.retryTimer = void 0;
2397
+ this.disconnect();
2398
+ this.attempt = 0;
2399
+ void this.connect();
2400
+ }
2401
+ async close() {
2402
+ this.stop();
2403
+ while (this.closing.size) await Promise.all([...this.closing]);
2404
+ const settled = await Promise.allSettled([...this.cleanup].map((release) => release()));
2405
+ const errors = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2406
+ if (errors.length) throw new AggregateError(errors, "developer.channel_cleanup_failed");
2407
+ }
2408
+ removeWorkspace(workspaceId) {
2409
+ this.workspaces.delete(workspaceId);
2410
+ for (const [id3, child] of this.children) if (developerChannelWorkspace(child.grant.target) === workspaceId) this.closeChild(id3);
2411
+ }
2412
+ setWorkspaces(workspaceIds) {
2413
+ const wanted = new Set(workspaceIds);
2414
+ for (const id3 of this.workspaces) if (!wanted.has(id3)) this.removeWorkspace(id3);
2415
+ this.workspaces = wanted;
2416
+ }
2417
+ active(current) {
2418
+ return !this.stopped && this.current === current && !current.abort.signal.aborted;
2419
+ }
2420
+ async connect() {
2421
+ if (this.stopped || this.current) return;
2422
+ const current = { abort: new AbortController(), generation: null, early: [], earlyBytes: 0 };
2423
+ this.current = current;
2424
+ this.ports.connectionState?.("connecting");
2425
+ try {
2426
+ current.ticket = await this.ports.authorize(current.abort.signal);
2427
+ if (!this.active(current)) return;
2428
+ if (!Number.isSafeInteger(current.ticket.expiresAt) || current.ticket.expiresAt <= Date.now()) throw new Error("developer.ticket_invalid");
2429
+ current.handshake = setTimeout(() => this.failed(current), DEVELOPER_CHANNEL_LIMITS.handshakeMs);
2430
+ const socket = await this.ports.open(current.ticket, {
2431
+ message: (raw) => {
2432
+ if (!this.active(current)) return;
2433
+ if (!current.socket) {
2434
+ if (typeof raw !== "string" || current.earlyBytes + new TextEncoder().encode(raw).length > DEVELOPER_REALTIME_LIMITS.socketBufferedBytes) {
2435
+ this.failed(current);
2436
+ return;
2437
+ }
2438
+ current.early.push(raw);
2439
+ current.earlyBytes += new TextEncoder().encode(raw).length;
2440
+ return;
2441
+ }
2442
+ this.receive(current, raw);
2443
+ },
2444
+ closed: () => {
2445
+ if (this.active(current)) {
2446
+ this.ports.diagnostic?.("developer.control_socket_closed");
2447
+ this.failed(current);
2448
+ }
2449
+ },
2450
+ failed: () => {
2451
+ if (this.active(current)) {
2452
+ this.ports.diagnostic?.("developer.control_socket_error");
2453
+ this.failed(current);
2454
+ }
2455
+ }
2456
+ }, current.abort.signal);
2457
+ if (!this.active(current)) {
2458
+ socket.close();
2459
+ return;
2460
+ }
2461
+ current.socket = socket;
2462
+ const early = current.early;
2463
+ current.early = [];
2464
+ current.earlyBytes = 0;
2465
+ for (const frame of early) this.receive(current, frame);
2466
+ } catch (error) {
2467
+ if (!this.active(current)) return;
2468
+ if ([401, 403].includes(Number(error?.status))) {
2469
+ this.disconnect();
2470
+ this.ports.diagnostic?.("developer.host_forbidden");
2471
+ } else this.failed(current);
2472
+ }
2473
+ }
2474
+ receive(current, raw) {
2475
+ if (!this.active(current)) return;
2476
+ try {
2477
+ if (typeof raw !== "string" || new TextEncoder().encode(raw).length > DEVELOPER_REALTIME_LIMITS.frameBytes) throw new Error("developer.invalid_frame");
2478
+ const frame = JSON.parse(raw);
2479
+ if (frame.type === "ready" && frame.version === 1 && typeof frame.generation === "string") {
2480
+ if (current.generation && current.generation !== frame.generation) for (const id3 of [...this.children.keys()]) this.closeChild(id3);
2481
+ current.generation = frame.generation;
2482
+ this.ports.connectionState?.("ready");
2483
+ clearTimeout(current.handshake);
2484
+ current.handshake = void 0;
2485
+ this.attempt = 0;
2486
+ return;
2487
+ }
2488
+ if (frame.type === "channel.open") {
2489
+ if (frame.controlEpoch === current.generation && frame.expiresAt > Date.now()) void this.openChild(current, frame).catch(() => {
2490
+ if (this.active(current)) this.send({ type: "channel.failed", controlEpoch: frame.controlEpoch, channelId: frame.channelId, code: "developer.workspace_unavailable" });
2491
+ });
2492
+ return;
2493
+ }
2494
+ if (frame.type === "channel.close") {
2495
+ if (frame.controlEpoch === current.generation && typeof frame.channelId === "string") this.closeChild(frame.channelId);
2496
+ return;
2497
+ }
2498
+ if (frame.type === "error") throw new Error("developer.control_rejected");
2499
+ throw new Error("developer.invalid_frame");
2500
+ } catch {
2501
+ this.failed(current);
2502
+ }
2503
+ }
2504
+ async openChild(current, raw) {
2505
+ const grant = readDeveloperChannelGrant(raw);
2506
+ if (grant.controlEpoch !== current.generation || !current.ticket || !Number.isSafeInteger(raw.expiresAt) || raw.expiresAt <= Date.now() || typeof raw.ticket !== "string") throw new Error("developer.channel_forbidden");
2507
+ const workspaceId = developerChannelWorkspace(grant.target);
2508
+ if (this.ports.workspaceExists && !await this.ports.workspaceExists(workspaceId)) {
2509
+ if (this.active(current)) this.send({ type: "channel.failed", controlEpoch: grant.controlEpoch, channelId: grant.channelId, code: "developer.workspace_removed" });
2510
+ return;
2511
+ }
2512
+ if (!this.active(current) || current.generation !== grant.controlEpoch || raw.expiresAt <= Date.now()) return;
2513
+ if (!this.ports.ownsWorkspace(workspaceId)) {
2514
+ this.send({ type: "channel.failed", controlEpoch: grant.controlEpoch, channelId: grant.channelId, code: "developer.workspace_unavailable" });
2515
+ return;
2516
+ }
2517
+ const previous = this.children.get(grant.channelId);
2518
+ if (previous) {
2519
+ if (JSON.stringify(previous.grant) !== JSON.stringify(grant)) throw new Error("developer.channel_forbidden");
2520
+ return;
2521
+ }
2522
+ for (const [id3, item] of this.children) if (developerChannelKey(item.grant.target) === developerChannelKey(grant.target)) this.closeChild(id3);
2523
+ let release;
2524
+ try {
2525
+ release = this.budget.acquireChannel();
2526
+ } catch {
2527
+ this.send({ type: "channel.failed", controlEpoch: grant.controlEpoch, channelId: grant.channelId, code: "developer.channel_capacity" });
2528
+ return;
2529
+ }
2530
+ const ticket = { ...current.ticket, ticket: raw.ticket, expiresAt: raw.expiresAt };
2531
+ const worker = new DeveloperHostChannelConnection({
2532
+ ...this.ports,
2533
+ channel: grant,
2534
+ budget: this.budget,
2535
+ preview: grant.target.kind === "product-preview" ? this.ports.preview : void 0,
2536
+ authorize: async () => ticket,
2537
+ disconnected: () => {
2538
+ if (this.children.get(grant.channelId)?.worker !== worker) return;
2539
+ this.closeChild(grant.channelId);
2540
+ this.send({ type: "channel.failed", controlEpoch: grant.controlEpoch, channelId: grant.channelId, code: "developer.channel_disconnected" });
2541
+ }
2542
+ });
2543
+ this.children.set(grant.channelId, { grant, worker, release });
2544
+ worker.start();
2545
+ }
2546
+ closeChild(id3) {
2547
+ const child = this.children.get(id3);
2548
+ if (!child) return;
2549
+ this.children.delete(id3);
2550
+ let pending;
2551
+ const release = () => {
2552
+ if (!pending) {
2553
+ pending = child.worker.close().then(child.release);
2554
+ void pending.then(() => this.cleanup.delete(release), () => {
2555
+ pending = void 0;
2556
+ });
2557
+ }
2558
+ return pending;
2559
+ };
2560
+ this.cleanup.add(release);
2561
+ const work = release().catch(() => {
2562
+ this.ports.diagnostic?.("developer.channel_cleanup_failed");
2563
+ }).finally(() => {
2564
+ this.closing.delete(work);
2565
+ });
2566
+ this.closing.add(work);
2567
+ }
2568
+ send(value) {
2569
+ const current = this.current;
2570
+ if (!current?.generation || !current.socket || !this.active(current)) return;
2571
+ try {
2572
+ current.socket.send(JSON.stringify(value));
2573
+ } catch {
2574
+ this.failed(current);
2575
+ }
2576
+ }
2577
+ failed(current) {
2578
+ if (!this.active(current)) return;
2579
+ this.disconnect();
2580
+ if (!this.stopped) this.retryTimer = setTimeout(() => {
2581
+ this.retryTimer = void 0;
2582
+ void this.connect();
2583
+ }, Math.min(8e3, 500 * 2 ** Math.min(this.attempt++, 4)));
2584
+ }
2585
+ disconnect() {
2586
+ const current = this.current;
2587
+ this.current = void 0;
2588
+ this.ports.connectionState?.("offline");
2589
+ for (const id3 of [...this.children.keys()]) this.closeChild(id3);
2590
+ if (!current) return;
2591
+ current.abort.abort();
2592
+ clearTimeout(current.handshake);
2593
+ try {
2594
+ current.socket?.close();
2595
+ } catch {
2596
+ this.ports.diagnostic?.("developer.socket_release_failed");
2597
+ }
2598
+ }
2599
+ };
2600
+ var DeveloperHostChannelConnection = class {
2601
+ constructor(ports) {
2602
+ this.ports = ports;
2603
+ this.budget = ports.budget ?? new DeveloperHostBudget();
2604
+ if (ports.preview) this.preview = new DeveloperProductPreviewHost({
2605
+ ...ports.preview,
2606
+ connections: (sessions) => {
2607
+ if (ports.channel?.target.kind === "product-preview") ports.preview?.connections?.(ports.channel.channelId, ports.channel.target.product, sessions);
2608
+ },
2609
+ budget: this.budget,
2610
+ ownsWorkspace: (id3) => this.owns(id3),
2611
+ diagnostic: (code) => ports.diagnostic?.(code),
2612
+ send: (frame) => {
2613
+ const current = this.current;
2614
+ if (current && this.active(current)) current.socket?.send(JSON.stringify(frame));
2615
+ },
2616
+ sendBinary: async (bytes, signal) => {
2617
+ const current = this.current;
2618
+ if (!current || !this.active(current) || !current.socket?.sendBinary) throw new Error("developer.preview_transport_unavailable");
2619
+ await current.socket.sendBinary(bytes, signal);
2620
+ }
2621
+ });
2622
+ }
2623
+ current;
2624
+ sources = /* @__PURE__ */ new Map();
2625
+ requests = /* @__PURE__ */ new Map();
2626
+ requestTimers = /* @__PURE__ */ new Map();
2627
+ requestBudgets = /* @__PURE__ */ new Map();
2628
+ budget;
2629
+ retryTimer;
2630
+ attempt = 0;
2631
+ stopped = true;
2632
+ transferSerial = 0;
2633
+ outgoing = [];
2634
+ outgoingBytes = 0;
2635
+ // 四段最坏JSON转义仍小于DO的1MiB缓冲预算,避免每段都串行承担远端RTT。
2636
+ waiting = /* @__PURE__ */ new Map();
2637
+ draining = false;
2638
+ preview;
2639
+ async close() {
2640
+ this.stop();
2641
+ await this.preview?.close();
2642
+ }
2643
+ start() {
2644
+ this.stopped = false;
2645
+ if (!this.current && !this.retryTimer) void this.connect();
2646
+ }
2647
+ stop() {
2648
+ this.stopped = true;
2649
+ clearTimeout(this.retryTimer);
2650
+ this.retryTimer = void 0;
2651
+ this.disconnect();
2652
+ }
2653
+ retry() {
2654
+ if (this.stopped) return;
2655
+ clearTimeout(this.retryTimer);
2656
+ this.retryTimer = void 0;
2657
+ this.disconnect();
2658
+ this.attempt = 0;
2659
+ void this.connect();
2660
+ }
2661
+ async connect() {
2662
+ if (this.stopped || this.current) return;
2663
+ const current = { abort: new AbortController(), generation: null, early: [], earlyBytes: 0 };
2664
+ this.current = current;
2665
+ try {
2666
+ const ticket = await this.ports.authorize(current.abort.signal);
2667
+ if (!this.active(current)) return;
2668
+ if (!Number.isSafeInteger(ticket.expiresAt) || ticket.expiresAt <= Date.now()) throw new DeveloperRealtimeClientError("developer.ticket_invalid");
2669
+ current.handshake = setTimeout(() => this.failed(current), 1e4);
2670
+ const socket = await this.ports.open(ticket, {
2671
+ message: (raw) => {
2672
+ if (!this.active(current)) return;
2673
+ if (!current.socket) {
2674
+ const bytes = typeof raw === "string" ? new TextEncoder().encode(raw).length : raw instanceof ArrayBuffer ? raw.byteLength : Infinity;
2675
+ if (bytes > DEVELOPER_REALTIME_LIMITS.frameBytes || current.early.length >= 512 || current.earlyBytes + bytes > DEVELOPER_REALTIME_LIMITS.socketBufferedBytes) {
2676
+ this.failed(current);
2677
+ return;
2678
+ }
2679
+ current.early.push(raw);
2680
+ current.earlyBytes += bytes;
2681
+ return;
2682
+ }
2683
+ this.receive(current, raw);
2684
+ },
2685
+ closed: () => {
2686
+ if (this.active(current)) {
2687
+ this.ports.diagnostic?.(this.ports.channel?.target.kind === "product-preview" ? "developer.product_socket_closed" : "developer.workspace_socket_closed");
2688
+ this.failed(current);
2689
+ }
2690
+ },
2691
+ failed: () => {
2692
+ if (this.active(current)) {
2693
+ this.ports.diagnostic?.(this.ports.channel?.target.kind === "product-preview" ? "developer.product_socket_error" : "developer.workspace_socket_error");
2694
+ this.failed(current);
2695
+ }
2696
+ }
2697
+ }, current.abort.signal);
2698
+ if (!this.active(current)) {
2699
+ socket.close();
2700
+ return;
2701
+ }
2702
+ current.socket = socket;
2703
+ const early = current.early;
2704
+ current.early = [];
2705
+ current.earlyBytes = 0;
2706
+ for (const frame of early) this.receive(current, frame);
2707
+ } catch (error) {
2708
+ if (!this.active(current)) return;
2709
+ const value = error;
2710
+ if (value?.status === 401 || value?.status === 403 || value?.code === "developer.forbidden") {
2711
+ this.disconnect();
2712
+ this.ports.diagnostic?.("developer.host_forbidden");
2713
+ } else this.failed(current);
2714
+ }
2715
+ }
2716
+ receive(current, raw) {
2717
+ if (!this.active(current)) return;
2718
+ let frame;
2719
+ try {
2720
+ if (raw instanceof ArrayBuffer) {
2721
+ if (!this.preview?.receive(raw)) throw new Error("developer.invalid_frame");
2722
+ return;
2723
+ }
2724
+ frame = decodeDeveloperHostFrame(raw);
2725
+ if (isPreviewControl(frame)) {
2726
+ if (frame.type === "preview.prepare" && this.ports.channel && (this.ports.channel.target.kind !== "product-preview" || JSON.stringify(frame.session.target) !== JSON.stringify(this.ports.channel.target.product))) throw new Error("developer.preview_scope_changed");
2727
+ if (!this.preview?.receive(frame)) throw new Error("developer.invalid_frame");
2728
+ return;
2729
+ }
2730
+ } catch {
2731
+ this.disconnect();
2732
+ this.ports.diagnostic?.("developer.invalid_frame");
2733
+ return;
2734
+ }
2735
+ if (frame.type === "ready") {
2736
+ this.releaseWork(false);
2737
+ if (current.generation === frame.generation) this.preview?.resume();
2738
+ else this.preview?.reset(frame.generation);
2739
+ current.generation = frame.generation;
2740
+ this.attempt = 0;
2741
+ clearTimeout(current.handshake);
2742
+ current.handshake = void 0;
2743
+ return;
2744
+ }
2745
+ if (frame.type === "error") {
2746
+ this.disconnect();
2747
+ this.ports.diagnostic?.(frame.code);
2748
+ return;
2749
+ }
2750
+ if (!current.generation) {
2751
+ this.disconnect();
2752
+ this.ports.diagnostic?.("developer.ready_required");
2753
+ return;
2754
+ }
2755
+ if (frame.generation !== current.generation) return;
2756
+ if (this.ports.channel?.target.kind === "product-preview") {
2757
+ this.failed(current);
2758
+ return;
2759
+ }
2760
+ if (frame.type === "fragment-ack") {
2761
+ const pending = this.waiting.get(frame.index);
2762
+ if (pending?.id === frame.id) {
2763
+ clearTimeout(pending.timer);
2764
+ this.waiting.delete(frame.index);
2765
+ this.drain(current);
2766
+ }
2767
+ return;
2768
+ }
2769
+ if (frame.type === "unsubscribe") {
2770
+ this.releaseSource(frame.streamId);
2771
+ return;
2772
+ }
2773
+ if (!this.owns(frame.workspaceId)) {
2774
+ if (frame.type === "request") this.send(current, {
2775
+ type: "result",
2776
+ generation: frame.generation,
2777
+ requestId: frame.requestId,
2778
+ ok: false,
2779
+ payload: { code: "developer.workspace_forbidden" }
2780
+ });
2781
+ else {
2782
+ this.disconnect();
2783
+ this.ports.diagnostic?.("developer.workspace_forbidden");
2784
+ }
2785
+ return;
2786
+ }
2787
+ if (frame.type === "subscribe") this.observe(current, frame);
2788
+ else void this.execute(current, frame);
2789
+ }
2790
+ observe(current, frame) {
2791
+ if (this.sources.has(frame.streamId)) return;
2792
+ if (this.sources.size >= DEVELOPER_REALTIME_LIMITS.subscriptionsPerViewer * DEVELOPER_REALTIME_LIMITS.viewersPerHost) {
2793
+ this.failed(current);
2794
+ return;
2795
+ }
2796
+ let releaseBudget;
2797
+ try {
2798
+ releaseBudget = this.budget.acquireStream();
2799
+ } catch {
2800
+ this.failed(current);
2801
+ return;
2802
+ }
2803
+ const source = { releaseBudget, abort: new AbortController(), sequence: -1, kind: frame.kind };
2804
+ this.sources.set(frame.streamId, source);
2805
+ const publish = (type, payload) => {
2806
+ if (!this.active(current) || this.sources.get(frame.streamId) !== source) return;
2807
+ if (!this.owns(frame.workspaceId) || type === "event" && source.sequence < 0) {
2808
+ this.failed(current);
2809
+ return;
2810
+ }
2811
+ this.send(current, { type, generation: frame.generation, streamId: frame.streamId, sequence: source.sequence + 1, payload }, source);
2812
+ };
2813
+ try {
2814
+ const release = this.ports.observe(frame.workspaceId, frame.kind, {
2815
+ snapshot: (payload) => publish("snapshot", payload),
2816
+ event: (payload) => publish("event", payload),
2817
+ closed: () => {
2818
+ if (this.sources.get(frame.streamId) === source) this.failed(current);
2819
+ }
2820
+ }, source.abort.signal);
2821
+ void Promise.resolve(release).then((stop) => {
2822
+ if (!this.active(current) || this.sources.get(frame.streamId) !== source) this.release(stop);
2823
+ else source.release = stop;
2824
+ }, () => {
2825
+ if (this.sources.get(frame.streamId) === source) this.failed(current);
2826
+ });
2827
+ } catch {
2828
+ this.failed(current);
2829
+ }
2830
+ }
2831
+ async execute(current, frame) {
2832
+ if (this.requests.has(frame.requestId) || this.requests.size >= DEVELOPER_REALTIME_LIMITS.requestsPerViewer * DEVELOPER_REALTIME_LIMITS.viewersPerHost) {
2833
+ this.send(current, { type: "result", generation: frame.generation, requestId: frame.requestId, ok: false, payload: { code: "developer.request_limit" } });
2834
+ return;
2835
+ }
2836
+ let releaseBudget;
2837
+ try {
2838
+ releaseBudget = this.budget.acquireStream();
2839
+ } catch {
2840
+ this.send(current, { type: "result", generation: frame.generation, requestId: frame.requestId, ok: false, payload: { code: "developer.request_limit" } });
2841
+ return;
2842
+ }
2843
+ const abort = new AbortController();
2844
+ this.requests.set(frame.requestId, abort);
2845
+ this.requestBudgets.set(abort, releaseBudget);
2846
+ const timer = setTimeout(() => {
2847
+ if (this.requests.get(frame.requestId) !== abort) return;
2848
+ this.requests.delete(frame.requestId);
2849
+ this.requestTimers.delete(abort);
2850
+ this.requestBudgets.get(abort)?.();
2851
+ this.requestBudgets.delete(abort);
2852
+ abort.abort();
2853
+ this.send(current, {
2854
+ type: "result",
2855
+ generation: frame.generation,
2856
+ requestId: frame.requestId,
2857
+ ok: false,
2858
+ payload: { code: "developer.result_unknown", ...frame.operation === "send" || frame.operation === "receipt" ? { outcome: "unknown" } : {} }
2859
+ });
2860
+ }, DEVELOPER_REALTIME_LIMITS.requestTimeoutMs);
2861
+ this.requestTimers.set(abort, timer);
2862
+ try {
2863
+ const result = await this.ports.request({ workspaceId: frame.workspaceId, subject: frame.subject, operation: frame.operation, input: frame.input }, abort.signal);
2864
+ if (this.active(current) && this.requests.get(frame.requestId) === abort) this.send(
2865
+ current,
2866
+ { type: "result", generation: frame.generation, requestId: frame.requestId, ok: result.ok === true, payload: result.payload }
2867
+ );
2868
+ } catch {
2869
+ if (this.active(current) && this.requests.get(frame.requestId) === abort) this.send(current, {
2870
+ type: "result",
2871
+ generation: frame.generation,
2872
+ requestId: frame.requestId,
2873
+ ok: false,
2874
+ payload: { code: "developer.request_failed", ...frame.operation === "send" || frame.operation === "receipt" ? { outcome: "unknown" } : {} }
2875
+ });
2876
+ } finally {
2877
+ releaseBudget();
2878
+ this.requestBudgets.delete(abort);
2879
+ clearTimeout(timer);
2880
+ this.requestTimers.delete(abort);
2881
+ if (this.requests.get(frame.requestId) === abort) this.requests.delete(frame.requestId);
2882
+ }
2883
+ }
2884
+ send(current, frame, source) {
2885
+ if (!this.active(current) || !current.socket) return;
2886
+ let releaseBudget;
2887
+ try {
2888
+ const bytes = new TextEncoder().encode(JSON.stringify(frame)).length;
2889
+ if (this.outgoingBytes + bytes > 64 * 1024 * 1024) throw new Error("developer.assembly_limit");
2890
+ releaseBudget = this.budget.acquireBytes(bytes);
2891
+ const id3 = String(++this.transferSerial);
2892
+ const parts = source?.kind === "products" ? [{ payload: frame.payload }] : [...fragmentDeveloperPayload(frame.payload, id3)];
2893
+ const start = source ? source.sequence + 1 : 0;
2894
+ if (source) source.sequence += parts.length;
2895
+ function* frames() {
2896
+ for (const [index, part] of parts.entries()) yield {
2897
+ ...frame,
2898
+ ...part,
2899
+ ...frame.type !== "result" ? { sequence: start + index } : {}
2900
+ };
2901
+ }
2902
+ this.outgoing.push({ frames: frames(), bytes, releaseBudget, ...frame.type !== "result" ? { streamId: frame.streamId } : {} });
2903
+ this.outgoingBytes += bytes;
2904
+ this.drain(current);
2905
+ } catch {
2906
+ releaseBudget?.();
2907
+ this.failed(current);
2908
+ }
2909
+ }
2910
+ drain(current) {
2911
+ if (this.draining) return;
2912
+ this.draining = true;
2913
+ try {
2914
+ while (this.active(current) && current.socket && this.waiting.size < 4 && this.outgoing.length) {
2915
+ const entry = this.outgoing[0];
2916
+ const next = entry.frames.next();
2917
+ if (next.done) {
2918
+ if (this.waiting.size) break;
2919
+ this.outgoing.shift();
2920
+ this.outgoingBytes -= entry.bytes;
2921
+ entry.releaseBudget?.();
2922
+ continue;
2923
+ }
2924
+ const frame = next.value, text2 = JSON.stringify(frame);
2925
+ if (new TextEncoder().encode(text2).length > DEVELOPER_REALTIME_LIMITS.frameBytes) throw new Error("developer.frame_limit");
2926
+ if (frame.fragment) this.waiting.set(frame.fragment.index, {
2927
+ id: frame.fragment.id,
2928
+ timer: setTimeout(() => this.failed(current), 1e4)
2929
+ });
2930
+ current.socket.send(text2);
2931
+ }
2932
+ } catch {
2933
+ this.failed(current);
2934
+ } finally {
2935
+ this.draining = false;
2936
+ }
2937
+ }
2938
+ failed(current) {
2939
+ if (!this.active(current)) return;
2940
+ this.disconnect();
2941
+ if (this.ports.disconnected) {
2942
+ this.ports.disconnected();
2943
+ return;
2944
+ }
2945
+ if (!this.stopped) this.retryTimer = setTimeout(() => {
2946
+ this.retryTimer = void 0;
2947
+ void this.connect();
2948
+ }, Math.min(8e3, 500 * 2 ** Math.min(this.attempt++, 4)));
2949
+ }
2950
+ active(current) {
2951
+ return !this.stopped && this.current === current && !current.abort.signal.aborted;
2952
+ }
2953
+ disconnect() {
2954
+ const current = this.current;
2955
+ this.current = void 0;
2956
+ this.releaseWork();
2957
+ if (!current) return;
2958
+ current.abort.abort();
2959
+ clearTimeout(current.handshake);
2960
+ current.early = [];
2961
+ try {
2962
+ current.socket?.close();
2963
+ } catch {
2964
+ this.ports.diagnostic?.("developer.socket_release_failed");
2965
+ }
2966
+ }
2967
+ releaseSource(id3) {
2968
+ const source = this.sources.get(id3);
2969
+ if (!source) return;
2970
+ this.sources.delete(id3);
2971
+ source.releaseBudget?.();
2972
+ source.abort.abort();
2973
+ if (source.release) this.release(source.release);
2974
+ if (this.outgoing[0]?.streamId === id3) {
2975
+ for (const pending of this.waiting.values()) clearTimeout(pending.timer);
2976
+ this.waiting.clear();
2977
+ }
2978
+ this.outgoing = this.outgoing.filter((entry) => {
2979
+ if (entry.streamId !== id3) return true;
2980
+ this.outgoingBytes -= entry.bytes;
2981
+ entry.releaseBudget?.();
2982
+ return false;
2983
+ });
2984
+ if (this.current) this.drain(this.current);
2985
+ }
2986
+ release(stop) {
2987
+ try {
2988
+ stop();
2989
+ } catch {
2990
+ this.ports.diagnostic?.("developer.source_release_failed");
2991
+ }
2992
+ }
2993
+ owns(workspaceId) {
2994
+ try {
2995
+ return (!this.ports.channel || developerChannelWorkspace(this.ports.channel.target) === workspaceId) && this.ports.ownsWorkspace(workspaceId);
2996
+ } catch {
2997
+ this.ports.diagnostic?.("developer.workspace_unavailable");
2998
+ return false;
2999
+ }
3000
+ }
3001
+ releaseWork(resetPreview = true) {
3002
+ if (resetPreview) this.preview?.reset();
3003
+ for (const pending of this.waiting.values()) clearTimeout(pending.timer);
3004
+ this.waiting.clear();
3005
+ for (const entry of this.outgoing) entry.releaseBudget?.();
3006
+ this.outgoing = [];
3007
+ this.outgoingBytes = 0;
3008
+ for (const id3 of [...this.sources.keys()]) this.releaseSource(id3);
3009
+ for (const [abort, timer] of this.requestTimers) {
3010
+ clearTimeout(timer);
3011
+ abort.abort();
3012
+ }
3013
+ this.requestTimers.clear();
3014
+ this.requests.clear();
3015
+ for (const release of this.requestBudgets.values()) release();
3016
+ this.requestBudgets.clear();
3017
+ }
3018
+ };
3019
+ function isPreviewControl(frame) {
3020
+ return frame.type.startsWith("preview.");
3021
+ }
3022
+ function decodeDeveloperHostFrame(raw) {
3023
+ const invalid4 = () => {
3024
+ throw new DeveloperRealtimeClientError("developer.invalid_frame");
3025
+ };
3026
+ if (typeof raw !== "string" || new TextEncoder().encode(raw).length > DEVELOPER_REALTIME_LIMITS.frameBytes) return invalid4();
3027
+ let frame;
3028
+ try {
3029
+ frame = JSON.parse(raw);
3030
+ } catch {
3031
+ return invalid4();
3032
+ }
3033
+ if (!frame || typeof frame !== "object" || Array.isArray(frame)) return invalid4();
3034
+ if (typeof frame.type === "string" && frame.type.startsWith("preview.")) return frame;
3035
+ if (frame.type === "ready" && frame.version === 1 && id2(frame.generation)) return frame;
3036
+ if (frame.type === "error" && id2(frame.code)) return frame;
3037
+ if (!id2(frame.generation)) return invalid4();
3038
+ if (frame.type === "fragment-ack" && id2(frame.id) && Number.isSafeInteger(frame.index) && Number(frame.index) >= 0) return frame;
3039
+ if (frame.type === "unsubscribe" && id2(frame.streamId)) return frame;
3040
+ if (frame.type === "subscribe" && id2(frame.streamId) && id2(frame.workspaceId) && (frame.kind === "agent" || frame.kind === "products")) return frame;
3041
+ if (frame.type === "request" && id2(frame.requestId) && id2(frame.workspaceId) && id2(frame.subject) && ["history", "send", "receipt", "file"].includes(String(frame.operation)) && "input" in frame) return frame;
3042
+ return invalid4();
3043
+ }
3044
+ function id2(value) {
3045
+ return typeof value === "string" && value.length > 0 && value.length <= 160 && !/[\u0000-\u0020\u007f]/u.test(value);
3046
+ }
3047
+
3048
+ // ../agent-question.ts
3049
+ import { normalizeWorkspaceId as normalizeWorkspaceId3, readWorkspaceQuestionReply } from "@kuafucloud/product-runtime-protocol";
3050
+ var object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
3051
+ var text = (value, limit) => typeof value === "string" && !!value.trim() && value.length <= limit;
3052
+ function readAgentQuestion(value) {
3053
+ if (!object(value) || value.type !== "agent.question" || !text(value.questionMessageId, 100) || !value.questionMessageId.startsWith("agent-question:") || !["waiting", "answered", "resolved"].includes(String(value.state)) || !Array.isArray(value.questions) || !value.questions.length || value.questions.length > 4) return null;
3054
+ try {
3055
+ normalizeWorkspaceId3(value.questionMessageId.slice(15));
3056
+ if (value.sessionId !== null) normalizeWorkspaceId3(String(value.sessionId));
3057
+ } catch {
3058
+ return null;
3059
+ }
3060
+ const questions = [];
3061
+ for (const item of value.questions) {
3062
+ if (!object(item) || !text(item.id, 128) || !text(item.header, 256) || !text(item.question, 16384) || typeof item.isOther !== "boolean" || !Array.isArray(item.options) || item.options.length > 20) return null;
3063
+ const options = [];
3064
+ for (const option of item.options) {
3065
+ if (!object(option) || !text(option.label, 1024) || typeof option.description !== "string" || option.description.length > 4096) return null;
3066
+ options.push({ label: option.label, description: option.description });
3067
+ }
3068
+ if (questions.some((question) => question.id === item.id)) return null;
3069
+ questions.push({ id: item.id, header: item.header, question: item.question, isOther: item.isOther, options });
3070
+ }
3071
+ let answers;
3072
+ if (value.answers !== void 0) {
3073
+ if (value.state !== "answered" || !object(value.answers) || Object.keys(value.answers).length !== questions.length) return null;
3074
+ answers = /* @__PURE__ */ Object.create(null);
3075
+ for (const question of questions) {
3076
+ const answer = value.answers[question.id];
3077
+ if (!Object.hasOwn(value.answers, question.id) || !Array.isArray(answer) || answer.length !== 1 || !text(answer[0], 16384) || question.options.length && !question.isOther && !question.options.some((option) => option.label === answer[0])) return null;
3078
+ answers[question.id] = [answer[0]];
3079
+ }
3080
+ }
3081
+ return {
3082
+ type: "agent.question",
3083
+ questionMessageId: value.questionMessageId,
3084
+ sessionId: value.sessionId,
3085
+ state: value.state,
3086
+ ...value.approval === true ? { approval: true } : {},
3087
+ questions,
3088
+ ...answers ? { answers } : {}
3089
+ };
3090
+ }
3091
+ function canAnswerAgentQuestion(question, sessionId) {
3092
+ return question.state === "waiting" && !!question.sessionId && question.sessionId === sessionId;
3093
+ }
3094
+ function createAgentQuestionReply(question, sessionId, values) {
3095
+ if (!canAnswerAgentQuestion(question, sessionId)) throw new Error("developer.question_expired");
3096
+ const answers = /* @__PURE__ */ Object.create(null);
3097
+ for (const item of question.questions) {
3098
+ const answer = Object.hasOwn(values, item.id) ? values[item.id] : "";
3099
+ if (!answer?.trim() || item.options.length && !item.isOther && !item.options.some((option) => option.label === answer)) throw new Error("developer.answer_required");
3100
+ answers[item.id] = [answer];
3101
+ }
3102
+ return readWorkspaceQuestionReply({ sessionId, questionMessageId: question.questionMessageId, answers });
3103
+ }
3104
+
3105
+ // ../agent-chat-model.ts
3106
+ import { readWorkspaceAttachment } from "@kuafucloud/product-runtime-protocol";
3107
+ function normalizeWorkspaceAgentServerMessage(input) {
3108
+ if (!input || typeof input !== "object") {
3109
+ return null;
3110
+ }
3111
+ const value = input;
3112
+ const type = typeof value.type === "string" ? value.type : "";
3113
+ if (!type) {
3114
+ return null;
3115
+ }
3116
+ switch (type) {
3117
+ case "message.delta":
3118
+ if (typeof value.id === "string" && typeof value.seq === "number" && (value.role === "assistant" || value.role === "system") && Array.isArray(value.delta)) {
3119
+ return {
3120
+ type,
3121
+ id: value.id,
3122
+ seq: value.seq,
3123
+ role: value.role,
3124
+ delta: normalizeContentParts(value.delta),
3125
+ runId: normalizeNullableString(value.runId) ?? void 0,
3126
+ agentId: normalizeNullableString(value.agentId) ?? void 0,
3127
+ parentRunId: normalizeNullableString(value.parentRunId)
3128
+ };
3129
+ }
3130
+ return null;
3131
+ case "message.commit":
3132
+ if (typeof value.id === "string" && typeof value.seq === "number" && (value.status === "complete" || value.status === "error")) {
3133
+ return {
3134
+ type,
3135
+ id: value.id,
3136
+ seq: value.seq,
3137
+ status: value.status,
3138
+ runId: normalizeNullableString(value.runId) ?? void 0,
3139
+ agentId: normalizeNullableString(value.agentId) ?? void 0,
3140
+ parentRunId: normalizeNullableString(value.parentRunId)
3141
+ };
3142
+ }
3143
+ return null;
3144
+ default:
3145
+ return null;
3146
+ }
3147
+ }
3148
+ function applyDelta(current, event) {
3149
+ const existing = current.find((m) => m.id === event.id);
3150
+ if (!existing) {
3151
+ return [
3152
+ ...current,
3153
+ {
3154
+ id: event.id,
3155
+ role: "assistant",
3156
+ content: [...event.delta],
3157
+ status: "in_progress",
3158
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
3159
+ }
3160
+ ];
3161
+ }
3162
+ return current.map((m) => {
3163
+ if (m.id !== event.id) {
3164
+ return m;
3165
+ }
3166
+ const merged = mergeDeltaParts(m.content, event.delta);
3167
+ return { ...m, content: merged };
3168
+ });
3169
+ }
3170
+ function applyCommit(current, event) {
3171
+ return current.map((m) => {
3172
+ if (m.id !== event.id) {
3173
+ return m;
3174
+ }
3175
+ return { ...m, status: event.status };
3176
+ });
3177
+ }
3178
+ function mergeDeltaParts(existing, delta) {
3179
+ const result = [...existing];
3180
+ for (const part of delta) {
3181
+ if (part.type === "text" && result.length > 0) {
3182
+ const last = result[result.length - 1];
3183
+ if (last.type === "text") {
3184
+ result[result.length - 1] = { type: "text", text: last.text + part.text };
3185
+ continue;
3186
+ }
3187
+ }
3188
+ if (part.type === "reasoning" && result.length > 0) {
3189
+ const last = result[result.length - 1];
3190
+ if (last.type === "reasoning") {
3191
+ result[result.length - 1] = { type: "reasoning", text: last.text + part.text };
3192
+ continue;
3193
+ }
3194
+ }
3195
+ const replaced = replaceStructuredPart(result, part);
3196
+ if (replaced) {
3197
+ continue;
3198
+ }
3199
+ result.push({ ...part });
3200
+ }
3201
+ return result;
3202
+ }
3203
+ function replaceStructuredPart(result, part) {
3204
+ const key = resolveStructuredPartKey(part);
3205
+ if (!key) {
3206
+ return false;
3207
+ }
3208
+ const index = result.findIndex((item) => resolveStructuredPartKey(item) === key);
3209
+ if (index < 0) {
3210
+ return false;
3211
+ }
3212
+ result[index] = { ...part };
3213
+ return true;
3214
+ }
3215
+ function resolveStructuredPartKey(part) {
3216
+ if (part.type === "agent-run") {
3217
+ return `agent-run:${part.runId}`;
3218
+ }
3219
+ if (part.type === "agent.activity") {
3220
+ return `agent-activity:${part.activityId}`;
3221
+ }
3222
+ if (part.type === "tool-call") {
3223
+ return `tool:${part.toolCallId}`;
3224
+ }
3225
+ return "";
3226
+ }
3227
+ function workspaceTerminalSource(message) {
3228
+ const input = message.payload;
3229
+ const source = input?.projectAgentInput?.source;
3230
+ if (message.role !== "user" || source?.kind !== "task" || !source.workspaceId) return;
3231
+ try {
3232
+ const event = JSON.parse(message.content)?.event;
3233
+ if (event?.type === "agent.terminal" && (event.state === "completed" || event.state === "stopped")) {
3234
+ return { workspaceId: source.workspaceId, state: event.state };
3235
+ }
3236
+ } catch {
3237
+ }
3238
+ }
3239
+ function mapAgentMessagesToTimeline(messages, options) {
3240
+ const prefix = options?.idPrefix ?? "agent";
3241
+ const result = [];
3242
+ messages.forEach((message, index) => {
3243
+ const terminal = message.payload;
3244
+ const ownTerminal = message.role === "system" && message.kind === "task" && terminal?.type === "agent.terminal";
3245
+ if (ownTerminal && (terminal.state === "completed" || terminal.state === "stopped")) return;
3246
+ if (message.role === "system" && isNoiseSystemMessage(message.content) && !hasPayloadAttachments(message.payload)) return;
3247
+ const workspaceTerminal = workspaceTerminalSource(message);
3248
+ if (workspaceTerminal?.state === "completed") return;
3249
+ const stoppedWorkspaceId = workspaceTerminal?.state === "stopped" ? workspaceTerminal.workspaceId : void 0;
3250
+ const role = message.role === "user" && !stoppedWorkspaceId ? "user" : "assistant";
3251
+ const payloadPart = stoppedWorkspaceId ? { type: "system.message", text: `${options?.workspaceLabels?.get(stoppedWorkspaceId) ?? "\u5DE5\u4F5C\u533A Agent"}\u5DF2\u505C\u6B62` } : normalizeContentPart(message.payload);
3252
+ const content = payloadPart ? [payloadPart] : message.kind === "thinking" ? [{ type: "reasoning", text: stripThinkingPrefix(message.content) }] : message.content === "" ? [] : [{
3253
+ type: "text",
3254
+ text: message.content
3255
+ }];
3256
+ if (!payloadPart) content.push(...normalizeAttachmentContentParts(message.payload));
3257
+ const dispatchState = message.payload?.dispatchState;
3258
+ const row = {
3259
+ id: options?.preserveMessageIds && message.messageId ? message.messageId : `${prefix}-${message.messageId ?? String(index)}`,
3260
+ role,
3261
+ content,
3262
+ status: message.status === "streaming" ? role === "user" ? dispatchState === "accepted" ? "awaiting_dispatch" : dispatchState === "dispatching" ? "dispatching" : "queued_for_agent" : "in_progress" : message.status === "error" ? "error" : "complete",
3263
+ createdAt: normalizeTimestamp(message.createdAt),
3264
+ ...role === "user" && message.actorSubject ? { actorSubject: message.actorSubject } : {}
3265
+ };
3266
+ if (options?.groupReasoning === false) result.push(row);
3267
+ else appendTimelineMessage(result, row);
3268
+ });
3269
+ return result;
3270
+ }
3271
+ function appendTimelineMessage(result, message) {
3272
+ const previous = result[result.length - 1];
3273
+ const previousReasoning = readOnlyReasoningPart(previous);
3274
+ const nextReasoning = readOnlyReasoningPart(message);
3275
+ if (previous && previousReasoning && nextReasoning) {
3276
+ previous.content = [{
3277
+ type: "reasoning",
3278
+ text: [previousReasoning.text, nextReasoning.text].filter(Boolean).join("\n\n")
3279
+ }];
3280
+ previous.status = message.status;
3281
+ return;
3282
+ }
3283
+ result.push(message);
3284
+ }
3285
+ function readOnlyReasoningPart(message) {
3286
+ if (message?.role !== "assistant" || message.content.length !== 1) return null;
3287
+ const [part] = message.content;
3288
+ return part?.type === "reasoning" ? part : null;
3289
+ }
3290
+ function normalizeContentParts(input) {
3291
+ const result = [];
3292
+ for (const item of input) {
3293
+ const part = normalizeContentPart(item);
3294
+ if (part) {
3295
+ result.push(part);
3296
+ }
3297
+ }
3298
+ return result;
3299
+ }
3300
+ function normalizeContentPart(input) {
3301
+ if (!input || typeof input !== "object") {
3302
+ return null;
3303
+ }
3304
+ const value = input;
3305
+ switch (value.type) {
3306
+ case "agent.question":
3307
+ return readAgentQuestion(value);
3308
+ case "text":
3309
+ return typeof value.text === "string" ? { type: "text", text: value.text, ...contentPartMeta(value) } : null;
3310
+ case "system.message":
3311
+ return typeof value.text === "string" ? { type: "system.message", text: value.text, ...contentPartMeta(value) } : null;
3312
+ case "reasoning":
3313
+ return typeof value.text === "string" ? { type: "reasoning", text: value.text, ...contentPartMeta(value) } : null;
3314
+ case "tool-call":
3315
+ return typeof value.toolCallId === "string" && typeof value.toolName === "string" ? {
3316
+ type: "tool-call",
3317
+ toolCallId: value.toolCallId,
3318
+ toolName: value.toolName,
3319
+ args: value.args,
3320
+ result: value.result,
3321
+ status: normalizeToolCallStatus(value.status),
3322
+ ...contentPartMeta(value)
3323
+ } : null;
3324
+ case "agent-run":
3325
+ return typeof value.runId === "string" && typeof value.agentId === "string" ? {
3326
+ type: "agent-run",
3327
+ runId: value.runId,
3328
+ parentRunId: normalizeNullableString(value.parentRunId),
3329
+ agentId: value.agentId,
3330
+ agentNickname: normalizeNullableString(value.agentNickname) ?? void 0,
3331
+ agentName: normalizeNullableString(value.agentName) ?? void 0,
3332
+ status: normalizeAgentRunStatus(value.status),
3333
+ model: normalizeNullableString(value.model) ?? void 0,
3334
+ summary: normalizeNullableString(value.summary) ?? void 0,
3335
+ startedAt: normalizeNullableString(value.startedAt) ?? void 0,
3336
+ completedAt: normalizeNullableString(value.completedAt) ?? void 0,
3337
+ recentToolName: normalizeNullableString(value.recentToolName) ?? void 0
3338
+ } : null;
3339
+ case "agent.activity":
3340
+ return normalizeAgentActivityContentPart(value);
3341
+ case "file":
3342
+ if (value.attachment !== void 0) {
3343
+ const attachment = readWorkspaceAttachment(value.attachment);
3344
+ return {
3345
+ type: "file",
3346
+ attachment,
3347
+ fileName: attachment.fileName,
3348
+ mime: attachment.mimeType,
3349
+ kind: attachment.type,
3350
+ size: attachment.size,
3351
+ ...contentPartMeta(value)
3352
+ };
3353
+ }
3354
+ return typeof value.fileName === "string" ? {
3355
+ type: "file",
3356
+ fileName: value.fileName,
3357
+ path: normalizeNullableString(value.path) ?? void 0,
3358
+ url: normalizeNullableString(value.url) ?? void 0,
3359
+ mime: normalizeNullableString(value.mime) ?? void 0,
3360
+ source: normalizeNullableString(value.source) ?? void 0,
3361
+ kind: value.kind === "image" ? "image" : value.kind === "file" ? "file" : void 0,
3362
+ size: normalizeFileSize(value.size),
3363
+ width: normalizeImageDimension(value.width),
3364
+ height: normalizeImageDimension(value.height),
3365
+ ...contentPartMeta(value)
3366
+ } : null;
3367
+ case "step":
3368
+ return value.status === "started" || value.status === "finished" ? { type: "step", status: value.status, label: normalizeNullableString(value.label) ?? void 0, ...contentPartMeta(value) } : null;
3369
+ case "snapshot":
3370
+ return { type: "snapshot", label: normalizeNullableString(value.label) ?? void 0, summary: normalizeNullableString(value.summary) ?? void 0, ...contentPartMeta(value) };
3371
+ case "patch":
3372
+ return {
3373
+ type: "patch",
3374
+ summary: normalizeNullableString(value.summary) ?? void 0,
3375
+ files: Array.isArray(value.files) ? value.files.map(normalizePatchContentFile).filter((item) => item !== null) : void 0,
3376
+ hash: normalizeNullableString(value.hash) ?? void 0,
3377
+ turnId: normalizeNullableString(value.turnId) ?? void 0,
3378
+ snapshotRef: normalizeNullableString(value.snapshotRef) ?? void 0,
3379
+ snapshotId: normalizeNullableString(value.snapshotId) ?? void 0,
3380
+ delivery: normalizePatchDelivery(value.delivery),
3381
+ versionLabel: normalizeNullableString(value.versionLabel) ?? void 0,
3382
+ createdAt: normalizeNullableString(value.createdAt) ?? void 0,
3383
+ ...contentPartMeta(value)
3384
+ };
3385
+ case "retry":
3386
+ return typeof value.attempt === "number" ? { type: "retry", attempt: value.attempt, error: normalizeNullableString(value.error) ?? void 0, ...contentPartMeta(value) } : null;
3387
+ case "compaction":
3388
+ return { type: "compaction", summary: normalizeNullableString(value.summary) ?? void 0, ...contentPartMeta(value) };
3389
+ case "todo":
3390
+ return Array.isArray(value.items) ? {
3391
+ type: "todo",
3392
+ items: value.items.map(normalizeTodoItem).filter((item) => Boolean(item)),
3393
+ ...contentPartMeta(value)
3394
+ } : null;
3395
+ case "command":
3396
+ return typeof value.command === "string" ? { type: "command", command: value.command, args: value.args, status: normalizeNullableString(value.status) ?? void 0, ...contentPartMeta(value) } : null;
3397
+ default:
3398
+ return null;
3399
+ }
3400
+ }
3401
+ function normalizeTodoItem(input) {
3402
+ if (!input || typeof input !== "object") {
3403
+ return null;
3404
+ }
3405
+ const value = input;
3406
+ const text2 = normalizeNonEmptyString(value.text);
3407
+ if (!text2) {
3408
+ return null;
3409
+ }
3410
+ const id3 = normalizeNullableString(value.id);
3411
+ const status = normalizeNullableString(value.status);
3412
+ return {
3413
+ ...id3 ? { id: id3 } : {},
3414
+ text: text2,
3415
+ ...status ? { status } : {}
3416
+ };
3417
+ }
3418
+ function normalizePatchContentFile(input) {
3419
+ if (typeof input === "string") {
3420
+ const path = input.trim();
3421
+ return path ? path : null;
3422
+ }
3423
+ if (!input || typeof input !== "object") {
3424
+ return null;
3425
+ }
3426
+ const value = input;
3427
+ const filePath = normalizeNullableString(value.path) ?? normalizeNullableString(value.file);
3428
+ if (!filePath) {
3429
+ return null;
3430
+ }
3431
+ return {
3432
+ path: filePath,
3433
+ status: normalizePatchFileStatus(value.status),
3434
+ diff: normalizeNullableString(value.diff) ?? void 0,
3435
+ binary: value.binary === true,
3436
+ additions: normalizePatchLineCount(value.additions),
3437
+ deletions: normalizePatchLineCount(value.deletions)
3438
+ };
3439
+ }
3440
+ function normalizeAgentActivityContentPart(value) {
3441
+ const activityId = normalizeNullableString(value.activityId) ?? "";
3442
+ const title = normalizeNullableString(value.title) ?? "";
3443
+ if (!activityId || !title) {
3444
+ return null;
3445
+ }
3446
+ return {
3447
+ type: "agent.activity",
3448
+ activityId,
3449
+ status: normalizeAgentActivityStatus(value.status),
3450
+ title,
3451
+ icon: normalizeAgentActivityIcon(value.icon),
3452
+ counts: value.counts && typeof value.counts === "object" ? Object.fromEntries(
3453
+ Object.entries(value.counts).filter(([key, count]) => ["read", "search", "command", "edit", "tool"].includes(key) && typeof count === "number" && Number.isSafeInteger(count) && count > 0)
3454
+ ) : void 0,
3455
+ startedAt: normalizeNullableString(value.startedAt) ?? void 0,
3456
+ completedAt: normalizeNullableString(value.completedAt) ?? void 0,
3457
+ ...contentPartMeta(value)
3458
+ };
3459
+ }
3460
+ function normalizePatchLineCount(value) {
3461
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
3462
+ return void 0;
3463
+ }
3464
+ return Math.trunc(value);
3465
+ }
3466
+ function normalizeAttachmentContentParts(payload) {
3467
+ if (!payload || typeof payload !== "object") {
3468
+ return [];
3469
+ }
3470
+ const value = payload;
3471
+ if (!Array.isArray(value.attachments)) {
3472
+ return [];
3473
+ }
3474
+ const result = [];
3475
+ for (const item of value.attachments) {
3476
+ if (!item || typeof item !== "object") {
3477
+ continue;
3478
+ }
3479
+ const attachment = item;
3480
+ if (attachment.attachmentId !== void 0) {
3481
+ const registered = readWorkspaceAttachment(attachment);
3482
+ result.push({
3483
+ type: "file",
3484
+ fileName: registered.fileName,
3485
+ mime: registered.mimeType,
3486
+ kind: registered.type,
3487
+ size: registered.size,
3488
+ attachment: registered
3489
+ });
3490
+ continue;
3491
+ }
3492
+ const fileName = normalizeNonEmptyString(attachment.fileName);
3493
+ if (!fileName) {
3494
+ continue;
3495
+ }
3496
+ const type = normalizeNullableString(attachment.type);
3497
+ result.push({
3498
+ type: "file",
3499
+ fileName,
3500
+ path: normalizeNullableString(attachment.filePath) ?? normalizeNullableString(attachment.path) ?? void 0,
3501
+ mime: normalizeNullableString(attachment.mime) ?? void 0,
3502
+ source: normalizeNullableString(attachment.source) ?? void 0,
3503
+ kind: type === "image" ? "image" : "file",
3504
+ size: normalizeFileSize(attachment.size)
3505
+ });
3506
+ }
3507
+ return result;
3508
+ }
3509
+ function hasPayloadAttachments(payload) {
3510
+ return Boolean(
3511
+ payload && typeof payload === "object" && Array.isArray(payload.attachments) && payload.attachments.length > 0
3512
+ );
3513
+ }
3514
+ function normalizeFileSize(value) {
3515
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
3516
+ return void 0;
3517
+ }
3518
+ return Math.trunc(value);
3519
+ }
3520
+ function normalizeImageDimension(value) {
3521
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
3522
+ return void 0;
3523
+ }
3524
+ return Math.trunc(value);
3525
+ }
3526
+ function normalizePatchFileStatus(value) {
3527
+ if (value === "added" || value === "modified" || value === "removed" || value === "renamed") {
3528
+ return value;
3529
+ }
3530
+ return void 0;
3531
+ }
3532
+ function contentPartMeta(value) {
3533
+ return {
3534
+ runId: normalizeNullableString(value.runId) ?? void 0,
3535
+ agentId: normalizeNullableString(value.agentId) ?? void 0,
3536
+ parentRunId: normalizeNullableString(value.parentRunId) ?? void 0
3537
+ };
3538
+ }
3539
+ function normalizeAgentRunStatus(value) {
3540
+ if (value === "queued" || value === "running" || value === "waiting" || value === "done" || value === "failed" || value === "cancelled") {
3541
+ return value;
3542
+ }
3543
+ return "running";
3544
+ }
3545
+ function normalizeAgentActivityStatus(value) {
3546
+ if (value === "running" || value === "completed" || value === "error") {
3547
+ return value;
3548
+ }
3549
+ return "running";
3550
+ }
3551
+ function normalizeAgentActivityIcon(value) {
3552
+ if (value === "read" || value === "search" || value === "command" || value === "edit" || value === "tool" || value === "mixed") {
3553
+ return value;
3554
+ }
3555
+ return "mixed";
3556
+ }
3557
+ function normalizeToolCallStatus(value) {
3558
+ if (value === "pending" || value === "running" || value === "completed" || value === "error") {
3559
+ return value;
3560
+ }
3561
+ return void 0;
3562
+ }
3563
+ function normalizeNonEmptyString(value) {
3564
+ if (typeof value !== "string") {
3565
+ return "";
3566
+ }
3567
+ return value.trim();
3568
+ }
3569
+ function normalizeNullableString(value) {
3570
+ if (typeof value !== "string") {
3571
+ return null;
3572
+ }
3573
+ return value;
3574
+ }
3575
+ function normalizeTimestamp(value) {
3576
+ const timestamp = typeof value === "number" ? value : Date.parse(value);
3577
+ if (Number.isNaN(timestamp)) {
3578
+ return (/* @__PURE__ */ new Date()).toISOString();
3579
+ }
3580
+ return new Date(timestamp).toISOString();
3581
+ }
3582
+ function stripThinkingPrefix(content) {
3583
+ const prefix = "[assistant.thinking]";
3584
+ const normalized = content.trim();
3585
+ if (!normalized.startsWith(prefix)) {
3586
+ return normalized;
3587
+ }
3588
+ return normalized.slice(prefix.length).trim();
3589
+ }
3590
+ function isNoiseSystemMessage(content) {
3591
+ const original = content.trim();
3592
+ const normalized = original.toLowerCase();
3593
+ if (!normalized) {
3594
+ return true;
3595
+ }
3596
+ return normalized.startsWith("agent runtime ready for ") || normalized.startsWith("agent process started") || normalized.startsWith("agent process exited") || normalized.startsWith("agent runtime stopped") || normalized.startsWith("[agent.system.init]") || isTransientAgentResultErrorMessage(original);
3597
+ }
3598
+ function isTransientAgentResultErrorMessage(content) {
3599
+ const normalized = content.trim();
3600
+ if (!normalized.startsWith("[agent.result.error]")) {
3601
+ return false;
3602
+ }
3603
+ const detail = normalized.replace(/^\[agent\.result\.error\]\s*/u, "").trim();
3604
+ return /^Reconnecting\.\.\. \d+\/\d+$/u.test(detail);
3605
+ }
3606
+ function normalizePatchDelivery(value) {
3607
+ if (value === void 0) return void 0;
3608
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("\u7248\u672C\u5361\u7247\u4EA4\u4ED8\u6807\u8BB0\u65E0\u6548\u3002");
3609
+ const delivery = value;
3610
+ if (typeof delivery.deliveryId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(delivery.deliveryId) || typeof delivery.taskKey !== "string" || !/^T[0-9]{3,}$/u.test(delivery.taskKey) || typeof delivery.revision !== "string" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(delivery.revision)) throw new Error("\u7248\u672C\u5361\u7247\u4EA4\u4ED8\u6807\u8BB0\u65E0\u6548\u3002");
3611
+ return { deliveryId: delivery.deliveryId, taskKey: delivery.taskKey, revision: delivery.revision };
3612
+ }
3613
+ function isOwnAgentMessage(message, currentSubject) {
3614
+ return message.role === "user" && !!currentSubject && message.actorSubject === currentSubject;
3615
+ }
3616
+ function agentMessageMember(message, members) {
3617
+ return message.actorSubject ? members.find((member) => member.subject === message.actorSubject) : void 0;
3618
+ }
3619
+ function agentMemberInitial(name) {
3620
+ return Array.from(name.trim())[0]?.toLocaleUpperCase() ?? "?";
3621
+ }
3622
+
3623
+ // ../workspace-chat-stream.ts
3624
+ function applyWorkspaceChatStream(snapshot, stream, delta) {
3625
+ const parsed = normalizeWorkspaceAgentServerMessage({ ...delta, type: delta.type === "delta" ? "message.delta" : "message.commit" });
3626
+ if (delta.sessionId !== snapshot.sessionId || !["delta", "commit"].includes(delta.type) || !delta.id || !Number.isSafeInteger(delta.seq) || delta.seq < 1 || !parsed) throw new Error("developer.agent_event_invalid");
3627
+ const stored = snapshot.messages.find((message) => message.messageId === parsed.id);
3628
+ const dispatch = stored?.payload?.dispatchState;
3629
+ if (stored && (stored.status !== "streaming" || stored.role === "user" && (dispatch === "accepted" || dispatch === "dispatching"))) return [...stream];
3630
+ const current = stream.some((message) => message.id === parsed.id) ? stream : [...stream, ...mapAgentMessagesToTimeline(snapshot.messages.filter((message) => message.messageId === parsed.id), { preserveMessageIds: true, groupReasoning: false })];
3631
+ return parsed.type === "message.delta" ? applyDelta(current, parsed) : applyCommit(current, parsed);
3632
+ }
3633
+ function restoreWorkspaceChatStream(snapshot) {
3634
+ let stream = mapAgentMessagesToTimeline(snapshot.messages.filter((message) => message.status === "streaming"), { preserveMessageIds: true, groupReasoning: false });
3635
+ for (const delta of snapshot.stream) stream = applyWorkspaceChatStream(snapshot, stream, delta);
3636
+ return stream;
3637
+ }
3638
+ function workspaceChatTimeline(snapshot, stream = restoreWorkspaceChatStream(snapshot), agentLabel) {
3639
+ const persisted = mapAgentMessagesToTimeline(snapshot.messages, { agentLabel, idPrefix: snapshot.sessionId, preserveMessageIds: true, groupReasoning: false });
3640
+ const rows = new Map(persisted.map((message) => [message.id, message]));
3641
+ const storedIds = new Set(snapshot.messages.map((message) => message.messageId));
3642
+ for (const message of stream) {
3643
+ if (storedIds.has(message.id) && !rows.has(message.id)) continue;
3644
+ const stored = rows.get(message.id);
3645
+ if (!stored || stored.status !== "complete" && stored.status !== "error") rows.set(message.id, message);
3646
+ }
3647
+ return [...rows.values()];
3648
+ }
3649
+
3650
+ // ../workspace-agent-view.ts
3651
+ function readDeveloperAgentView(workspaceId, input) {
3652
+ const value = record2(input), history = record2(value.history);
3653
+ if (value.workspaceId !== workspaceId || typeof value.sessionId !== "string" || !value.sessionId || !["idle", "running"].includes(String(value.status)) || typeof value.updatedAt !== "string" || !Array.isArray(value.messages) || !Array.isArray(value.stream) || typeof history.hasMore !== "boolean" || (history.hasMore ? !Number.isSafeInteger(history.nextBefore) || history.nextBefore < 1 : history.nextBefore !== null)) invalid2();
3654
+ for (const item of value.messages) {
3655
+ const message = record2(item);
3656
+ if (!["user", "assistant", "system"].includes(String(message.role)) || typeof message.content !== "string" || typeof message.createdAt !== "string" || message.messageId !== void 0 && typeof message.messageId !== "string" || message.actorSubject !== void 0 && (message.role !== "user" || typeof message.actorSubject !== "string" || !message.actorSubject || message.actorSubject.length > 512 || /\s/.test(message.actorSubject)) || message.status !== void 0 && !["streaming", "final", "error"].includes(String(message.status))) invalid2();
3657
+ }
3658
+ const snapshot = input;
3659
+ const stream = restoreWorkspaceChatStream(snapshot);
3660
+ return { snapshot, history, stream, messages: workspaceChatTimeline(snapshot, stream) };
3661
+ }
3662
+ function applyDeveloperAgentEvent(view, input) {
3663
+ const delta = record2(input);
3664
+ const stream = applyWorkspaceChatStream(view.snapshot, view.stream, delta);
3665
+ const changed = stream.find((message) => message.id === delta.id);
3666
+ if (!changed) return { ...view, stream };
3667
+ const found = view.messages.some((message) => message.id === changed.id);
3668
+ return { ...view, stream, messages: found ? view.messages.map((message) => message.id === changed.id ? changed : message) : [...view.messages, changed] };
3669
+ }
3670
+ function refreshDeveloperAgentView(next, previous) {
3671
+ if (!previous || previous.snapshot.workspaceId !== next.snapshot.workspaceId || previous.snapshot.sessionId !== next.snapshot.sessionId) return next;
3672
+ return { ...next, history: previous.history, messages: mergeAgentHistoryWindow(previous.messages, next.messages) };
3673
+ }
3674
+ function mergeDeveloperAgentHistory(view, value, beforeSeq, beforeMessageId) {
3675
+ const page = record2(value);
3676
+ if (page.workspaceId !== view.snapshot.workspaceId || page.sessionId !== view.snapshot.sessionId || view.history.nextBefore !== beforeSeq || view.history.beforeMessageId !== beforeMessageId || !view.history.hasMore || !Array.isArray(page.messages) || page.messages.length > 100 || page.hasMore === true && (!Number.isSafeInteger(page.nextBefore) || page.nextBefore >= beforeSeq)) invalid2();
3677
+ const decoded = readDeveloperAgentView(view.snapshot.workspaceId, { ...view.snapshot, messages: page.messages, stream: [], history: { hasMore: page.hasMore, nextBefore: page.nextBefore } });
3678
+ if (decoded.snapshot.messages.some((message) => !message.messageId)) invalid2();
3679
+ return { ...view, history: decoded.history, messages: mergeAgentHistoryWindow(decoded.messages, view.messages) };
3680
+ }
3681
+ function mergeAgentHistoryWindow(older, latest) {
3682
+ const ids = new Set(latest.map((message) => message.id));
3683
+ return [...older.filter((message) => !ids.has(message.id)), ...latest];
3684
+ }
3685
+ function invalid2() {
3686
+ throw new Error("developer.agent_snapshot_invalid");
3687
+ }
3688
+ function record2(value) {
3689
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid2();
3690
+ return value;
3691
+ }
3692
+
3693
+ // ../workspace-agent-input.ts
3694
+ import { readWorkspaceQuestionReply as readWorkspaceQuestionReply2 } from "@kuafucloud/product-runtime-protocol";
3695
+ var DeveloperAgentInput = class _DeveloperAgentInput {
3696
+ constructor(newId) {
3697
+ this.newId = newId;
3698
+ }
3699
+ state = { text: "", phase: "draft", attempt: null, error: null };
3700
+ listeners = /* @__PURE__ */ new Set();
3701
+ lastAccepted = false;
3702
+ outbox = /* @__PURE__ */ new Map();
3703
+ get accepted() {
3704
+ return this.lastAccepted;
3705
+ }
3706
+ questions = /* @__PURE__ */ new Map();
3707
+ forQuestion(key) {
3708
+ let owner = this.questions.get(key);
3709
+ if (!owner) {
3710
+ owner = new _DeveloperAgentInput(this.newId);
3711
+ this.questions.set(key, owner);
3712
+ }
3713
+ return owner;
3714
+ }
3715
+ getSnapshot = () => this.state;
3716
+ subscribe = (listener) => {
3717
+ this.listeners.add(listener);
3718
+ return () => {
3719
+ this.listeners.delete(listener);
3720
+ };
3721
+ };
3722
+ /** 本地发送展示与源端复用 clientMessageId;只投影当前会话,不写入历史缓存。 */
3723
+ projectMessages(messages, scope, actorSubject) {
3724
+ const present = new Set(messages.filter((message) => message.role === "user").map((message) => message.id));
3725
+ const pending = [];
3726
+ for (const { attempt, createdAt } of this.outbox.values()) {
3727
+ if (attempt.workspaceId !== scope.workspaceId || attempt.sessionId !== scope.sessionId || present.has(attempt.clientMessageId)) continue;
3728
+ const current = this.state.attempt?.clientMessageId === attempt.clientMessageId;
3729
+ pending.push({
3730
+ id: attempt.clientMessageId,
3731
+ role: "user",
3732
+ ...actorSubject ? { actorSubject } : {},
3733
+ createdAt,
3734
+ content: [{ type: "text", text: attempt.text }],
3735
+ status: current ? this.state.phase === "sending" ? "in_progress" : "error" : "complete"
3736
+ });
3737
+ }
3738
+ return pending.length ? [...messages, ...pending] : messages;
3739
+ }
3740
+ acknowledge(messages, scope) {
3741
+ let changed = false, settled;
3742
+ for (const message of messages) {
3743
+ const entry = this.outbox.get(message.id);
3744
+ if (message.role === "user" && entry?.attempt.workspaceId === scope.workspaceId && entry.attempt.sessionId === scope.sessionId) {
3745
+ if (message.status === "awaiting_dispatch" || message.status === "dispatching") continue;
3746
+ this.outbox.delete(message.id);
3747
+ changed = true;
3748
+ if (this.state.attempt?.clientMessageId === message.id) settled = message.status === "error" ? "rejected" : "accepted";
3749
+ }
3750
+ }
3751
+ if (settled) {
3752
+ this.lastAccepted = settled === "accepted";
3753
+ this.update({ text: "", phase: "draft", attempt: null, error: this.lastAccepted ? null : "developer.input_rejected" });
3754
+ } else if (changed) this.update({ ...this.state });
3755
+ }
3756
+ edit(text2) {
3757
+ if (this.state.attempt) return;
3758
+ this.update({ ...this.state, text: text2, error: null });
3759
+ }
3760
+ async submit(scope, request, reply) {
3761
+ if (this.state.phase === "sending" || !this.state.attempt && !this.state.text.trim()) return;
3762
+ const previous = this.state.attempt;
3763
+ if (previous && (previous.workspaceId !== scope.workspaceId || previous.sessionId !== scope.sessionId || reply !== void 0 && JSON.stringify(previous.reply) !== JSON.stringify(reply))) {
3764
+ this.update({ ...this.state, error: "developer.input_session_changed" });
3765
+ return;
3766
+ }
3767
+ let attempt;
3768
+ try {
3769
+ attempt = previous ?? { ...scope, clientMessageId: this.newId(), text: this.state.text.trim(), ...reply ? { reply: readWorkspaceQuestionReply2(reply) } : {} };
3770
+ if (!attempt.clientMessageId) throw new Error();
3771
+ } catch {
3772
+ this.update({ ...this.state, error: "developer.identity_unavailable" });
3773
+ return;
3774
+ }
3775
+ if (!this.outbox.has(attempt.clientMessageId)) this.outbox.set(attempt.clientMessageId, { attempt, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
3776
+ this.update({ ...this.state, text: "", phase: "sending", attempt, error: null });
3777
+ try {
3778
+ let receipt = previous ? await request("receipt", { sessionId: attempt.sessionId, clientMessageId: attempt.clientMessageId }) : null;
3779
+ if (this.state.attempt !== attempt) return;
3780
+ if (receipt === null) receipt = await request("send", { sessionId: attempt.sessionId, clientMessageId: attempt.clientMessageId, text: attempt.text, ...attempt.reply ? { reply: attempt.reply } : {} });
3781
+ if (this.state.attempt !== attempt) return;
3782
+ if (readDeveloperAgentReceipt(receipt, attempt).state === "rejected") {
3783
+ this.lastAccepted = false;
3784
+ this.outbox.delete(attempt.clientMessageId);
3785
+ this.update({ text: "", phase: "draft", attempt: null, error: "developer.input_rejected" });
3786
+ return;
3787
+ }
3788
+ this.lastAccepted = true;
3789
+ this.update({ text: "", phase: "draft", attempt: null, error: null });
3790
+ } catch (error) {
3791
+ if (this.state.attempt !== attempt) return;
3792
+ if (!previous && error instanceof DeveloperRealtimeClientError && ["developer.input_forbidden", "developer.membership_unavailable", "developer.payload_invalid", "developer.request_limit", "developer.host_offline", "developer.request_cancelled"].includes(error.code)) {
3793
+ this.outbox.delete(attempt.clientMessageId);
3794
+ this.update({ ...this.state, text: attempt.text, phase: "draft", attempt: null, error: error.code });
3795
+ return;
3796
+ }
3797
+ this.update({ ...this.state, phase: "unknown", error: "developer.input_result_unknown" });
3798
+ }
3799
+ }
3800
+ update(state) {
3801
+ this.state = state;
3802
+ for (const listener of this.listeners) listener();
3803
+ }
3804
+ };
3805
+ function readDeveloperAgentReceipt(value, expected) {
3806
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("developer.receipt_invalid");
3807
+ const receipt = value;
3808
+ if (receipt.workspaceId !== expected.workspaceId || receipt.sessionId !== expected.sessionId || receipt.clientMessageId !== expected.clientMessageId || !["accepted", "dispatching", "dispatched", "rejected"].includes(receipt.state)) throw new Error("developer.receipt_invalid");
3809
+ return receipt;
3810
+ }
3811
+
3812
+ // ../workspace-cache.ts
3813
+ var DEVELOPER_AGENT_CACHE_MESSAGES = 1e3;
3814
+ var DeveloperWorkspaceCache = class {
3815
+ constructor(store) {
3816
+ this.store = store;
3817
+ }
3818
+ bindings = /* @__PURE__ */ new Map();
3819
+ listeners = /* @__PURE__ */ new Set();
3820
+ pending = /* @__PURE__ */ new Map();
3821
+ hydrating = /* @__PURE__ */ new Map();
3822
+ loaded = /* @__PURE__ */ new Set();
3823
+ timer;
3824
+ writes = Promise.resolve();
3825
+ revision = 0;
3826
+ generation = 0;
3827
+ storageError = null;
3828
+ missingRevision = 0;
3829
+ missingLoad;
3830
+ invalidated = /* @__PURE__ */ new Set();
3831
+ confirmedPresent = /* @__PURE__ */ new Set();
3832
+ subscribe = (listener) => {
3833
+ this.listeners.add(listener);
3834
+ return () => this.listeners.delete(listener);
3835
+ };
3836
+ getRevision = () => this.revision;
3837
+ getMissingRevision = () => this.missingRevision;
3838
+ isMissing(conversationId, membershipEpoch) {
3839
+ const scope = this.resolve(conversationId, membershipEpoch);
3840
+ return !!scope && this.entries.get(scopeKey(scope))?.workspaceMissing === true;
3841
+ }
3842
+ /** 账号分区中的已确认事实;普通断线不调用此入口,也不创建Host删除记录。 */
3843
+ restoreMissing() {
3844
+ if (!this.store) return Promise.resolve();
3845
+ const generation = this.generation;
3846
+ return this.missingLoad ??= this.store.readMissing().then((scopes) => {
3847
+ if (this.generation !== generation) return;
3848
+ for (const scope of scopes) {
3849
+ if (this.invalidated.has(scope.conversationId)) continue;
3850
+ if (this.confirmedPresent.has(scopeKey(scope))) continue;
3851
+ const current = this.bindings.get(scope.conversationId);
3852
+ if (current && scopeKey(current) !== scopeKey(scope)) continue;
3853
+ this.bindings.set(scope.conversationId, scope);
3854
+ this.entry(scope).workspaceMissing = true;
3855
+ this.entry(scope).products = { revision: 0, products: [] };
3856
+ }
3857
+ this.missingRevision++;
3858
+ this.notify();
3859
+ }).catch((error) => {
3860
+ if (this.generation === generation) {
3861
+ this.missingLoad = void 0;
3862
+ this.storageError = "developer.cache_read_failed";
3863
+ this.notify();
3864
+ }
3865
+ throw error;
3866
+ });
3867
+ }
3868
+ getStorageError = () => this.storageError;
3869
+ hasHydrated(conversationId, membershipEpoch) {
3870
+ return !this.store || this.loaded.has(JSON.stringify([conversationId, membershipEpoch]));
3871
+ }
3872
+ notify() {
3873
+ this.revision++;
3874
+ for (const listener of this.listeners) listener();
3875
+ }
3876
+ /** 读取本地绑定与历史,不依赖远端 resolve;迟到读取不能覆盖新连接已写入的数据。 */
3877
+ hydrate(conversationId, membershipEpoch) {
3878
+ const key = JSON.stringify([conversationId, membershipEpoch]);
3879
+ if (!this.store || this.loaded.has(key)) return Promise.resolve();
3880
+ const existing = this.hydrating.get(key);
3881
+ if (existing) return existing;
3882
+ const generation = this.generation;
3883
+ const load = this.store.read(conversationId).then((record3) => {
3884
+ if (this.generation !== generation) return;
3885
+ this.loaded.add(key);
3886
+ const binding = this.bindings.get(conversationId);
3887
+ if (record3 && record3.scope.membershipEpoch === membershipEpoch && (!binding || scopeKey(binding) === scopeKey(record3.scope))) {
3888
+ const current = this.entries.get(scopeKey(record3.scope));
3889
+ const workspaceMissing = current?.workspaceMissing ?? (this.confirmedPresent.has(scopeKey(record3.scope)) ? void 0 : record3.workspaceMissing);
3890
+ this.bindings.set(conversationId, record3.scope);
3891
+ this.entries.set(scopeKey(record3.scope), {
3892
+ agent: current?.agent ?? record3.agent,
3893
+ products: current?.products ?? record3.products,
3894
+ history: current?.history ?? record3.history,
3895
+ workspaceMissing
3896
+ });
3897
+ if (!current?.workspaceMissing && workspaceMissing) this.missingRevision++;
3898
+ const pending = this.pending.get(conversationId);
3899
+ if (pending && scopeKey(pending.scope) === scopeKey(record3.scope)) {
3900
+ this.pending.set(conversationId, { scope: record3.scope, ...this.entry(record3.scope) });
3901
+ }
3902
+ this.notify();
3903
+ }
3904
+ }).catch((error) => {
3905
+ if (this.generation === generation) {
3906
+ this.storageError = "developer.cache_read_failed";
3907
+ this.notify();
3908
+ }
3909
+ throw error;
3910
+ }).finally(() => {
3911
+ if (this.hydrating.get(key) === load) this.hydrating.delete(key);
3912
+ });
3913
+ this.hydrating.set(key, load);
3914
+ return load;
3915
+ }
3916
+ /** 合并短时片段写入;关闭时 flush,持久化失败保持可观察错误,不伪称保存成功。 */
3917
+ flush() {
3918
+ clearTimeout(this.timer);
3919
+ this.timer = void 0;
3920
+ const pending = [...this.pending];
3921
+ if (!this.store || !pending.length) return this.writes;
3922
+ const store = this.store;
3923
+ const generation = this.generation;
3924
+ const write = this.writes.catch(() => {
3925
+ }).then(async () => {
3926
+ for (const [id3, candidate] of pending) {
3927
+ if (this.generation !== generation || this.pending.get(id3) !== candidate) continue;
3928
+ if (candidate) await this.hydrate(id3, candidate.scope.membershipEpoch);
3929
+ if (this.generation !== generation) return;
3930
+ const record3 = this.pending.get(id3);
3931
+ if (record3 === void 0 || record3 && candidate && scopeKey(record3.scope) !== scopeKey(candidate.scope)) continue;
3932
+ if (record3) await store.write(record3);
3933
+ else await store.remove(id3);
3934
+ if (this.pending.get(id3) === record3) this.pending.delete(id3);
3935
+ }
3936
+ if (this.storageError) {
3937
+ this.storageError = null;
3938
+ this.notify();
3939
+ }
3940
+ }).catch((error) => {
3941
+ this.storageError = "developer.cache_write_failed";
3942
+ this.notify();
3943
+ throw error;
3944
+ });
3945
+ this.writes = write;
3946
+ return write;
3947
+ }
3948
+ async close() {
3949
+ try {
3950
+ await this.flush();
3951
+ } finally {
3952
+ await this.store?.close();
3953
+ this.clear();
3954
+ }
3955
+ }
3956
+ persist(scope) {
3957
+ if (!this.store) return;
3958
+ this.pending.set(scope.conversationId, { scope, ...this.entry(scope) });
3959
+ if (!this.timer) this.timer = setTimeout(() => {
3960
+ void this.flush().catch(() => {
3961
+ });
3962
+ }, 400);
3963
+ }
3964
+ /** 只接受resolve返回且与IM成员代际一致的绑定。 */
3965
+ bind(scope) {
3966
+ scopeKey(scope);
3967
+ const previous = this.bindings.get(scope.conversationId);
3968
+ if (previous && scopeKey(previous) !== scopeKey(scope)) this.invalidate(previous);
3969
+ this.bindings.set(scope.conversationId, scope);
3970
+ this.invalidated.delete(scope.conversationId);
3971
+ }
3972
+ resolve(conversationId, membershipEpoch) {
3973
+ const scope = this.bindings.get(conversationId);
3974
+ return scope?.membershipEpoch === membershipEpoch ? scope : null;
3975
+ }
3976
+ entries = /* @__PURE__ */ new Map();
3977
+ readAgent(scope) {
3978
+ return this.entries.get(scopeKey(scope))?.agent ?? null;
3979
+ }
3980
+ readProducts(scope) {
3981
+ return this.entries.get(scopeKey(scope))?.products ?? null;
3982
+ }
3983
+ /** 仅在新首帧证实同会话且有重叠时保留更早缓存;分页由Host重新解析消息身份。 */
3984
+ restoreAgent(scope, next) {
3985
+ const previous = this.readAgent(scope);
3986
+ if (!previous || previous.snapshot.sessionId !== next.snapshot.sessionId || !next.history.hasMore) return next;
3987
+ const currentIds = new Set(next.messages.map((message) => message.id));
3988
+ const overlap = previous.messages.findIndex((message) => currentIds.has(message.id));
3989
+ if (overlap <= 0) return next;
3990
+ const messages = [...previous.messages.slice(0, overlap), ...next.messages];
3991
+ return { ...next, messages, history: { ...next.history, beforeMessageId: messages[0].id } };
3992
+ }
3993
+ saveAgent(scope, view) {
3994
+ if (scope.workspaceId !== view.snapshot.workspaceId) throw new Error("developer.cache_scope_invalid");
3995
+ this.confirmPresent(scope);
3996
+ const { workspaceId, sessionId, status, updatedAt } = view.snapshot;
3997
+ this.entry(scope).agent = {
3998
+ snapshot: { workspaceId, sessionId, status, updatedAt },
3999
+ messages: view.messages.slice(-DEVELOPER_AGENT_CACHE_MESSAGES)
4000
+ };
4001
+ this.entry(scope).history = {
4002
+ hasMore: view.history.hasMore || view.messages.length > DEVELOPER_AGENT_CACHE_MESSAGES,
4003
+ ...this.entry(scope).agent.messages[0] ? { beforeMessageId: this.entry(scope).agent.messages[0].id } : {}
4004
+ };
4005
+ this.persist(scope);
4006
+ this.notify();
4007
+ }
4008
+ saveProducts(scope, products) {
4009
+ this.confirmPresent(scope);
4010
+ this.entry(scope).products = products;
4011
+ this.persist(scope);
4012
+ this.notify();
4013
+ }
4014
+ /** 明确不存在只清空产品入口,保留群对应的本地Agent历史。 */
4015
+ removeProducts(scope) {
4016
+ if (this.entries.get(scopeKey(scope))?.products?.products.length === 0) return;
4017
+ this.saveProducts(scope, { revision: 0, products: [] });
4018
+ }
4019
+ markMissing(scope) {
4020
+ if (this.entry(scope).workspaceMissing) return;
4021
+ this.removeProducts(scope);
4022
+ this.confirmedPresent.delete(scopeKey(scope));
4023
+ this.entry(scope).workspaceMissing = true;
4024
+ this.missingRevision++;
4025
+ this.persist(scope);
4026
+ this.notify();
4027
+ }
4028
+ confirmPresent(scope) {
4029
+ this.confirmedPresent.add(scopeKey(scope));
4030
+ if (this.entry(scope).workspaceMissing) {
4031
+ delete this.entry(scope).workspaceMissing;
4032
+ this.missingRevision++;
4033
+ }
4034
+ }
4035
+ readHistory(scope) {
4036
+ return this.entries.get(scopeKey(scope))?.history ?? null;
4037
+ }
4038
+ invalidate(scope) {
4039
+ this.confirmedPresent.delete(scopeKey(scope));
4040
+ this.invalidated.add(scope.conversationId);
4041
+ if (this.entries.get(scopeKey(scope))?.workspaceMissing) this.missingRevision++;
4042
+ this.entries.delete(scopeKey(scope));
4043
+ const binding = this.bindings.get(scope.conversationId);
4044
+ if (binding && scopeKey(binding) === scopeKey(scope)) this.bindings.delete(scope.conversationId);
4045
+ this.loaded.delete(JSON.stringify([scope.conversationId, scope.membershipEpoch]));
4046
+ if (this.store) {
4047
+ this.pending.set(scope.conversationId, null);
4048
+ void this.flush().catch(() => {
4049
+ });
4050
+ }
4051
+ this.notify();
4052
+ }
4053
+ /** 只释放内存;清理磁盘必须显式 invalidate,页面卸载不删除持久历史。 */
4054
+ clear() {
4055
+ this.missingLoad = void 0;
4056
+ this.missingRevision++;
4057
+ this.generation++;
4058
+ clearTimeout(this.timer);
4059
+ this.timer = void 0;
4060
+ this.pending.clear();
4061
+ this.hydrating.clear();
4062
+ this.entries.clear();
4063
+ this.bindings.clear();
4064
+ this.loaded.clear();
4065
+ this.notify();
4066
+ this.invalidated.clear();
4067
+ this.confirmedPresent.clear();
4068
+ }
4069
+ entry(scope) {
4070
+ const key = scopeKey(scope);
4071
+ let entry = this.entries.get(key);
4072
+ if (!entry) {
4073
+ entry = {};
4074
+ this.entries.set(key, entry);
4075
+ }
4076
+ return entry;
4077
+ }
4078
+ };
4079
+ function scopeKey(scope) {
4080
+ const values = [
4081
+ scope.conversationId,
4082
+ scope.membershipEpoch,
4083
+ scope.hostDeviceId,
4084
+ scope.workspaceId
4085
+ ];
4086
+ if (values.some((value) => typeof value !== "string" || !value.trim())) throw new Error("developer.cache_scope_invalid");
4087
+ return JSON.stringify(values);
4088
+ }
4089
+
4090
+ // ../workspace-cache-store.ts
4091
+ var SqliteDeveloperCacheStore = class {
4092
+ constructor(transaction, release = async () => {
4093
+ }) {
4094
+ this.transaction = transaction;
4095
+ this.release = release;
4096
+ }
4097
+ initialized;
4098
+ initialize() {
4099
+ return this.initialized ??= this.transaction([
4100
+ { sql: "CREATE TABLE IF NOT EXISTS developer_cache_meta (conversation_id TEXT PRIMARY KEY, data TEXT NOT NULL)" },
4101
+ { sql: "CREATE TABLE IF NOT EXISTS developer_cache_message (conversation_id TEXT NOT NULL, message_id TEXT NOT NULL, position INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY(conversation_id, message_id))" },
4102
+ { sql: "CREATE INDEX IF NOT EXISTS developer_cache_message_order ON developer_cache_message(conversation_id, position)" }
4103
+ ]).then(() => void 0).catch((error) => {
4104
+ this.initialized = void 0;
4105
+ throw error;
4106
+ });
4107
+ }
4108
+ async read(conversationId) {
4109
+ await this.initialize();
4110
+ const rows = await this.transaction([
4111
+ { sql: "SELECT data FROM developer_cache_meta WHERE conversation_id = ?", parameters: [conversationId] },
4112
+ { sql: "SELECT data FROM developer_cache_message WHERE conversation_id = ? ORDER BY position DESC LIMIT ?", parameters: [conversationId, DEVELOPER_AGENT_CACHE_MESSAGES] }
4113
+ ]);
4114
+ const metadata2 = rows[0]?.rows[0]?.data;
4115
+ if (metadata2 === void 0) return null;
4116
+ if (typeof metadata2 !== "string") throw new Error("developer.cache_corrupt");
4117
+ const value = JSON.parse(metadata2);
4118
+ if (value.agent) value.agent.messages = [...rows[1].rows].reverse().map((row) => {
4119
+ if (typeof row.data !== "string") throw new Error("developer.cache_corrupt");
4120
+ return JSON.parse(row.data);
4121
+ });
4122
+ assertDeveloperCacheRecord(value);
4123
+ if (value.scope.conversationId !== conversationId) throw new Error("developer.cache_corrupt");
4124
+ return value;
4125
+ }
4126
+ /** 会话列表只读轻量标记,不为显示标题加载每个群的千条历史。 */
4127
+ async readMissing() {
4128
+ await this.initialize();
4129
+ const result = await this.transaction([{ sql: "SELECT json_extract(data, '$.scope') AS scope FROM developer_cache_meta WHERE json_extract(data, '$.workspaceMissing') = 1" }]);
4130
+ return result[0].rows.map((row) => {
4131
+ if (typeof row.scope !== "string") throw new Error("developer.cache_corrupt");
4132
+ const value = { scope: JSON.parse(row.scope), workspaceMissing: true };
4133
+ assertDeveloperCacheRecord(value);
4134
+ return value.scope;
4135
+ });
4136
+ }
4137
+ async write(record3) {
4138
+ assertDeveloperCacheRecord(record3);
4139
+ const messages = JSON.stringify((record3.agent?.messages ?? []).map((message, position) => ({ id: message.id, position, data: message })));
4140
+ const metadata2 = JSON.stringify({ ...record3, ...record3.agent ? { agent: { ...record3.agent, messages: [] } } : {} });
4141
+ const id3 = record3.scope.conversationId;
4142
+ await this.initialize();
4143
+ await this.transaction([
4144
+ { sql: "INSERT INTO developer_cache_meta(conversation_id, data) VALUES (?, ?) ON CONFLICT(conversation_id) DO UPDATE SET data = excluded.data", parameters: [id3, metadata2] },
4145
+ { sql: "DELETE FROM developer_cache_message WHERE conversation_id = ? AND message_id NOT IN (SELECT json_extract(value, '$.id') FROM json_each(?))", parameters: [id3, messages] },
4146
+ { sql: "INSERT INTO developer_cache_message(conversation_id, message_id, position, data) SELECT ?, json_extract(value, '$.id'), json_extract(value, '$.position'), json_extract(value, '$.data') FROM json_each(?) WHERE 1 ON CONFLICT(conversation_id, message_id) DO UPDATE SET position = excluded.position, data = excluded.data WHERE developer_cache_message.position != excluded.position OR developer_cache_message.data != excluded.data", parameters: [id3, messages] }
4147
+ ]);
4148
+ }
4149
+ async remove(conversationId) {
4150
+ await this.initialize();
4151
+ await this.transaction([
4152
+ { sql: "DELETE FROM developer_cache_message WHERE conversation_id = ?", parameters: [conversationId] },
4153
+ { sql: "DELETE FROM developer_cache_meta WHERE conversation_id = ?", parameters: [conversationId] }
4154
+ ]);
4155
+ }
4156
+ async close() {
4157
+ await this.release();
4158
+ }
4159
+ };
4160
+ function assertDeveloperCacheRecord(value) {
4161
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid3();
4162
+ const { scope, agent, history, products, workspaceMissing } = value;
4163
+ if (workspaceMissing !== void 0 && workspaceMissing !== true) invalid3();
4164
+ if (!scope || [scope.conversationId, scope.membershipEpoch, scope.workspaceId, scope.hostDeviceId].some((id3) => typeof id3 !== "string" || !id3 || id3.length > 1024)) invalid3();
4165
+ if (agent && (!agent.snapshot || agent.snapshot.workspaceId !== scope.workspaceId || typeof agent.snapshot.sessionId !== "string" || !["idle", "running"].includes(agent.snapshot.status) || typeof agent.snapshot.updatedAt !== "string" || !Array.isArray(agent.messages) || agent.messages.length > DEVELOPER_AGENT_CACHE_MESSAGES || new Set(agent.messages.map((message) => message.id)).size !== agent.messages.length || agent.messages.some((message) => !message || typeof message.id !== "string" || !message.id || !["user", "assistant"].includes(message.role) || typeof message.createdAt !== "string" || !Array.isArray(message.content) || !["complete", "error", "in_progress", "queued_for_agent", "awaiting_dispatch", "dispatching"].includes(message.status)))) invalid3();
4166
+ if (history && (typeof history.hasMore !== "boolean" || history.beforeMessageId !== void 0 && typeof history.beforeMessageId !== "string")) invalid3();
4167
+ if (products && (!Number.isSafeInteger(products.revision) || !Array.isArray(products.products) || products.products.length > 256)) invalid3();
4168
+ }
4169
+ function invalid3() {
4170
+ throw new Error("developer.cache_invalid");
4171
+ }
4172
+
4173
+ // ../workspace-agent-history.ts
4174
+ var DeveloperAgentHistory = class {
4175
+ constructor(cache, conversationId, membershipEpoch) {
4176
+ this.cache = cache;
4177
+ this.conversationId = conversationId;
4178
+ this.membershipEpoch = membershipEpoch;
4179
+ }
4180
+ state = { content: null, syncing: true, loadingHistory: false, hasMore: false, error: null };
4181
+ listeners = /* @__PURE__ */ new Set();
4182
+ all = null;
4183
+ restored;
4184
+ visible = 50;
4185
+ cursor = { hasMore: false, nextBefore: null };
4186
+ viewer;
4187
+ live;
4188
+ scope;
4189
+ streamKey;
4190
+ abort;
4191
+ detach;
4192
+ releaseCache;
4193
+ closed = false;
4194
+ initializing = false;
4195
+ startGeneration = 0;
4196
+ getSnapshot = () => this.state;
4197
+ subscribe = (listener) => {
4198
+ this.listeners.add(listener);
4199
+ return () => this.listeners.delete(listener);
4200
+ };
4201
+ start() {
4202
+ this.closed = false;
4203
+ const generation = ++this.startGeneration;
4204
+ this.initializing = !this.cache.hasHydrated(this.conversationId, this.membershipEpoch);
4205
+ this.releaseCache ??= this.cache.subscribe(() => this.restore());
4206
+ this.restore();
4207
+ const finish = (error) => {
4208
+ if (this.closed || generation !== this.startGeneration) return;
4209
+ this.initializing = false;
4210
+ this.restore();
4211
+ if (error) this.publish({ error });
4212
+ if (this.viewer) this.receive(this.viewer);
4213
+ };
4214
+ void this.cache.hydrate(this.conversationId, this.membershipEpoch).then(() => finish(), () => finish("developer.cache_read_failed"));
4215
+ }
4216
+ attach(viewer, scope) {
4217
+ this.detach?.();
4218
+ this.abort?.abort();
4219
+ this.viewer = viewer;
4220
+ this.scope = scope;
4221
+ this.streamKey = void 0;
4222
+ const receive = () => this.receive(viewer);
4223
+ const release = viewer.subscribe("agent", receive);
4224
+ receive();
4225
+ const detach = () => {
4226
+ release();
4227
+ if (this.viewer === viewer) {
4228
+ this.abort?.abort();
4229
+ this.viewer = void 0;
4230
+ this.live = void 0;
4231
+ this.streamKey = void 0;
4232
+ }
4233
+ };
4234
+ this.detach = detach;
4235
+ return detach;
4236
+ }
4237
+ close() {
4238
+ this.closed = true;
4239
+ this.startGeneration++;
4240
+ this.detach?.();
4241
+ this.releaseCache?.();
4242
+ this.listeners.clear();
4243
+ this.detach = void 0;
4244
+ this.releaseCache = void 0;
4245
+ void this.cache.flush().catch(() => {
4246
+ });
4247
+ }
4248
+ restore() {
4249
+ if (this.closed) return;
4250
+ const scope = this.cache.resolve(this.conversationId, this.membershipEpoch), cached = scope && this.cache.readAgent(scope);
4251
+ if (!this.live && cached && cached !== this.restored) {
4252
+ this.restored = cached;
4253
+ const sameSession = this.all?.snapshot.sessionId === cached.snapshot.sessionId;
4254
+ const previous = this.all;
4255
+ this.replace(sameSession ? { ...cached, messages: mergeAgentHistoryWindow(previous.messages, cached.messages) } : cached);
4256
+ const history = this.cache.readHistory(scope);
4257
+ if (!sameSession) this.cursor = { hasMore: history?.hasMore ?? false, nextBefore: null, beforeMessageId: history?.beforeMessageId };
4258
+ }
4259
+ this.publish({ error: this.cache.getStorageError() ?? this.state.error });
4260
+ }
4261
+ receive(viewer) {
4262
+ if (this.closed || this.viewer !== viewer) return;
4263
+ if (this.initializing) return;
4264
+ const state = viewer.getSnapshot("agent");
4265
+ if (state.phase !== "ready") {
4266
+ this.abort?.abort();
4267
+ this.streamKey = void 0;
4268
+ this.live = void 0;
4269
+ this.publish({ syncing: state.phase === "connecting", loadingHistory: false });
4270
+ return;
4271
+ }
4272
+ const next = state.content, key = JSON.stringify([state.generation, state.streamId, next.snapshot.sessionId]);
4273
+ this.live = next;
4274
+ if (this.all?.snapshot.sessionId !== next.snapshot.sessionId) {
4275
+ this.all = null;
4276
+ this.visible = 50;
4277
+ }
4278
+ this.replace({ snapshot: metadata(next), messages: mergeAgentHistoryWindow(this.all?.messages ?? [], next.messages) });
4279
+ if (this.streamKey !== key) {
4280
+ this.streamKey = key;
4281
+ this.abort?.abort();
4282
+ this.abort = new AbortController();
4283
+ this.publish({ syncing: true, error: this.cache.getStorageError() });
4284
+ void this.reconcile(viewer, next, this.abort.signal);
4285
+ } else {
4286
+ this.persist();
4287
+ this.publish();
4288
+ }
4289
+ }
4290
+ async reconcile(viewer, initial, signal) {
4291
+ let assembled = initial;
4292
+ let remaining = DEVELOPER_AGENT_CACHE_MESSAGES - Math.max(initial.snapshot.messages.length, initial.messages.length);
4293
+ try {
4294
+ while (assembled.history.hasMore && remaining > 0) {
4295
+ const before = assembled.history.nextBefore;
4296
+ if (before === null) throw new Error("developer.history_cursor_invalid");
4297
+ const page = await viewer.request("history", {
4298
+ sessionId: assembled.snapshot.sessionId,
4299
+ beforeSeq: before,
4300
+ limit: Math.min(100, remaining)
4301
+ }, signal);
4302
+ if (signal.aborted || this.closed) return;
4303
+ assembled = mergeDeveloperAgentHistory(assembled, page, before, assembled.history.beforeMessageId);
4304
+ const count = page.messages.length;
4305
+ if (assembled.history.hasMore && count === 0) throw new Error("developer.history_no_progress");
4306
+ remaining -= count;
4307
+ }
4308
+ if (signal.aborted || this.closed || !this.live) return;
4309
+ const first = assembled.messages[0]?.id;
4310
+ const boundary = this.all?.messages.findIndex((message) => message.id === first) ?? -1;
4311
+ const retained = assembled.history.hasMore && boundary > 0 ? this.all.messages.slice(0, boundary) : [];
4312
+ if (!retained.length) this.cursor = assembled.history;
4313
+ this.replace({ snapshot: metadata(this.live), messages: mergeAgentHistoryWindow([...retained, ...assembled.messages], this.live.messages) });
4314
+ this.persist();
4315
+ this.publish({ syncing: false });
4316
+ } catch {
4317
+ if (!signal.aborted && !this.closed) this.publish({ syncing: false, error: "developer.history_sync_failed" });
4318
+ }
4319
+ }
4320
+ loadOlder = async () => {
4321
+ if (this.closed || this.state.loadingHistory || !this.all) return;
4322
+ if (this.visible < this.all.messages.length) {
4323
+ this.visible += 50;
4324
+ this.publish();
4325
+ return;
4326
+ }
4327
+ if (!this.cursor.hasMore || this.state.syncing || !this.viewer || !this.live || this.cursor.nextBefore === null) return;
4328
+ const viewer = this.viewer, live = this.live, signal = this.abort.signal;
4329
+ const before = this.cursor.nextBefore;
4330
+ const anchor = this.all.messages[0]?.id;
4331
+ this.publish({ loadingHistory: true, error: this.cache.getStorageError() });
4332
+ try {
4333
+ const page = await viewer.request("history", { sessionId: live.snapshot.sessionId, ...anchor ? { beforeMessageId: anchor } : { beforeSeq: before }, limit: 50 }, signal);
4334
+ if (signal.aborted || this.closed || !this.all) return;
4335
+ const merged = mergeDeveloperAgentHistory({ ...live, messages: this.all.messages, history: { ...this.cursor, beforeMessageId: anchor } }, page, before, anchor);
4336
+ this.cursor = merged.history;
4337
+ this.all = { ...this.all, messages: merged.messages };
4338
+ this.visible += 50;
4339
+ this.persist();
4340
+ this.publish({ loadingHistory: false });
4341
+ } catch {
4342
+ if (!signal.aborted && !this.closed) this.publish({ loadingHistory: false, error: "developer.history_load_failed" });
4343
+ }
4344
+ };
4345
+ persist() {
4346
+ if (!this.scope || !this.all || !this.live) return;
4347
+ this.cache.saveAgent(this.scope, { ...this.live, messages: this.all.messages, history: this.cursor });
4348
+ }
4349
+ replace(next) {
4350
+ const anchor = this.all?.snapshot.sessionId === next.snapshot.sessionId ? this.all.messages.slice(-this.visible)[0]?.id : void 0;
4351
+ if (anchor) {
4352
+ const index = next.messages.findIndex((message) => message.id === anchor);
4353
+ if (index >= 0) this.visible = Math.max(this.visible, next.messages.length - index);
4354
+ }
4355
+ this.all = next;
4356
+ }
4357
+ publish(patch = {}) {
4358
+ if (this.closed) return;
4359
+ this.state = {
4360
+ ...this.state,
4361
+ ...patch,
4362
+ content: this.all ? { ...this.all, messages: this.all.messages.slice(-this.visible) } : null,
4363
+ hasMore: !!this.all && (this.visible < this.all.messages.length || this.cursor.hasMore)
4364
+ };
4365
+ for (const listener of this.listeners) listener();
4366
+ }
4367
+ };
4368
+ function metadata(view) {
4369
+ const { workspaceId, sessionId, status, updatedAt } = view.snapshot;
4370
+ return { workspaceId, sessionId, status, updatedAt };
4371
+ }
4372
+
4373
+ // ../workspace-file-view.ts
4374
+ import { assertWorkspaceFileResult, normalizeWorkspaceFileReference, normalizeWorkspaceFilePath } from "@kuafucloud/product-runtime-protocol";
4375
+ async function readDeveloperWorkspaceFile(viewer, workspaceId, path, mode, signal) {
4376
+ if (signal.aborted) throw new DeveloperRealtimeClientError("developer.request_cancelled");
4377
+ if (/^(?:\/|[a-z]:\/)/iu.test(path)) normalizeWorkspaceFileReference(path);
4378
+ else normalizeWorkspaceFilePath(path);
4379
+ const value = await viewer.request("file", { path, mode }, signal);
4380
+ if (signal.aborted) throw new DeveloperRealtimeClientError("developer.request_cancelled");
4381
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new DeveloperRealtimeClientError("developer.file_invalid");
4382
+ const result = value;
4383
+ const query = { mode, path: normalizeWorkspaceFilePath(result.path) };
4384
+ if (!/^(?:\/|[a-z]:\/)/iu.test(path) && query.path !== path) throw new DeveloperRealtimeClientError("developer.file_invalid");
4385
+ assertWorkspaceFileResult(value, workspaceId, query);
4386
+ if (value.mode === "image") return { path: value.path, kind: "image", content: `data:${value.mimeType};base64,${value.base64}` };
4387
+ if (value.mode !== "read" || value.file.binary || typeof value.file.content !== "string") throw new DeveloperRealtimeClientError("developer.file_not_text");
4388
+ return { path: value.path, kind: "text", content: value.file.content, ...value.file.truncated ? { truncated: true } : {} };
4389
+ }
4390
+
4391
+ // ../workspace-agent-member.ts
4392
+ function workspaceAgentMember(conversation, subject) {
4393
+ if (conversation.kind !== "group" || !conversation.tags?.includes("agent-workspace") || !/^agent:[a-f0-9]{64}$/u.test(subject) || !conversation.memberSubjects.includes(subject)) return;
4394
+ return { subject, displayName: `${conversation.title} Agent` };
4395
+ }
4396
+ function workspaceSenderName(conversation, subject, ...profiles) {
4397
+ const named = profiles.find((profile) => profile?.displayName && profile.nameSource !== "id");
4398
+ return named?.displayName ?? workspaceAgentMember(conversation, subject)?.displayName ?? subject;
4399
+ }
4400
+
4401
+ // ../workspace-status-view.ts
4402
+ import { normalizeWorkspaceId as normalizeWorkspaceId4 } from "@kuafucloud/product-runtime-protocol";
4403
+ function object2(raw) {
4404
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Object.values(Object.getOwnPropertyDescriptors(raw)).some((value) => value.get || value.set)) return void 0;
4405
+ return raw;
4406
+ }
4407
+ function workspaceStatusView(conversation, imStatus) {
4408
+ const summary = object2(conversation);
4409
+ if (imStatus === "signed-out" || !summary || summary.kind !== "group" || !Array.isArray(summary.tags) || !summary.tags.includes("agent-workspace")) return null;
4410
+ const business = object2(summary.businessState), value = object2(business?.["developer.workspace"]);
4411
+ if (!value || Object.keys(value).sort().join(",") !== "agentState,v,workspaceId" || value.v !== 1 || typeof value.workspaceId !== "string" || !["running", "waiting", "idle", "unknown"].includes(String(value.agentState))) return null;
4412
+ try {
4413
+ if (normalizeWorkspaceId4(value.workspaceId) !== value.workspaceId) return null;
4414
+ } catch {
4415
+ return null;
4416
+ }
4417
+ const connections = object2(summary.producerConnection), connection = object2(connections?.["developer.workspace"]);
4418
+ const valid = connection && Object.keys(connection).sort().join(",") === "observedAt,state,synchronized" && ["online", "offline", "unknown"].includes(String(connection.state)) && typeof connection.synchronized === "boolean" && Number.isSafeInteger(connection.observedAt) && Number(connection.observedAt) >= 0 && (connection.state === "online" || !connection.synchronized);
4419
+ return Object.freeze({
4420
+ workspaceId: value.workspaceId,
4421
+ observedAt: valid ? Number(connection.observedAt) : 0,
4422
+ confirmation: imStatus === "ready" ? "current" : "cached",
4423
+ state: !valid ? "unknown" : connection.state === "offline" ? "offline" : connection.state === "online" && connection.synchronized ? value.agentState : "unknown"
4424
+ });
4425
+ }
4426
+
4427
+ // ../project-workspaces.ts
4428
+ function projectSupervisorMentions(projectId, memberSubjects, members) {
4429
+ const candidates = members.filter((member) => member.actor?.status === "active" && member.actor.projectId === projectId && member.permissions?.canDevelop !== false && memberSubjects.includes(member.subject));
4430
+ const duplicateNames = new Set(candidates.filter((member, index) => candidates.some((other, otherIndex) => index !== otherIndex && member.displayName === other.displayName)).map((member) => member.displayName));
4431
+ return candidates.map((member) => ({
4432
+ subject: member.subject,
4433
+ displayName: member.displayName,
4434
+ deviceHint: duplicateNames.has(member.displayName) ? member.actor.hostDeviceId.slice(-8) : void 0
4435
+ }));
4436
+ }
4437
+ function projectSupervisorMentionText(text2, mentions) {
4438
+ return [...mentions.map((mention) => `@${mention.displayName}`), text2.trim()].join(" ");
4439
+ }
4440
+ function groupProjectWorkspaces(workspaces, members, projectId, localConversations = /* @__PURE__ */ new Set()) {
4441
+ const groups = /* @__PURE__ */ new Map();
4442
+ for (const workspace of workspaces) {
4443
+ const actors = members.filter((member) => member.actor?.projectId === projectId && workspace.memberSubjects.includes(member.subject));
4444
+ const actor = actors.length === 1 ? actors[0] : void 0;
4445
+ const deviceId = actor?.actor?.hostDeviceId;
4446
+ let group = groups.get(deviceId);
4447
+ if (!group) {
4448
+ group = { deviceId, label: actor?.actor?.deviceName ?? deviceId, local: false, workspaces: [] };
4449
+ groups.set(deviceId, group);
4450
+ }
4451
+ group.workspaces.push(workspace);
4452
+ group.local ||= localConversations.has(workspace.id);
4453
+ }
4454
+ for (const group of groups.values()) group.workspaces.sort((a, b) => Number(localConversations.has(b.id)) - Number(localConversations.has(a.id)));
4455
+ return [...groups.values()].sort((a, b) => Number(b.local) - Number(a.local));
4456
+ }
4457
+
4458
+ // ../preview-device.ts
4459
+ var PREVIEW_DEVICE_FRAME_HEIGHT_RATIO = 0.8;
4460
+ var PREVIEW_DEVICE_FRAME_BORDER_WIDTH = 8;
4461
+ var PREVIEW_DEVICE_PRESETS = [
4462
+ { id: "phone-19.5:9", category: "phone", ratio: 9 / 19.5 },
4463
+ { id: "phone-20:9", category: "phone", ratio: 9 / 20 },
4464
+ { id: "phone-16:9", category: "phone", ratio: 9 / 16 },
4465
+ { id: "tablet-4:3", category: "tablet", ratio: 3 / 4 },
4466
+ { id: "tablet-16:10", category: "tablet", ratio: 10 / 16 },
4467
+ { id: "tablet-3:2", category: "tablet", ratio: 2 / 3 }
4468
+ ];
4469
+ export {
4470
+ DEVELOPER_AGENT_CACHE_MESSAGES,
4471
+ DEVELOPER_CHANNEL_LIMITS,
4472
+ DEVELOPER_REALTIME_LIMITS,
4473
+ DEVELOPER_REALTIME_VERSION,
4474
+ DeveloperAgentHistory,
4475
+ DeveloperAgentInput,
4476
+ DeveloperHostBudget,
4477
+ DeveloperHostChannelConnection,
4478
+ DeveloperHostConnection,
4479
+ DeveloperPayloadAssembly,
4480
+ DeveloperProductPreviewHost,
4481
+ DeveloperProductPreviewViewer,
4482
+ DeveloperProductPreviewViewerHttp,
4483
+ DeveloperRealtimeClientError,
4484
+ DeveloperWorkspaceCache,
4485
+ DeveloperWorkspaceViewer,
4486
+ PREVIEW_DEVICE_FRAME_BORDER_WIDTH,
4487
+ PREVIEW_DEVICE_FRAME_HEIGHT_RATIO,
4488
+ PREVIEW_DEVICE_PRESETS,
4489
+ PRODUCT_PREVIEW_CACHE_LIMITS,
4490
+ PRODUCT_PREVIEW_LIMITS,
4491
+ ProductPreviewResourceCache,
4492
+ SqliteDeveloperCacheStore,
4493
+ agentMemberInitial,
4494
+ agentMessageMember,
4495
+ applyCommit,
4496
+ applyDelta,
4497
+ applyDeveloperAgentEvent,
4498
+ applyWorkspaceChatStream,
4499
+ assertDeveloperCacheRecord,
4500
+ assertProductPreviewRequest,
4501
+ buildProductPreviewSocketUrl,
4502
+ canAnswerAgentQuestion,
4503
+ createAgentQuestionReply,
4504
+ decodeDeveloperHostFrame,
4505
+ decodeDeveloperViewerFrame,
4506
+ decodeProductPreviewChunk,
4507
+ developerChannelKey,
4508
+ developerChannelWorkspace,
4509
+ developerWorkspaceUnavailable,
4510
+ emptyDeveloperWorkspaceView,
4511
+ encodeProductPreviewChunk,
4512
+ fragmentDeveloperPayload,
4513
+ groupProjectWorkspaces,
4514
+ isOwnAgentMessage,
4515
+ mapAgentMessagesToTimeline,
4516
+ mergeAgentHistoryWindow,
4517
+ mergeDeveloperAgentHistory,
4518
+ normalizePatchDelivery,
4519
+ normalizeWorkspaceAgentServerMessage,
4520
+ openDeveloperWebSocket,
4521
+ openProductPreviewWebSocket,
4522
+ openWorkspaceReadWebSocket,
4523
+ productPreviewHeaders,
4524
+ projectSupervisorMentionText,
4525
+ projectSupervisorMentions,
4526
+ readAgentQuestion,
4527
+ readDeveloperAgentReceipt,
4528
+ readDeveloperAgentView,
4529
+ readDeveloperChannelGrant,
4530
+ readDeveloperChannelTarget,
4531
+ readDeveloperNativePreviewSource,
4532
+ readDeveloperWorkspaceFile,
4533
+ readProductPreviewClient,
4534
+ readProductPreviewFailureCode,
4535
+ readProductPreviewSocketUrl,
4536
+ readProductPreviewTarget,
4537
+ readProductPreviewVersion,
4538
+ reduceDeveloperWorkspaceView,
4539
+ refreshDeveloperAgentView,
4540
+ restoreWorkspaceChatStream,
4541
+ standardProductPreviewHttpRuntime,
4542
+ throwIfProductPreviewAborted,
4543
+ validDeveloperPayloadPart,
4544
+ validServiceSocketText,
4545
+ validStream,
4546
+ workspaceAgentMember,
4547
+ workspaceChatTimeline,
4548
+ workspaceSenderName,
4549
+ workspaceStatusView
4550
+ };