scope-agent-workbench 0.2.0 → 0.2.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 (88) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bridge/agent-email-relay.mjs +160 -160
  3. package/bridge/app-server-websocket-transport.mjs +219 -219
  4. package/bridge/archive/service.mjs +130 -130
  5. package/bridge/auth-profile-failover.mjs +58 -58
  6. package/bridge/auth-profile-manager.mjs +215 -215
  7. package/bridge/capacity-recovery.mjs +90 -90
  8. package/bridge/gpu-usage-history.mjs +322 -322
  9. package/bridge/local/history.mjs +20 -5
  10. package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
  11. package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
  12. package/bridge/private-gateway.mjs +371 -371
  13. package/bridge/private-start.mjs +22 -22
  14. package/bridge/probes/app-server-handoff-probe.mjs +87 -87
  15. package/bridge/probes/app-server-writer-probe.mjs +69 -69
  16. package/bridge/probes/assistant-search-probe.mjs +321 -321
  17. package/bridge/probes/dialogue-probe.mjs +462 -462
  18. package/bridge/probes/history-probe.mjs +430 -345
  19. package/bridge/probes/new-session-preflight.mjs +14 -14
  20. package/bridge/probes/profile-cancel-probe.mjs +17 -17
  21. package/bridge/probes/profile-delete-probe.mjs +26 -26
  22. package/bridge/probes/profile-list-probe.mjs +114 -114
  23. package/bridge/probes/profile-write-probe.mjs +109 -109
  24. package/bridge/probes/raw-context-probe.mjs +51 -51
  25. package/bridge/probes/remote-probe.mjs +627 -626
  26. package/bridge/probes/submission-probe.mjs +2 -2
  27. package/bridge/probes/takeover-probe.mjs +326 -326
  28. package/bridge/probes/vscode-open-preflight.mjs +21 -21
  29. package/bridge/providers/claude-interactive.py +463 -341
  30. package/bridge/providers/cli-command.mjs +103 -103
  31. package/bridge/providers/conversations.mjs +231 -231
  32. package/bridge/providers/native-commands.py +38 -38
  33. package/bridge/providers/native-session-state.mjs +14 -14
  34. package/bridge/providers/native-session-state.py +96 -96
  35. package/bridge/providers/remote-job.py +130 -130
  36. package/bridge/remote-app-server-command.mjs +121 -121
  37. package/bridge/remote-directory-listing.mjs +148 -148
  38. package/bridge/rollout-summary.mjs +20 -2
  39. package/bridge/routes/dialogue.mjs +48 -3
  40. package/bridge/routes/models.mjs +312 -312
  41. package/bridge/server.mjs +3357 -3332
  42. package/bridge/session-attachments.mjs +150 -150
  43. package/bridge/session-catalog/agy-history.py +141 -2
  44. package/bridge/session-catalog/catalog.mjs +17 -0
  45. package/bridge/session-catalog/probe.py +1207 -331
  46. package/bridge/session-catalog/routes.mjs +6 -0
  47. package/bridge/start.mjs +205 -205
  48. package/bridge/state-persistence.mjs +9 -1
  49. package/bridge/tmux-session-control.mjs +29 -29
  50. package/bridge/vscode-opener.mjs +157 -157
  51. package/bridge/web-terminal.mjs +52 -52
  52. package/bridge/workbench/manager-context.mjs +51 -51
  53. package/bridge/workbench/service.mjs +301 -301
  54. package/dist/client/.vite/manifest.json +4 -4
  55. package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
  56. package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
  57. package/dist/client/assets/page-CJqXlhDs.js +551 -0
  58. package/dist/client/assets/page-LYzRz6_S.css +1 -0
  59. package/dist/client/favicon.svg +6 -6
  60. package/dist/server/__vite_rsc_assets_manifest.js +8 -8
  61. package/dist/server/index.js +7 -7
  62. package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
  63. package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
  64. package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
  65. package/dist/server/ssr/index.js +1 -1
  66. package/dist/server/ssr/vinext-server.json +1 -1
  67. package/dist/server/vinext-server.json +1 -1
  68. package/dist/server/wrangler.json +1 -1
  69. package/lib/browser-snapshot-cache.js +53 -53
  70. package/lib/formula-preview.js +1 -1
  71. package/lib/incremental-snapshot.js +300 -300
  72. package/lib/markdown-math.js +151 -151
  73. package/lib/remote-links.js +95 -95
  74. package/lib/runtime-config.js +70 -70
  75. package/lib/session-filters.js +38 -38
  76. package/lib/ssh-config.js +26 -26
  77. package/lib/stable-order.js +39 -39
  78. package/lib/subagent-display-prefs.ts +130 -0
  79. package/package.json +1 -1
  80. package/scripts/agent-email-relay.mjs +104 -104
  81. package/scripts/email-notification-cli.mjs +28 -28
  82. package/scripts/enable-private-access.ps1 +109 -109
  83. package/scripts/fixtures/native-conversations.mjs +164 -6
  84. package/scripts/fixtures/workbench-conversations.mjs +475 -352
  85. package/scripts/preview-workbench.mjs +669 -669
  86. package/dist/client/assets/page-COBv6VWj.css +0 -1
  87. package/dist/client/assets/page-DVjU6VG_.js +0 -550
  88. package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
@@ -1,669 +1,669 @@
1
- /** Isolated UI fixture: synthetic inventory and adapters, no SSH or model calls. */
2
- import { sessionArchiveService } from "../bridge/archive/service.mjs";
3
- import { archiveRoutes } from "../bridge/archive/routes.mjs";
4
- import { createServer } from "node:http";
5
- import { mkdtemp, readFile } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import path from "node:path";
8
- import { startProductionUiServer } from "../bridge/ui-server.mjs";
9
- import { WorkbenchStore } from "../bridge/workbench/store.mjs";
10
- import { WorkbenchService } from "../bridge/workbench/service.mjs";
11
- import { workbenchRoutes } from "../bridge/workbench/routes.mjs";
12
- import { createIncrementalSnapshotStore } from "../lib/incremental-snapshot.js";
13
- import { createConversationFixture } from "./fixtures/workbench-conversations.mjs";
14
- import { nativeConversationFixture } from "./fixtures/native-conversations.mjs";
15
- import { PluginRegistry } from "../bridge/plugins/registry.mjs";
16
- import { pluginRoutes } from "../bridge/plugins/routes.mjs";
17
- import { createAliyunDlcPlugin } from "../bridge/plugins/aliyun-dlc/index.mjs";
18
- import { fileURLToPath } from "node:url";
19
- import { installPackage } from "../bridge/plugins/package.mjs";
20
- import { loadExternalPlugins } from "../bridge/plugins/external.mjs";
21
-
22
- const isEn = process.env.SCOPE_PREVIEW_LOCALE === "en";
23
- const dir = await mkdtemp(path.join(tmpdir(), "scope-ui-preview-"));
24
- const store = await new WorkbenchStore(path.join(dir, "workbench.json")).load();
25
- const projects = [
26
- { host: "lab-gpu", cwd: "/workspace/vision", name: "Vision Lab" },
27
- { host: "build-node", cwd: "/workspace/scope", name: "SCOPE" },
28
- { host: "lab-gpu", cwd: "/workspace/research", name: isEn ? "Research Notes" : "研究笔记" },
29
- ];
30
- const snapshot = {
31
- generatedAt: new Date().toISOString(),
32
- scanning: false,
33
- sshConfig: "Preview fixture — no SSH",
34
- summary: { hosts: 2, online: 2, codex: 0, tmux: 0, attention: 0 },
35
- management: {
36
- operatorName: isEn ? "Preview" : "预览",
37
- sessions: {
38
- "lab-gpu:vision-plan": {
39
- reserved: true,
40
- reservedUpdatedAt: new Date().toISOString(),
41
- },
42
- },
43
- projects,
44
- hostRuntimeConfigs: {},
45
- resourcePolicy: { prompt: "", version: 0, updatedAt: null },
46
- },
47
- appServer: {
48
- experimental: true,
49
- connections: [],
50
- sessions: [],
51
- pendingRequests: [],
52
- pendingInputs: [],
53
- },
54
- submissionTracker: {
55
- scannedAt: null,
56
- scanning: false,
57
- windowDays: 1,
58
- items: [],
59
- calls: [],
60
- launches: [],
61
- alerts: [],
62
- hosts: [],
63
- error: null,
64
- },
65
- gpuUsage: { updatedAt: null, retentionHours: 168, episodes: [] },
66
- notifications: { email: { enabled: false, configured: false, to: [] } },
67
- hosts: [
68
- ...["lab-gpu", "build-node"].map((alias) => ({
69
- alias,
70
- hostname: alias === "lab-gpu" ? "gpu-cluster-a01" : "build-node-02",
71
- reachable: true,
72
- latencyMs: alias === "lab-gpu" ? 14 : 9,
73
- inventoryUpdatedAt: new Date().toISOString(),
74
- error: null,
75
- processes: [],
76
- panes: [],
77
- sessions: [],
78
- agents: [],
79
- workloads: [],
80
- gpus:
81
- alias === "lab-gpu"
82
- ? [
83
- {
84
- index: 0,
85
- name: "NVIDIA A100-SXM4-80GB",
86
- utilization: 94,
87
- memoryUsed: 68420,
88
- memoryTotal: 81920,
89
- },
90
- {
91
- index: 1,
92
- name: "NVIDIA A100-SXM4-80GB",
93
- utilization: 88,
94
- memoryUsed: 64110,
95
- memoryTotal: 81920,
96
- },
97
- {
98
- index: 2,
99
- name: "NVIDIA A100-SXM4-80GB",
100
- utilization: 12,
101
- memoryUsed: 10240,
102
- memoryTotal: 81920,
103
- },
104
- {
105
- index: 3,
106
- name: "NVIDIA A100-SXM4-80GB",
107
- utilization: 0,
108
- memoryUsed: 480,
109
- memoryTotal: 81920,
110
- },
111
- ]
112
- : [
113
- {
114
- index: 0,
115
- name: "NVIDIA GeForce RTX 4090",
116
- utilization: 36,
117
- memoryUsed: 9840,
118
- memoryTotal: 24564,
119
- },
120
- ],
121
- })),
122
- {
123
- alias: "archive-node",
124
- hostname: "archive-node",
125
- reachable: false,
126
- latencyMs: null,
127
- inventoryUpdatedAt: null,
128
- error: "Connection timed out",
129
- processes: [],
130
- panes: [],
131
- sessions: [],
132
- agents: [],
133
- workloads: [],
134
- gpus: [],
135
- },
136
- {
137
- alias: "eval-rack-2",
138
- hostname: "eval-rack-2",
139
- reachable: false,
140
- latencyMs: null,
141
- inventoryUpdatedAt: null,
142
- error: "Host offline (maintenance)",
143
- processes: [],
144
- panes: [],
145
- sessions: [],
146
- agents: [],
147
- workloads: [],
148
- gpus: [],
149
- },
150
- ],
151
- };
152
- snapshot.hosts.unshift({alias: "@local", hostname: "workstation", reachable: true, defaultCwd: "/workspace", kind: "local", latencyMs: 0, error: null, processes: [], panes: [], sessions: [], agents: [], workloads: [], gpus: []});
153
- snapshot.summary.hosts = 5; snapshot.summary.online = 3;
154
- const maintenanceFixture = new Map();
155
- const emailFixture = {
156
- enabled: false,
157
- configured: false,
158
- to: [],
159
- from: "",
160
- monitorUrl: "http://localhost:3000/",
161
- cooldownMinutes: 15,
162
- triggers: { humanRequests: true, agentCompletion: true, dlcAlerts: true },
163
- smtp: { host: "", port: 465, secure: true },
164
- smtpUser: "",
165
- hasPassword: false,
166
- credentialSource: null,
167
- lastSentAt: null,
168
- lastError: null,
169
- };
170
- const adapter = {
171
- async archive() {},
172
- async restore() {},
173
- async launch(task) {
174
- return { startedAt: Date.now(), id: task.id };
175
- },
176
- async poll(task) {
177
- return Date.now() - task.remote.startedAt < 3500
178
- ? { status: "running" }
179
- : {
180
- status: "completed",
181
- text: "这是隔离预览的模拟回复,没有调用任何远端 Agent。\n\n可以从项目进展开始,或者在资源页为新任务选择执行主机。",
182
- };
183
- },
184
- };
185
- const service = new WorkbenchService({
186
- store,
187
- snapshot: () => snapshot,
188
- adapters: { codex: adapter, claude: adapter, dsh: adapter },
189
- });
190
- await store.update((state) => {
191
- state.tasks.push({
192
- id: "preview-task",
193
- requestId: "preview-task",
194
- kind: "task",
195
- host: "build-node",
196
- cwd: "/workspace/scope",
197
- provider: "codex",
198
- prompt: isEn ? "Refactor backend modules & API routes" : "整理后端模块与接口",
199
- status: "completed",
200
- gpuIndices: [],
201
- gpuCount: 0,
202
- minMemoryMiB: 0,
203
- createdAt: new Date().toISOString(),
204
- updatedAt: new Date().toISOString(),
205
- remote: { sessionId: "preview-task-session" },
206
- });
207
- });
208
- service.start();
209
- const sync = createIncrementalSnapshotStore({
210
- epoch: `scope-isolated-preview-${crypto.randomUUID()}`,
211
- });
212
- sync.publish(snapshot);
213
- const clients = new Set();
214
- const conversations = createConversationFixture(snapshot, () => {
215
- snapshot.generatedAt = new Date().toISOString();
216
- sync.publish(snapshot);
217
- for (const response of clients)
218
- response.write(
219
- `data: ${JSON.stringify({ type: "snapshot-invalidated", ...sync.info() })}\n\n`,
220
- );
221
- });
222
- sync.publish(snapshot);
223
- const jsonResponse = (response, status, value) => {
224
- response.writeHead(status, {
225
- "content-type": "application/json; charset=utf-8",
226
- });
227
- response.end(JSON.stringify(value));
228
- };
229
- const readJsonBody = async (request) => {
230
- let text = "";
231
- for await (const chunk of request) {
232
- text += chunk;
233
- if (text.length > 100000) throw new Error("too large");
234
- }
235
- return JSON.parse(text || "{}");
236
- };
237
- const routes = workbenchRoutes(service, { jsonResponse, readJsonBody });
238
- const fixturePlugins = new PluginRegistry();
239
- installPackage(fileURLToPath(new URL("../examples/plugins/hello", import.meta.url)), dir);
240
- loadExternalPlugins(fixturePlugins, dir);
241
- fixturePlugins.register(createAliyunDlcPlugin({ stateDirectory: dir, legacyHost: "",
242
- context: () => ({ readSshConfig: async () => "", sshAliasesForHostname: () => new Set(), getSnapshot: () => ({ hosts: [] }) }),
243
- notify() {}, onScanComplete: async () => {} }));
244
- const fixturePluginRoutes = pluginRoutes(fixturePlugins);
245
- fixturePlugins.start();
246
- const archives = sessionArchiveService({
247
- manager: {
248
- sessionRecords: () => snapshot.appServer.sessions,
249
- async archiveSession(host, id) {
250
- const agent = snapshot.hosts
251
- .find((h) => h.alias === host)
252
- ?.agents.find((a) => a.rollout.id === id);
253
- if (agent?.status === "working") throw new Error("会话仍在执行");
254
- },
255
- async unarchiveSession() {
256
- return {};
257
- },
258
- async resumeSession() {},
259
- },
260
- getState: () => snapshot.management,
261
- persist: async () => {},
262
- findAgent: (host, id) =>
263
- snapshot.hosts
264
- .find((h) => h.alias === host)
265
- ?.agents.find((a) => a.rollout.id === id),
266
- getHost: (host) => snapshot.hosts.find((h) => h.alias === host),
267
- executable: () => "codex",
268
- connectionKey: async () => "active",
269
- restored() {},
270
- notify() {
271
- snapshot.generatedAt = new Date().toISOString();
272
- sync.publish(snapshot);
273
- for (const response of clients)
274
- response.write(
275
- `data: ${JSON.stringify({ type: "snapshot-invalidated", ...sync.info() })}\n\n`,
276
- );
277
- },
278
- });
279
- const archiveRoute = archiveRoutes(archives, { jsonResponse, readJsonBody });
280
- const previewHost = process.env.SCOPE_PREVIEW_HOST || "127.0.0.1";
281
- const previewPort = Number(process.env.SCOPE_PREVIEW_PORT || 3001);
282
- const ui = await startProductionUiServer({ host: "127.0.0.1", port: 0 });
283
- const uiPort = ui.address().port;
284
- const createdDirectories = new Map();
285
- const fixtureImageBytes = await readFile(new URL("./fixtures/media/convergence.png", import.meta.url));
286
- const fixtureVideoBytes = await readFile(new URL("./fixtures/media/rollout_demo.mp4", import.meta.url));
287
- const preview = createServer(async (request, response) => {
288
- try {
289
- const url = new URL(request.url, `http://${previewHost}:${previewPort}`);
290
- if (url.pathname === "/scope-image-api") {
291
- response.writeHead(200, {
292
- "content-type": "image/png",
293
- "content-length": String(fixtureImageBytes.length),
294
- "cache-control": "private, max-age=60",
295
- });
296
- response.end(fixtureImageBytes);
297
- return;
298
- }
299
- if (url.pathname === "/scope-video-api") {
300
- const total = fixtureVideoBytes.length;
301
- const rangeHeader = request.headers.range;
302
- if (rangeHeader && /^bytes=(\d*)-(\d*)$/.test(rangeHeader)) {
303
- const [, rawStart, rawEnd] = rangeHeader.match(/^bytes=(\d*)-(\d*)$/);
304
- const start = rawStart ? Number(rawStart) : 0;
305
- const end = rawEnd ? Math.min(total - 1, Number(rawEnd)) : total - 1;
306
- const slice = fixtureVideoBytes.subarray(start, end + 1);
307
- response.writeHead(206, {
308
- "content-type": "video/mp4",
309
- "accept-ranges": "bytes",
310
- "content-range": `bytes ${start}-${end}/${total}`,
311
- "content-length": String(slice.length),
312
- });
313
- response.end(slice);
314
- return;
315
- }
316
- response.writeHead(200, {
317
- "content-type": "video/mp4",
318
- "accept-ranges": "bytes",
319
- "content-length": String(total),
320
- });
321
- response.end(fixtureVideoBytes);
322
- return;
323
- }
324
- if (await fixturePluginRoutes(request, response, new URL(url.pathname.replace(/^\/scope-api/, "") + url.search, url.origin))) return;
325
- if (url.pathname === "/scope-directory-api") {
326
- const cwd = url.searchParams.get("path") || "/workspace";
327
- const host = url.searchParams.get("host");
328
- const names = createdDirectories.get(`${host}:${cwd}`) || [
329
- "data",
330
- "experiments",
331
- ];
332
- return jsonResponse(response, 200, {
333
- host,
334
- cwd,
335
- parent:
336
- cwd === "/" ? null : cwd.split("/").slice(0, -1).join("/") || "/",
337
- directories: names.map((name) => ({
338
- name,
339
- path: `${cwd.replace(/\/$/, "")}/${name}`,
340
- })),
341
- truncated: false,
342
- });
343
- }
344
- if (url.pathname.startsWith("/scope-api/")) {
345
- url.pathname = url.pathname.slice("/scope-api".length);
346
- if (
347
- url.pathname === "/api/remote/directories" &&
348
- request.method === "POST"
349
- ) {
350
- const { host, parent, name } = await readJsonBody(request);
351
- const key = `${host}:${parent}`;
352
- const names = createdDirectories.get(key) || ["data", "experiments"];
353
- if (names.includes(name))
354
- return jsonResponse(response, 400, { error: "同名文件或目录已存在" });
355
- createdDirectories.set(key, [...names, name]);
356
- return jsonResponse(response, 200, {
357
- host,
358
- cwd: `${parent.replace(/\/$/, "")}/${name}`,
359
- });
360
- }
361
- if (url.pathname === "/api/session/attachment" && request.method === "POST") {
362
- let size = 0;
363
- for await (const chunk of request) size += chunk.length;
364
- const name = (url.searchParams.get("name") || "attachment").trim() || "attachment";
365
- const mimeType = (url.searchParams.get("mimeType") || "application/octet-stream").trim();
366
- return jsonResponse(response, 201, {
367
- ok: true,
368
- attachment: {
369
- token: crypto.randomUUID(),
370
- name,
371
- mimeType,
372
- kind: mimeType.startsWith("image/") ? "image" : "file",
373
- size,
374
- sha256: "preview",
375
- remotePath: `/workspace/.codex/scope-attachments/${name}`,
376
- },
377
- });
378
- }
379
- if (nativeConversationFixture(request, response, url, jsonResponse)) return;
380
- if (await archiveRoute(request, response, url)) return;
381
- if (await routes(request, response, url)) return;
382
- if (
383
- await conversations(request, response, url, jsonResponse, readJsonBody)
384
- )
385
- return;
386
- if (url.pathname === "/api/events") {
387
- response.writeHead(200, { "content-type": "text/event-stream" });
388
- response.write('data: {"type":"ready"}\n\n');
389
- clients.add(response);
390
- response.on("close", () => clients.delete(response));
391
- return;
392
- }
393
- if (url.pathname === "/api/sync")
394
- return jsonResponse(
395
- response,
396
- 200,
397
- sync.read({
398
- clientEpoch: url.searchParams.get("epoch"),
399
- since: url.searchParams.get("since"),
400
- }),
401
- );
402
- if (url.pathname === "/api/history/cache")
403
- return jsonResponse(response, 200, {
404
- cached: true,
405
- scope: "preview",
406
- sessions: [],
407
- hosts: [],
408
- scannedAt: new Date().toISOString(),
409
- });
410
- if (url.pathname === "/api/agents/maintenance") {
411
- if (request.method === "POST") {
412
- const body = await readJsonBody(request);
413
- const job = {id: crypto.randomUUID(), action: body.action, status: "completed", info: {installed: body.action === "check" ? null : "fixture 1.0.0", latest: "1.0.0", supported: body.provider !== "antigravity"}, log: "Isolated fixture: no installation executed"};
414
- maintenanceFixture.set(body.host + ":" + body.provider, job);
415
- return jsonResponse(response, 202, {job});
416
- }
417
- return jsonResponse(response, 200, {agents: ["codex", "claude", "antigravity", "dsh"].map(provider => ({provider, job: maintenanceFixture.get(url.searchParams.get("host") + ":" + provider) || null}))});
418
- }
419
- if (url.pathname === "/api/email/settings") {
420
- if (request.method === "POST") {
421
- const body = await readJsonBody(request);
422
- Object.assign(emailFixture, {
423
- enabled: Boolean(body.enabled),
424
- configured: Boolean(body.enabled && body.smtp?.host && body.to),
425
- to: Array.isArray(body.to) ? body.to : String(body.to || "").split(/[,;\n]+/).map((s) => s.trim()).filter(Boolean),
426
- from: body.from || "",
427
- monitorUrl: body.monitorUrl || "http://localhost:3000/",
428
- cooldownMinutes: Number(body.cooldownMinutes ?? 15),
429
- triggers: body.triggers || emailFixture.triggers,
430
- smtp: body.smtp || emailFixture.smtp,
431
- smtpUser: body.smtpUser ?? emailFixture.smtpUser,
432
- hasPassword: body.clearCredentials ? false : Boolean(body.smtpPass || emailFixture.hasPassword),
433
- });
434
- return jsonResponse(response, 200, { ok: true, settings: emailFixture });
435
- }
436
- return jsonResponse(response, 200, emailFixture);
437
- }
438
- if (url.pathname === "/api/email/verify" || url.pathname === "/api/email/test") {
439
- return jsonResponse(response, 200, { ok: true, messageId: "fixture-mail-1", settings: emailFixture });
440
- }
441
- if (url.pathname === "/api/remote-bootstrap") {
442
- const host = request.method === "POST" ? (await readJsonBody(request)).host : url.searchParams.get("host") || "";
443
- return jsonResponse(response, 200, {
444
- host,
445
- checkedAt: new Date().toISOString(),
446
- lastAction: "inspect",
447
- report: {
448
- user: "researcher",
449
- isRoot: false,
450
- home: "/home/researcher",
451
- python3: "Python 3.11.8",
452
- node: "v22.14.0",
453
- npm: true,
454
- tmux: true,
455
- gpuCount: host === "lab-gpu" ? 2 : 0,
456
- localBinInPath: true,
457
- systemdUserAvailable: true,
458
- clis: {
459
- codex: { installed: true, executable: "/home/researcher/.local/bin/codex", version: "0.158.0" },
460
- claude: { installed: true, executable: "/home/researcher/.local/bin/claude", version: "2.1.325" },
461
- antigravity: { installed: false, executable: null, version: null },
462
- dsh: { installed: false, executable: null, version: null },
463
- },
464
- scopeProtocol: { codex: true, claude: true, antigravity: true },
465
- scopeNotify: { installed: false, executable: null, daemonActive: false, systemdServiceActive: false, relayReachable: false, queued: 0, lastDeliveredAt: null, codexMcp: false, claudeMcp: false },
466
- },
467
- tunnel: { enabled: false, remotePort: 4922, status: "disabled", connectedAt: null, lastError: null },
468
- relay: { relayListening: false, relayPort: 4822, relayTokenReady: false },
469
- });
470
- }
471
- if (url.pathname === "/api/auth/profiles") {
472
- const host = url.searchParams.get("host") || "lab-gpu";
473
- const isLocal = host === "@local";
474
- return jsonResponse(response, 200, {
475
- host,
476
- local: isLocal,
477
- defaultAuthPresent: true,
478
- activeProfile: isLocal ? null : "lab-pro",
479
- currentAccount: {
480
- type: "chatgpt",
481
- email: "researcher@example.com",
482
- planType: "pro",
483
- },
484
- runningSessions: isLocal ? 0 : 3,
485
- profiles: isLocal
486
- ? []
487
- : [
488
- {
489
- slug: "lab-pro",
490
- name: "Lab Pro",
491
- createdAt: new Date(Date.now() - 86400_000 * 14).toISOString(),
492
- updatedAt: new Date().toISOString(),
493
- account: { type: "chatgpt", email: "researcher@example.com", planType: "pro" },
494
- ready: true,
495
- active: true,
496
- },
497
- {
498
- slug: "backup-plus",
499
- name: "Backup Plus",
500
- createdAt: new Date(Date.now() - 86400_000 * 7).toISOString(),
501
- updatedAt: new Date().toISOString(),
502
- account: { type: "chatgpt", email: "backup-team@example.com", planType: "plus" },
503
- ready: true,
504
- active: false,
505
- },
506
- ],
507
- restartJob: null,
508
- automaticFailover: null,
509
- });
510
- }
511
- if (url.pathname === "/api/auth/quota") {
512
- const host = url.searchParams.get("host") || "lab-gpu";
513
- const nowSec = Math.floor(Date.now() / 1000);
514
- const currentQuota = {
515
- planType: "pro",
516
- primary: { usedPercent: 9, remainingPercent: 91, windowMinutes: 300, resetsAt: nowSec + 11_400, expired: false },
517
- secondary: { usedPercent: 26, remainingPercent: 74, windowMinutes: 10080, resetsAt: nowSec + 410_000, expired: false },
518
- credits: null,
519
- };
520
- if (url.searchParams.get("all") === "1") {
521
- return jsonResponse(response, 200, {
522
- host,
523
- local: host === "@local",
524
- fetchedAt: new Date().toISOString(),
525
- currentAccount: { type: "chatgpt", email: "researcher@example.com", planType: "pro" },
526
- currentQuota,
527
- profileQuotas:
528
- host === "@local"
529
- ? {}
530
- : {
531
- "lab-pro": { quota: currentQuota, error: null },
532
- "backup-plus": {
533
- quota: {
534
- planType: "plus",
535
- primary: { usedPercent: 18, remainingPercent: 82, windowMinutes: 300, resetsAt: nowSec + 14_200, expired: false },
536
- secondary: { usedPercent: 12, remainingPercent: 88, windowMinutes: 10080, resetsAt: nowSec + 500_000, expired: false },
537
- credits: null,
538
- },
539
- error: null,
540
- },
541
- },
542
- error: null,
543
- });
544
- }
545
- return jsonResponse(response, 200, {
546
- host,
547
- connectionKey: url.searchParams.get("connectionKey") || "active",
548
- quota: currentQuota,
549
- source: "app-server",
550
- error: null,
551
- });
552
- }
553
- if (url.pathname === "/api/auth/providers") {
554
- const host = url.searchParams.get("host") || "lab-gpu";
555
- const nowSec = Math.floor(Date.now() / 1000);
556
- return jsonResponse(response, 200, {
557
- host,
558
- local: host === "@local",
559
- fetchedAt: new Date().toISOString(),
560
- claude: {
561
- installed: true,
562
- executable: "/usr/local/bin/claude",
563
- loggedIn: true,
564
- email: "researcher@example.com",
565
- authMethod: "claude.ai",
566
- subscriptionType: "max",
567
- planTier: "max_20x",
568
- orgName: "Vision Research Lab",
569
- loginExpiresAt: new Date(Date.now() + 86400_000 * 30).toISOString(),
570
- quota: {
571
- planType: "max_20x",
572
- primary: { usedPercent: 11, remainingPercent: 89, windowMinutes: 300, resetsAt: nowSec + 9_600, expired: false },
573
- secondary: { usedPercent: 5, remainingPercent: 95, windowMinutes: 10080, resetsAt: nowSec + 518_400, expired: false },
574
- credits: null,
575
- },
576
- quotaError: null,
577
- error: null,
578
- },
579
- antigravity: {
580
- installed: true,
581
- executable: "/usr/local/bin/agy",
582
- loggedIn: true,
583
- email: "researcher@example.com",
584
- authMethod: "consumer",
585
- defaultModel: "Gemini 2.5 Pro (High)",
586
- useG1Credits: true,
587
- quota: {
588
- planType: null,
589
- primary: { usedPercent: 4, remainingPercent: 96, windowMinutes: 300, resetsAt: nowSec + 12_600, expired: false },
590
- secondary: { usedPercent: 16, remainingPercent: 84, windowMinutes: 10080, resetsAt: nowSec + 432_000, expired: false },
591
- credits: { hasCredits: true, unlimited: false, balance: isEn ? "G1 Credits enabled" : "G1 Credits 已启用" },
592
- groups: [
593
- {
594
- name: "Gemini Models",
595
- primary: { usedPercent: 4, remainingPercent: 96, windowMinutes: 300, resetsAt: nowSec + 12_600, expired: false },
596
- secondary: { usedPercent: 16, remainingPercent: 84, windowMinutes: 10080, resetsAt: nowSec + 432_000, expired: false },
597
- },
598
- {
599
- name: "Claude and GPT models",
600
- primary: { usedPercent: 0, remainingPercent: 100, windowMinutes: 300, resetsAt: nowSec + 16_200, expired: false },
601
- secondary: { usedPercent: 7, remainingPercent: 93, windowMinutes: 10080, resetsAt: nowSec + 360_000, expired: false },
602
- },
603
- ],
604
- },
605
- quotaError: null,
606
- error: null,
607
- },
608
- });
609
- }
610
- if (url.pathname === "/api/models")
611
- return jsonResponse(response, 200, {
612
- models: [
613
- {
614
- id: "o3",
615
- model: "o3",
616
- displayName: "o3",
617
- supportedReasoningEfforts: ["medium", "high", "xhigh"],
618
- defaultReasoningEffort: "high",
619
- },
620
- {
621
- id: "gpt-5-codex",
622
- model: "gpt-5-codex",
623
- displayName: "GPT-5 Codex",
624
- supportedReasoningEfforts: ["medium", "high", "xhigh"],
625
- defaultReasoningEffort: "high",
626
- },
627
- ],
628
- });
629
- return jsonResponse(response, 200, {});
630
- }
631
- const upstream = await fetch(`http://127.0.0.1:${uiPort}${request.url}`);
632
- const outHeaders = Object.fromEntries(
633
- [...upstream.headers].filter(
634
- ([key]) => !["content-encoding", "content-length"].includes(key),
635
- ),
636
- );
637
- const contentType = upstream.headers.get("content-type") || "";
638
- if (contentType.includes("text/html")) {
639
- const html = (await upstream.text()).replace(
640
- /<head(\b[^>]*)>/i,
641
- '<head$1><meta name="scope-bridge-url" content="/scope-api">',
642
- );
643
- response.writeHead(upstream.status, outHeaders);
644
- response.end(html);
645
- return;
646
- }
647
- response.writeHead(upstream.status, outHeaders);
648
- response.end(Buffer.from(await upstream.arrayBuffer()));
649
- } catch (error) {
650
- jsonResponse(response, 500, { error: error.message });
651
- }
652
- });
653
- preview.listen(previewPort, previewHost, () =>
654
- console.log(
655
- `Isolated preview: http://${previewHost}:${previewPort} (synthetic data, no SSH; temporary state: ` +
656
- dir +
657
- ")",
658
- ),
659
- );
660
- function stop() {
661
- fixturePlugins.stop();
662
- service.stop();
663
- preview.closeAllConnections();
664
- preview.close();
665
- ui.closeAllConnections();
666
- ui.close(() => process.exit(0));
667
- }
668
- process.once("SIGINT", stop);
669
- process.once("SIGTERM", stop);
1
+ /** Isolated UI fixture: synthetic inventory and adapters, no SSH or model calls. */
2
+ import { sessionArchiveService } from "../bridge/archive/service.mjs";
3
+ import { archiveRoutes } from "../bridge/archive/routes.mjs";
4
+ import { createServer } from "node:http";
5
+ import { mkdtemp, readFile } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import path from "node:path";
8
+ import { startProductionUiServer } from "../bridge/ui-server.mjs";
9
+ import { WorkbenchStore } from "../bridge/workbench/store.mjs";
10
+ import { WorkbenchService } from "../bridge/workbench/service.mjs";
11
+ import { workbenchRoutes } from "../bridge/workbench/routes.mjs";
12
+ import { createIncrementalSnapshotStore } from "../lib/incremental-snapshot.js";
13
+ import { createConversationFixture } from "./fixtures/workbench-conversations.mjs";
14
+ import { nativeConversationFixture } from "./fixtures/native-conversations.mjs";
15
+ import { PluginRegistry } from "../bridge/plugins/registry.mjs";
16
+ import { pluginRoutes } from "../bridge/plugins/routes.mjs";
17
+ import { createAliyunDlcPlugin } from "../bridge/plugins/aliyun-dlc/index.mjs";
18
+ import { fileURLToPath } from "node:url";
19
+ import { installPackage } from "../bridge/plugins/package.mjs";
20
+ import { loadExternalPlugins } from "../bridge/plugins/external.mjs";
21
+
22
+ const isEn = process.env.SCOPE_PREVIEW_LOCALE === "en";
23
+ const dir = await mkdtemp(path.join(tmpdir(), "scope-ui-preview-"));
24
+ const store = await new WorkbenchStore(path.join(dir, "workbench.json")).load();
25
+ const projects = [
26
+ { host: "lab-gpu", cwd: "/workspace/vision", name: "Vision Lab" },
27
+ { host: "build-node", cwd: "/workspace/scope", name: "SCOPE" },
28
+ { host: "lab-gpu", cwd: "/workspace/research", name: isEn ? "Research Notes" : "研究笔记" },
29
+ ];
30
+ const snapshot = {
31
+ generatedAt: new Date().toISOString(),
32
+ scanning: false,
33
+ sshConfig: "Preview fixture — no SSH",
34
+ summary: { hosts: 2, online: 2, codex: 0, tmux: 0, attention: 0 },
35
+ management: {
36
+ operatorName: isEn ? "Preview" : "预览",
37
+ sessions: {
38
+ "lab-gpu:vision-plan": {
39
+ reserved: true,
40
+ reservedUpdatedAt: new Date().toISOString(),
41
+ },
42
+ },
43
+ projects,
44
+ hostRuntimeConfigs: {},
45
+ resourcePolicy: { prompt: "", version: 0, updatedAt: null },
46
+ },
47
+ appServer: {
48
+ experimental: true,
49
+ connections: [],
50
+ sessions: [],
51
+ pendingRequests: [],
52
+ pendingInputs: [],
53
+ },
54
+ submissionTracker: {
55
+ scannedAt: null,
56
+ scanning: false,
57
+ windowDays: 1,
58
+ items: [],
59
+ calls: [],
60
+ launches: [],
61
+ alerts: [],
62
+ hosts: [],
63
+ error: null,
64
+ },
65
+ gpuUsage: { updatedAt: null, retentionHours: 168, episodes: [] },
66
+ notifications: { email: { enabled: false, configured: false, to: [] } },
67
+ hosts: [
68
+ ...["lab-gpu", "build-node"].map((alias) => ({
69
+ alias,
70
+ hostname: alias === "lab-gpu" ? "gpu-cluster-a01" : "build-node-02",
71
+ reachable: true,
72
+ latencyMs: alias === "lab-gpu" ? 14 : 9,
73
+ inventoryUpdatedAt: new Date().toISOString(),
74
+ error: null,
75
+ processes: [],
76
+ panes: [],
77
+ sessions: [],
78
+ agents: [],
79
+ workloads: [],
80
+ gpus:
81
+ alias === "lab-gpu"
82
+ ? [
83
+ {
84
+ index: 0,
85
+ name: "NVIDIA A100-SXM4-80GB",
86
+ utilization: 94,
87
+ memoryUsed: 68420,
88
+ memoryTotal: 81920,
89
+ },
90
+ {
91
+ index: 1,
92
+ name: "NVIDIA A100-SXM4-80GB",
93
+ utilization: 88,
94
+ memoryUsed: 64110,
95
+ memoryTotal: 81920,
96
+ },
97
+ {
98
+ index: 2,
99
+ name: "NVIDIA A100-SXM4-80GB",
100
+ utilization: 12,
101
+ memoryUsed: 10240,
102
+ memoryTotal: 81920,
103
+ },
104
+ {
105
+ index: 3,
106
+ name: "NVIDIA A100-SXM4-80GB",
107
+ utilization: 0,
108
+ memoryUsed: 480,
109
+ memoryTotal: 81920,
110
+ },
111
+ ]
112
+ : [
113
+ {
114
+ index: 0,
115
+ name: "NVIDIA GeForce RTX 4090",
116
+ utilization: 36,
117
+ memoryUsed: 9840,
118
+ memoryTotal: 24564,
119
+ },
120
+ ],
121
+ })),
122
+ {
123
+ alias: "archive-node",
124
+ hostname: "archive-node",
125
+ reachable: false,
126
+ latencyMs: null,
127
+ inventoryUpdatedAt: null,
128
+ error: "Connection timed out",
129
+ processes: [],
130
+ panes: [],
131
+ sessions: [],
132
+ agents: [],
133
+ workloads: [],
134
+ gpus: [],
135
+ },
136
+ {
137
+ alias: "eval-rack-2",
138
+ hostname: "eval-rack-2",
139
+ reachable: false,
140
+ latencyMs: null,
141
+ inventoryUpdatedAt: null,
142
+ error: "Host offline (maintenance)",
143
+ processes: [],
144
+ panes: [],
145
+ sessions: [],
146
+ agents: [],
147
+ workloads: [],
148
+ gpus: [],
149
+ },
150
+ ],
151
+ };
152
+ snapshot.hosts.unshift({alias: "@local", hostname: "workstation", reachable: true, defaultCwd: "/workspace", kind: "local", latencyMs: 0, error: null, processes: [], panes: [], sessions: [], agents: [], workloads: [], gpus: []});
153
+ snapshot.summary.hosts = 5; snapshot.summary.online = 3;
154
+ const maintenanceFixture = new Map();
155
+ const emailFixture = {
156
+ enabled: false,
157
+ configured: false,
158
+ to: [],
159
+ from: "",
160
+ monitorUrl: "http://localhost:3000/",
161
+ cooldownMinutes: 15,
162
+ triggers: { humanRequests: true, agentCompletion: true, dlcAlerts: true },
163
+ smtp: { host: "", port: 465, secure: true },
164
+ smtpUser: "",
165
+ hasPassword: false,
166
+ credentialSource: null,
167
+ lastSentAt: null,
168
+ lastError: null,
169
+ };
170
+ const adapter = {
171
+ async archive() {},
172
+ async restore() {},
173
+ async launch(task) {
174
+ return { startedAt: Date.now(), id: task.id };
175
+ },
176
+ async poll(task) {
177
+ return Date.now() - task.remote.startedAt < 3500
178
+ ? { status: "running" }
179
+ : {
180
+ status: "completed",
181
+ text: "这是隔离预览的模拟回复,没有调用任何远端 Agent。\n\n可以从项目进展开始,或者在资源页为新任务选择执行主机。",
182
+ };
183
+ },
184
+ };
185
+ const service = new WorkbenchService({
186
+ store,
187
+ snapshot: () => snapshot,
188
+ adapters: { codex: adapter, claude: adapter, dsh: adapter },
189
+ });
190
+ await store.update((state) => {
191
+ state.tasks.push({
192
+ id: "preview-task",
193
+ requestId: "preview-task",
194
+ kind: "task",
195
+ host: "build-node",
196
+ cwd: "/workspace/scope",
197
+ provider: "codex",
198
+ prompt: isEn ? "Refactor backend modules & API routes" : "整理后端模块与接口",
199
+ status: "completed",
200
+ gpuIndices: [],
201
+ gpuCount: 0,
202
+ minMemoryMiB: 0,
203
+ createdAt: new Date().toISOString(),
204
+ updatedAt: new Date().toISOString(),
205
+ remote: { sessionId: "preview-task-session" },
206
+ });
207
+ });
208
+ service.start();
209
+ const sync = createIncrementalSnapshotStore({
210
+ epoch: `scope-isolated-preview-${crypto.randomUUID()}`,
211
+ });
212
+ sync.publish(snapshot);
213
+ const clients = new Set();
214
+ const conversations = createConversationFixture(snapshot, () => {
215
+ snapshot.generatedAt = new Date().toISOString();
216
+ sync.publish(snapshot);
217
+ for (const response of clients)
218
+ response.write(
219
+ `data: ${JSON.stringify({ type: "snapshot-invalidated", ...sync.info() })}\n\n`,
220
+ );
221
+ });
222
+ sync.publish(snapshot);
223
+ const jsonResponse = (response, status, value) => {
224
+ response.writeHead(status, {
225
+ "content-type": "application/json; charset=utf-8",
226
+ });
227
+ response.end(JSON.stringify(value));
228
+ };
229
+ const readJsonBody = async (request) => {
230
+ let text = "";
231
+ for await (const chunk of request) {
232
+ text += chunk;
233
+ if (text.length > 100000) throw new Error("too large");
234
+ }
235
+ return JSON.parse(text || "{}");
236
+ };
237
+ const routes = workbenchRoutes(service, { jsonResponse, readJsonBody });
238
+ const fixturePlugins = new PluginRegistry();
239
+ installPackage(fileURLToPath(new URL("../examples/plugins/hello", import.meta.url)), dir);
240
+ loadExternalPlugins(fixturePlugins, dir);
241
+ fixturePlugins.register(createAliyunDlcPlugin({ stateDirectory: dir, legacyHost: "",
242
+ context: () => ({ readSshConfig: async () => "", sshAliasesForHostname: () => new Set(), getSnapshot: () => ({ hosts: [] }) }),
243
+ notify() {}, onScanComplete: async () => {} }));
244
+ const fixturePluginRoutes = pluginRoutes(fixturePlugins);
245
+ fixturePlugins.start();
246
+ const archives = sessionArchiveService({
247
+ manager: {
248
+ sessionRecords: () => snapshot.appServer.sessions,
249
+ async archiveSession(host, id) {
250
+ const agent = snapshot.hosts
251
+ .find((h) => h.alias === host)
252
+ ?.agents.find((a) => a.rollout.id === id);
253
+ if (agent?.status === "working") throw new Error("会话仍在执行");
254
+ },
255
+ async unarchiveSession() {
256
+ return {};
257
+ },
258
+ async resumeSession() {},
259
+ },
260
+ getState: () => snapshot.management,
261
+ persist: async () => {},
262
+ findAgent: (host, id) =>
263
+ snapshot.hosts
264
+ .find((h) => h.alias === host)
265
+ ?.agents.find((a) => a.rollout.id === id),
266
+ getHost: (host) => snapshot.hosts.find((h) => h.alias === host),
267
+ executable: () => "codex",
268
+ connectionKey: async () => "active",
269
+ restored() {},
270
+ notify() {
271
+ snapshot.generatedAt = new Date().toISOString();
272
+ sync.publish(snapshot);
273
+ for (const response of clients)
274
+ response.write(
275
+ `data: ${JSON.stringify({ type: "snapshot-invalidated", ...sync.info() })}\n\n`,
276
+ );
277
+ },
278
+ });
279
+ const archiveRoute = archiveRoutes(archives, { jsonResponse, readJsonBody });
280
+ const previewHost = process.env.SCOPE_PREVIEW_HOST || "127.0.0.1";
281
+ const previewPort = Number(process.env.SCOPE_PREVIEW_PORT || 3001);
282
+ const ui = await startProductionUiServer({ host: "127.0.0.1", port: 0 });
283
+ const uiPort = ui.address().port;
284
+ const createdDirectories = new Map();
285
+ const fixtureImageBytes = await readFile(new URL("./fixtures/media/convergence.png", import.meta.url));
286
+ const fixtureVideoBytes = await readFile(new URL("./fixtures/media/rollout_demo.mp4", import.meta.url));
287
+ const preview = createServer(async (request, response) => {
288
+ try {
289
+ const url = new URL(request.url, `http://${previewHost}:${previewPort}`);
290
+ if (url.pathname === "/scope-image-api") {
291
+ response.writeHead(200, {
292
+ "content-type": "image/png",
293
+ "content-length": String(fixtureImageBytes.length),
294
+ "cache-control": "private, max-age=60",
295
+ });
296
+ response.end(fixtureImageBytes);
297
+ return;
298
+ }
299
+ if (url.pathname === "/scope-video-api") {
300
+ const total = fixtureVideoBytes.length;
301
+ const rangeHeader = request.headers.range;
302
+ if (rangeHeader && /^bytes=(\d*)-(\d*)$/.test(rangeHeader)) {
303
+ const [, rawStart, rawEnd] = rangeHeader.match(/^bytes=(\d*)-(\d*)$/);
304
+ const start = rawStart ? Number(rawStart) : 0;
305
+ const end = rawEnd ? Math.min(total - 1, Number(rawEnd)) : total - 1;
306
+ const slice = fixtureVideoBytes.subarray(start, end + 1);
307
+ response.writeHead(206, {
308
+ "content-type": "video/mp4",
309
+ "accept-ranges": "bytes",
310
+ "content-range": `bytes ${start}-${end}/${total}`,
311
+ "content-length": String(slice.length),
312
+ });
313
+ response.end(slice);
314
+ return;
315
+ }
316
+ response.writeHead(200, {
317
+ "content-type": "video/mp4",
318
+ "accept-ranges": "bytes",
319
+ "content-length": String(total),
320
+ });
321
+ response.end(fixtureVideoBytes);
322
+ return;
323
+ }
324
+ if (await fixturePluginRoutes(request, response, new URL(url.pathname.replace(/^\/scope-api/, "") + url.search, url.origin))) return;
325
+ if (url.pathname === "/scope-directory-api") {
326
+ const cwd = url.searchParams.get("path") || "/workspace";
327
+ const host = url.searchParams.get("host");
328
+ const names = createdDirectories.get(`${host}:${cwd}`) || [
329
+ "data",
330
+ "experiments",
331
+ ];
332
+ return jsonResponse(response, 200, {
333
+ host,
334
+ cwd,
335
+ parent:
336
+ cwd === "/" ? null : cwd.split("/").slice(0, -1).join("/") || "/",
337
+ directories: names.map((name) => ({
338
+ name,
339
+ path: `${cwd.replace(/\/$/, "")}/${name}`,
340
+ })),
341
+ truncated: false,
342
+ });
343
+ }
344
+ if (url.pathname.startsWith("/scope-api/")) {
345
+ url.pathname = url.pathname.slice("/scope-api".length);
346
+ if (
347
+ url.pathname === "/api/remote/directories" &&
348
+ request.method === "POST"
349
+ ) {
350
+ const { host, parent, name } = await readJsonBody(request);
351
+ const key = `${host}:${parent}`;
352
+ const names = createdDirectories.get(key) || ["data", "experiments"];
353
+ if (names.includes(name))
354
+ return jsonResponse(response, 400, { error: "同名文件或目录已存在" });
355
+ createdDirectories.set(key, [...names, name]);
356
+ return jsonResponse(response, 200, {
357
+ host,
358
+ cwd: `${parent.replace(/\/$/, "")}/${name}`,
359
+ });
360
+ }
361
+ if (url.pathname === "/api/session/attachment" && request.method === "POST") {
362
+ let size = 0;
363
+ for await (const chunk of request) size += chunk.length;
364
+ const name = (url.searchParams.get("name") || "attachment").trim() || "attachment";
365
+ const mimeType = (url.searchParams.get("mimeType") || "application/octet-stream").trim();
366
+ return jsonResponse(response, 201, {
367
+ ok: true,
368
+ attachment: {
369
+ token: crypto.randomUUID(),
370
+ name,
371
+ mimeType,
372
+ kind: mimeType.startsWith("image/") ? "image" : "file",
373
+ size,
374
+ sha256: "preview",
375
+ remotePath: `/workspace/.codex/scope-attachments/${name}`,
376
+ },
377
+ });
378
+ }
379
+ if (nativeConversationFixture(request, response, url, jsonResponse)) return;
380
+ if (await archiveRoute(request, response, url)) return;
381
+ if (await routes(request, response, url)) return;
382
+ if (
383
+ await conversations(request, response, url, jsonResponse, readJsonBody)
384
+ )
385
+ return;
386
+ if (url.pathname === "/api/events") {
387
+ response.writeHead(200, { "content-type": "text/event-stream" });
388
+ response.write('data: {"type":"ready"}\n\n');
389
+ clients.add(response);
390
+ response.on("close", () => clients.delete(response));
391
+ return;
392
+ }
393
+ if (url.pathname === "/api/sync")
394
+ return jsonResponse(
395
+ response,
396
+ 200,
397
+ sync.read({
398
+ clientEpoch: url.searchParams.get("epoch"),
399
+ since: url.searchParams.get("since"),
400
+ }),
401
+ );
402
+ if (url.pathname === "/api/history/cache")
403
+ return jsonResponse(response, 200, {
404
+ cached: true,
405
+ scope: "preview",
406
+ sessions: [],
407
+ hosts: [],
408
+ scannedAt: new Date().toISOString(),
409
+ });
410
+ if (url.pathname === "/api/agents/maintenance") {
411
+ if (request.method === "POST") {
412
+ const body = await readJsonBody(request);
413
+ const job = {id: crypto.randomUUID(), action: body.action, status: "completed", info: {installed: body.action === "check" ? null : "fixture 1.0.0", latest: "1.0.0", supported: body.provider !== "antigravity"}, log: "Isolated fixture: no installation executed"};
414
+ maintenanceFixture.set(body.host + ":" + body.provider, job);
415
+ return jsonResponse(response, 202, {job});
416
+ }
417
+ return jsonResponse(response, 200, {agents: ["codex", "claude", "antigravity", "dsh"].map(provider => ({provider, job: maintenanceFixture.get(url.searchParams.get("host") + ":" + provider) || null}))});
418
+ }
419
+ if (url.pathname === "/api/email/settings") {
420
+ if (request.method === "POST") {
421
+ const body = await readJsonBody(request);
422
+ Object.assign(emailFixture, {
423
+ enabled: Boolean(body.enabled),
424
+ configured: Boolean(body.enabled && body.smtp?.host && body.to),
425
+ to: Array.isArray(body.to) ? body.to : String(body.to || "").split(/[,;\n]+/).map((s) => s.trim()).filter(Boolean),
426
+ from: body.from || "",
427
+ monitorUrl: body.monitorUrl || "http://localhost:3000/",
428
+ cooldownMinutes: Number(body.cooldownMinutes ?? 15),
429
+ triggers: body.triggers || emailFixture.triggers,
430
+ smtp: body.smtp || emailFixture.smtp,
431
+ smtpUser: body.smtpUser ?? emailFixture.smtpUser,
432
+ hasPassword: body.clearCredentials ? false : Boolean(body.smtpPass || emailFixture.hasPassword),
433
+ });
434
+ return jsonResponse(response, 200, { ok: true, settings: emailFixture });
435
+ }
436
+ return jsonResponse(response, 200, emailFixture);
437
+ }
438
+ if (url.pathname === "/api/email/verify" || url.pathname === "/api/email/test") {
439
+ return jsonResponse(response, 200, { ok: true, messageId: "fixture-mail-1", settings: emailFixture });
440
+ }
441
+ if (url.pathname === "/api/remote-bootstrap") {
442
+ const host = request.method === "POST" ? (await readJsonBody(request)).host : url.searchParams.get("host") || "";
443
+ return jsonResponse(response, 200, {
444
+ host,
445
+ checkedAt: new Date().toISOString(),
446
+ lastAction: "inspect",
447
+ report: {
448
+ user: "researcher",
449
+ isRoot: false,
450
+ home: "/home/researcher",
451
+ python3: "Python 3.11.8",
452
+ node: "v22.14.0",
453
+ npm: true,
454
+ tmux: true,
455
+ gpuCount: host === "lab-gpu" ? 2 : 0,
456
+ localBinInPath: true,
457
+ systemdUserAvailable: true,
458
+ clis: {
459
+ codex: { installed: true, executable: "/home/researcher/.local/bin/codex", version: "0.158.0" },
460
+ claude: { installed: true, executable: "/home/researcher/.local/bin/claude", version: "2.1.325" },
461
+ antigravity: { installed: false, executable: null, version: null },
462
+ dsh: { installed: false, executable: null, version: null },
463
+ },
464
+ scopeProtocol: { codex: true, claude: true, antigravity: true },
465
+ scopeNotify: { installed: false, executable: null, daemonActive: false, systemdServiceActive: false, relayReachable: false, queued: 0, lastDeliveredAt: null, codexMcp: false, claudeMcp: false },
466
+ },
467
+ tunnel: { enabled: false, remotePort: 4922, status: "disabled", connectedAt: null, lastError: null },
468
+ relay: { relayListening: false, relayPort: 4822, relayTokenReady: false },
469
+ });
470
+ }
471
+ if (url.pathname === "/api/auth/profiles") {
472
+ const host = url.searchParams.get("host") || "lab-gpu";
473
+ const isLocal = host === "@local";
474
+ return jsonResponse(response, 200, {
475
+ host,
476
+ local: isLocal,
477
+ defaultAuthPresent: true,
478
+ activeProfile: isLocal ? null : "lab-pro",
479
+ currentAccount: {
480
+ type: "chatgpt",
481
+ email: "researcher@example.com",
482
+ planType: "pro",
483
+ },
484
+ runningSessions: isLocal ? 0 : 3,
485
+ profiles: isLocal
486
+ ? []
487
+ : [
488
+ {
489
+ slug: "lab-pro",
490
+ name: "Lab Pro",
491
+ createdAt: new Date(Date.now() - 86400_000 * 14).toISOString(),
492
+ updatedAt: new Date().toISOString(),
493
+ account: { type: "chatgpt", email: "researcher@example.com", planType: "pro" },
494
+ ready: true,
495
+ active: true,
496
+ },
497
+ {
498
+ slug: "backup-plus",
499
+ name: "Backup Plus",
500
+ createdAt: new Date(Date.now() - 86400_000 * 7).toISOString(),
501
+ updatedAt: new Date().toISOString(),
502
+ account: { type: "chatgpt", email: "backup-team@example.com", planType: "plus" },
503
+ ready: true,
504
+ active: false,
505
+ },
506
+ ],
507
+ restartJob: null,
508
+ automaticFailover: null,
509
+ });
510
+ }
511
+ if (url.pathname === "/api/auth/quota") {
512
+ const host = url.searchParams.get("host") || "lab-gpu";
513
+ const nowSec = Math.floor(Date.now() / 1000);
514
+ const currentQuota = {
515
+ planType: "pro",
516
+ primary: { usedPercent: 9, remainingPercent: 91, windowMinutes: 300, resetsAt: nowSec + 11_400, expired: false },
517
+ secondary: { usedPercent: 26, remainingPercent: 74, windowMinutes: 10080, resetsAt: nowSec + 410_000, expired: false },
518
+ credits: null,
519
+ };
520
+ if (url.searchParams.get("all") === "1") {
521
+ return jsonResponse(response, 200, {
522
+ host,
523
+ local: host === "@local",
524
+ fetchedAt: new Date().toISOString(),
525
+ currentAccount: { type: "chatgpt", email: "researcher@example.com", planType: "pro" },
526
+ currentQuota,
527
+ profileQuotas:
528
+ host === "@local"
529
+ ? {}
530
+ : {
531
+ "lab-pro": { quota: currentQuota, error: null },
532
+ "backup-plus": {
533
+ quota: {
534
+ planType: "plus",
535
+ primary: { usedPercent: 18, remainingPercent: 82, windowMinutes: 300, resetsAt: nowSec + 14_200, expired: false },
536
+ secondary: { usedPercent: 12, remainingPercent: 88, windowMinutes: 10080, resetsAt: nowSec + 500_000, expired: false },
537
+ credits: null,
538
+ },
539
+ error: null,
540
+ },
541
+ },
542
+ error: null,
543
+ });
544
+ }
545
+ return jsonResponse(response, 200, {
546
+ host,
547
+ connectionKey: url.searchParams.get("connectionKey") || "active",
548
+ quota: currentQuota,
549
+ source: "app-server",
550
+ error: null,
551
+ });
552
+ }
553
+ if (url.pathname === "/api/auth/providers") {
554
+ const host = url.searchParams.get("host") || "lab-gpu";
555
+ const nowSec = Math.floor(Date.now() / 1000);
556
+ return jsonResponse(response, 200, {
557
+ host,
558
+ local: host === "@local",
559
+ fetchedAt: new Date().toISOString(),
560
+ claude: {
561
+ installed: true,
562
+ executable: "/usr/local/bin/claude",
563
+ loggedIn: true,
564
+ email: "researcher@example.com",
565
+ authMethod: "claude.ai",
566
+ subscriptionType: "max",
567
+ planTier: "max_20x",
568
+ orgName: "Vision Research Lab",
569
+ loginExpiresAt: new Date(Date.now() + 86400_000 * 30).toISOString(),
570
+ quota: {
571
+ planType: "max_20x",
572
+ primary: { usedPercent: 11, remainingPercent: 89, windowMinutes: 300, resetsAt: nowSec + 9_600, expired: false },
573
+ secondary: { usedPercent: 5, remainingPercent: 95, windowMinutes: 10080, resetsAt: nowSec + 518_400, expired: false },
574
+ credits: null,
575
+ },
576
+ quotaError: null,
577
+ error: null,
578
+ },
579
+ antigravity: {
580
+ installed: true,
581
+ executable: "/usr/local/bin/agy",
582
+ loggedIn: true,
583
+ email: "researcher@example.com",
584
+ authMethod: "consumer",
585
+ defaultModel: "Gemini 2.5 Pro (High)",
586
+ useG1Credits: true,
587
+ quota: {
588
+ planType: null,
589
+ primary: { usedPercent: 4, remainingPercent: 96, windowMinutes: 300, resetsAt: nowSec + 12_600, expired: false },
590
+ secondary: { usedPercent: 16, remainingPercent: 84, windowMinutes: 10080, resetsAt: nowSec + 432_000, expired: false },
591
+ credits: { hasCredits: true, unlimited: false, balance: isEn ? "G1 Credits enabled" : "G1 Credits 已启用" },
592
+ groups: [
593
+ {
594
+ name: "Gemini Models",
595
+ primary: { usedPercent: 4, remainingPercent: 96, windowMinutes: 300, resetsAt: nowSec + 12_600, expired: false },
596
+ secondary: { usedPercent: 16, remainingPercent: 84, windowMinutes: 10080, resetsAt: nowSec + 432_000, expired: false },
597
+ },
598
+ {
599
+ name: "Claude and GPT models",
600
+ primary: { usedPercent: 0, remainingPercent: 100, windowMinutes: 300, resetsAt: nowSec + 16_200, expired: false },
601
+ secondary: { usedPercent: 7, remainingPercent: 93, windowMinutes: 10080, resetsAt: nowSec + 360_000, expired: false },
602
+ },
603
+ ],
604
+ },
605
+ quotaError: null,
606
+ error: null,
607
+ },
608
+ });
609
+ }
610
+ if (url.pathname === "/api/models")
611
+ return jsonResponse(response, 200, {
612
+ models: [
613
+ {
614
+ id: "o3",
615
+ model: "o3",
616
+ displayName: "o3",
617
+ supportedReasoningEfforts: ["medium", "high", "xhigh"],
618
+ defaultReasoningEffort: "high",
619
+ },
620
+ {
621
+ id: "gpt-5-codex",
622
+ model: "gpt-5-codex",
623
+ displayName: "GPT-5 Codex",
624
+ supportedReasoningEfforts: ["medium", "high", "xhigh"],
625
+ defaultReasoningEffort: "high",
626
+ },
627
+ ],
628
+ });
629
+ return jsonResponse(response, 200, {});
630
+ }
631
+ const upstream = await fetch(`http://127.0.0.1:${uiPort}${request.url}`);
632
+ const outHeaders = Object.fromEntries(
633
+ [...upstream.headers].filter(
634
+ ([key]) => !["content-encoding", "content-length"].includes(key),
635
+ ),
636
+ );
637
+ const contentType = upstream.headers.get("content-type") || "";
638
+ if (contentType.includes("text/html")) {
639
+ const html = (await upstream.text()).replace(
640
+ /<head(\b[^>]*)>/i,
641
+ '<head$1><meta name="scope-bridge-url" content="/scope-api">',
642
+ );
643
+ response.writeHead(upstream.status, outHeaders);
644
+ response.end(html);
645
+ return;
646
+ }
647
+ response.writeHead(upstream.status, outHeaders);
648
+ response.end(Buffer.from(await upstream.arrayBuffer()));
649
+ } catch (error) {
650
+ jsonResponse(response, 500, { error: error.message });
651
+ }
652
+ });
653
+ preview.listen(previewPort, previewHost, () =>
654
+ console.log(
655
+ `Isolated preview: http://${previewHost}:${previewPort} (synthetic data, no SSH; temporary state: ` +
656
+ dir +
657
+ ")",
658
+ ),
659
+ );
660
+ function stop() {
661
+ fixturePlugins.stop();
662
+ service.stop();
663
+ preview.closeAllConnections();
664
+ preview.close();
665
+ ui.closeAllConnections();
666
+ ui.close(() => process.exit(0));
667
+ }
668
+ process.once("SIGINT", stop);
669
+ process.once("SIGTERM", stop);