forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
3785 lines (3543 loc) · 130 KB
/
server.ts
File metadata and controls
3785 lines (3543 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
import express from 'express';
import multer from 'multer';
import { execFile, spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import { composeSystemPrompt } from './prompts/system.js';
import { createCommandInvocation } from '@open-design/platform';
import {
checkPromptArgvBudget,
checkWindowsCmdShimCommandLineBudget,
checkWindowsDirectExeCommandLineBudget,
detectAgents,
getAgentDef,
isKnownModel,
resolveAgentBin,
sanitizeCustomModel,
spawnEnvForAgent,
} from './agents.js';
import { findSkillById, listSkills } from './skills.js';
import { validateLinkedDirs } from './linked-dirs.js';
import { listCodexPets, readCodexPetSpritesheet } from './codex-pets.js';
import { syncCommunityPets } from './community-pets-sync.js';
import { listDesignSystems, readDesignSystem } from './design-systems.js';
import { attachAcpSession } from './acp.js';
import { attachPiRpcSession } from './pi-rpc.js';
import { createClaudeStreamHandler } from './claude-stream.js';
import { createCopilotStreamHandler } from './copilot-stream.js';
import { createJsonEventStreamHandler } from './json-event-stream.js';
import { subscribe as subscribeFileEvents } from './project-watchers.js';
import { renderDesignSystemPreview } from './design-system-preview.js';
import { renderDesignSystemShowcase } from './design-system-showcase.js';
import { createChatRunService } from './runs.js';
import { importClaudeDesignZip } from './claude-design-import.js';
import { listPromptTemplates, readPromptTemplate } from './prompt-templates.js';
import { buildDocumentPreview } from './document-preview.js';
import { lintArtifact, renderFindingsForAgent } from './lint-artifact.js';
import { loadCraftSections } from './craft.js';
import { stageActiveSkill } from './cwd-aliases.js';
import { generateMedia } from './media.js';
import {
AUDIO_DURATIONS_SEC,
AUDIO_MODELS_BY_KIND,
IMAGE_MODELS,
MEDIA_ASPECTS,
MEDIA_PROVIDERS,
VIDEO_LENGTHS_SEC,
VIDEO_MODELS,
} from './media-models.js';
import { readMaskedConfig, writeConfig } from './media-config.js';
import { readAppConfig, writeAppConfig } from './app-config.js';
import {
buildProjectArchive,
buildBatchArchive,
decodeMultipartFilename,
deleteProjectFile,
ensureProject,
listFiles,
mimeFor,
projectDir,
readProjectFile,
removeProjectDir,
sanitizeName,
searchProjectFiles,
writeProjectFile,
} from './projects.js';
import { validateArtifactManifestInput } from './artifact-manifest.js';
import { readCurrentAppVersionInfo } from './app-version.js';
import {
deleteConversation,
deletePreviewComment,
deleteProject as dbDeleteProject,
deleteTemplate,
getConversation,
getDeployment,
getDeploymentById,
getProject,
getTemplate,
insertConversation,
insertProject,
insertTemplate,
listProjectsAwaitingInput,
listConversations,
listDeployments,
listLatestProjectRunStatuses,
listMessages,
listPreviewComments,
listProjects,
listTabs,
listTemplates,
openDatabase,
setTabs,
updateConversation,
updatePreviewCommentStatus,
updateProject,
upsertDeployment,
upsertMessage,
upsertPreviewComment,
} from './db.js';
import {
buildDeployFileSet,
checkDeploymentUrl,
DeployError,
deployToVercel,
prepareDeployPreflight,
publicDeployConfig,
readVercelConfig,
VERCEL_PROVIDER_ID,
writeVercelConfig,
} from './deploy.js';
/** @typedef {import('@open-design/contracts').ApiErrorCode} ApiErrorCode */
/** @typedef {import('@open-design/contracts').ApiError} ApiError */
/** @typedef {import('@open-design/contracts').ApiErrorResponse} ApiErrorResponse */
/** @typedef {import('@open-design/contracts').ChatRequest} ChatRequest */
/** @typedef {import('@open-design/contracts').ChatSseEvent} ChatSseEvent */
/** @typedef {import('@open-design/contracts').ProxyStreamRequest} ProxyStreamRequest */
/** @typedef {import('@open-design/contracts').ProxySseEvent} ProxySseEvent */
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export function resolveProjectRoot(moduleDir: string): string {
const base = path.basename(moduleDir);
const daemonDir =
base === 'dist' || base === 'src' ? path.dirname(moduleDir) : moduleDir;
return path.resolve(daemonDir, '../..');
}
const PROJECT_ROOT = resolveProjectRoot(__dirname);
const RESOURCE_ROOT_ENV = 'OD_RESOURCE_ROOT';
export function normalizeCommentAttachments(input) {
if (!Array.isArray(input)) return [];
return input
.map((raw, index) => {
if (!raw || typeof raw !== 'object') return null;
const filePath = cleanString(raw.filePath);
const elementId = cleanString(raw.elementId);
const selector = cleanString(raw.selector);
const label = cleanString(raw.label);
const comment = cleanString(raw.comment);
if (!filePath || !elementId || !selector || !comment) return null;
return {
id: cleanString(raw.id) || `comment-${index + 1}`,
order: Number.isFinite(raw.order)
? Math.max(1, Math.round(raw.order))
: index + 1,
filePath,
elementId,
selector,
label,
comment,
currentText: compactString(raw.currentText, 160),
pagePosition: normalizeAttachmentPosition(raw.pagePosition),
htmlHint: compactString(raw.htmlHint, 180),
};
})
.filter(Boolean)
.sort((a, b) => a.order - b.order);
}
export function renderCommentAttachmentHint(commentAttachments) {
if (!commentAttachments.length) return '';
const lines = [
'',
'',
'<attached-preview-comments>',
'Scope: edit the target element by default. Use the smallest necessary parent wrapper only if the target cannot satisfy the comment. Preserve stable ids and unrelated siblings.',
];
for (const item of commentAttachments) {
lines.push(
'',
`${item.order}. ${item.elementId}`,
`file: ${item.filePath}`,
`selector: ${item.selector}`,
`label: ${item.label || '(unlabeled)'}`,
`position: ${formatAttachmentPosition(item.pagePosition)}`,
`currentText: ${item.currentText || '(empty)'}`,
`htmlHint: ${item.htmlHint || '(none)'}`,
`comment: ${item.comment}`,
);
}
lines.push('</attached-preview-comments>');
return lines.join('\n');
}
function cleanString(value) {
return typeof value === 'string' ? value.trim() : '';
}
function compactString(value, max) {
const text = cleanString(value).replace(/\s+/g, ' ');
return text.length > max ? `${text.slice(0, max - 3)}...` : text;
}
function normalizeAttachmentPosition(input) {
const value = input && typeof input === 'object' ? input : {};
return {
x: finiteAttachmentNumber(value.x),
y: finiteAttachmentNumber(value.y),
width: finiteAttachmentNumber(value.width),
height: finiteAttachmentNumber(value.height),
};
}
function finiteAttachmentNumber(value) {
return Number.isFinite(value) ? Math.round(value) : 0;
}
function formatAttachmentPosition(position) {
return `x=${position.x}, y=${position.y}, width=${position.width}, height=${position.height}`;
}
function isPathWithin(base, target) {
const relativePath = path.relative(path.resolve(base), path.resolve(target));
return (
relativePath === '' ||
(relativePath.length > 0 &&
!relativePath.startsWith('..') &&
!path.isAbsolute(relativePath))
);
}
function resolveProcessResourcesPath() {
if (
typeof process.resourcesPath === 'string' &&
process.resourcesPath.length > 0
) {
return process.resourcesPath;
}
// Packaged daemon sidecars run under the bundled Node binary rather than the
// Electron root process, so `process.resourcesPath` is unavailable there.
// Infer the macOS app Resources directory from that bundled Node path.
const resourcesMarker = `${path.sep}Contents${path.sep}Resources${path.sep}`;
const markerIndex = process.execPath.indexOf(resourcesMarker);
if (markerIndex !== -1) {
return process.execPath.slice(0, markerIndex + resourcesMarker.length - 1);
}
const normalizedExecPath = process.execPath.toLowerCase();
const windowsResourceBinMarker =
`${path.sep}resources${path.sep}open-design${path.sep}bin${path.sep}`.toLowerCase();
const windowsMarkerIndex = normalizedExecPath.indexOf(
windowsResourceBinMarker,
);
if (windowsMarkerIndex !== -1) {
return process.execPath.slice(
0,
windowsMarkerIndex + `${path.sep}resources`.length,
);
}
return null;
}
export function resolveDaemonResourceRoot({
configured = process.env[RESOURCE_ROOT_ENV],
safeBases = [PROJECT_ROOT, resolveProcessResourcesPath()],
} = {}) {
if (!configured || configured.length === 0) return null;
const resolved = path.resolve(configured);
const normalizedSafeBases = safeBases
.filter((base) => typeof base === 'string' && base.length > 0)
.map((base) => path.resolve(base));
if (!normalizedSafeBases.some((base) => isPathWithin(base, resolved))) {
throw new Error(
`${RESOURCE_ROOT_ENV} must be under the workspace root or app resources path`,
);
}
return resolved;
}
function resolveDaemonResourceDir(resourceRoot, segment, fallback) {
return resourceRoot ? path.join(resourceRoot, segment) : fallback;
}
const DAEMON_RESOURCE_ROOT = resolveDaemonResourceRoot();
// Built web app lives in `out/` — that's where Next.js writes the static
// export configured in next.config.ts. The folder name used to be `dist/`
// when this project shipped with Vite; the daemon serves whatever the
// frontend toolchain emits, no further config needed.
const STATIC_DIR = path.join(PROJECT_ROOT, 'apps', 'web', 'out');
const OD_BIN = path.join(PROJECT_ROOT, 'apps', 'daemon', 'dist', 'cli.js');
const SKILLS_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'skills',
path.join(PROJECT_ROOT, 'skills'),
);
const DESIGN_SYSTEMS_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'design-systems',
path.join(PROJECT_ROOT, 'design-systems'),
);
const CRAFT_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'craft',
path.join(PROJECT_ROOT, 'craft'),
);
const FRAMES_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'frames',
path.join(PROJECT_ROOT, 'assets', 'frames'),
);
// Curated pets baked into the repo via `scripts/bake-community-pets.ts`.
// `listCodexPets` scans this in addition to `~/.codex/pets/` so the
// "Recently hatched" grid is non-empty out-of-the-box and users do not
// need to hit the "Download community pets" button to try a few pets.
const BUNDLED_PETS_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'community-pets',
path.join(PROJECT_ROOT, 'assets', 'community-pets'),
);
const PROMPT_TEMPLATES_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'prompt-templates',
path.join(PROJECT_ROOT, 'prompt-templates'),
);
export function resolveDataDir(raw, projectRoot) {
if (!raw) return path.join(projectRoot, '.od');
const expanded = raw.startsWith('~/')
? path.join(os.homedir(), raw.slice(2))
: raw;
const resolved = path.isAbsolute(expanded)
? expanded
: path.resolve(projectRoot, expanded);
try {
fs.mkdirSync(resolved, { recursive: true });
fs.accessSync(resolved, fs.constants.W_OK);
} catch (err) {
const e = err;
throw new Error(
`OD_DATA_DIR "${resolved}" is not writable: ${e.message}`,
);
}
return resolved;
}
const RUNTIME_DATA_DIR = resolveDataDir(process.env.OD_DATA_DIR, PROJECT_ROOT);
const ARTIFACTS_DIR = path.join(RUNTIME_DATA_DIR, 'artifacts');
const PROJECTS_DIR = path.join(RUNTIME_DATA_DIR, 'projects');
fs.mkdirSync(PROJECTS_DIR, { recursive: true });
export const SSE_KEEPALIVE_INTERVAL_MS = 25_000;
export function normalizeProjectDisplayStatus(status) {
return status === 'starting' || status === 'queued' ? 'running' : status;
}
export function composeProjectDisplayStatus(
baseStatus,
awaitingInputProjects,
projectId,
) {
if (
baseStatus.value === 'succeeded' &&
awaitingInputProjects.has(projectId)
) {
return { ...baseStatus, value: 'awaiting_input' };
}
return {
...baseStatus,
value: normalizeProjectDisplayStatus(baseStatus.value),
};
}
/**
* @param {ApiErrorCode} code
* @param {string} message
* @param {Omit<ApiError, 'code' | 'message'>} [init]
* @returns {ApiError}
*/
export function createCompatApiError(code, message, init = {}) {
return { code, message, ...init };
}
/**
* @param {ApiErrorCode} code
* @param {string} message
* @param {Omit<ApiError, 'code' | 'message'>} [init]
* @returns {ApiErrorResponse}
*/
export function createCompatApiErrorResponse(code, message, init = {}) {
return { error: createCompatApiError(code, message, init) };
}
/**
* @param {import('express').Response} res
* @param {number} status
* @param {ApiErrorCode} code
* @param {string} message
* @param {Omit<ApiError, 'code' | 'message'>} [init]
*/
function sendApiError(res, status, code, message, init = {}) {
return res
.status(status)
.json(createCompatApiErrorResponse(code, message, init));
}
// Filename slug for the Content-Disposition header on archive downloads.
// Browsers reject quotes and control bytes; we keep Unicode letters/digits
// so a project name with non-ASCII characters (e.g. "café-design")
// survives instead of becoming a row of underscores.
function sanitizeArchiveFilename(raw) {
const cleaned = String(raw ?? '')
.replace(/[\\/:*?"<>|]/g, '_')
.replace(/[\u0000-\u001f\u007f]/g, '')
.replace(/\s+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 80);
return cleaned;
}
function openNativeFolderDialog() {
return new Promise((resolve) => {
const platform = process.platform;
if (platform === 'darwin') {
execFile(
'osascript',
['-e', 'POSIX path of (choose folder with prompt "Select a code folder to link")'],
{ timeout: 120_000 },
(err, stdout) => {
if (err) return resolve(null);
const p = stdout.trim().replace(/\/$/, '');
resolve(p || null);
},
);
} else if (platform === 'linux') {
execFile(
'zenity',
['--file-selection', '--directory', '--title=Select a code folder to link'],
{ timeout: 120_000 },
(err, stdout) => {
if (err) return resolve(null);
const p = stdout.trim();
resolve(p || null);
},
);
} else if (platform === 'win32') {
const ps = "Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = 'Select a code folder to link'; if ($d.ShowDialog() -eq 'OK') { $d.SelectedPath }";
execFile('powershell.exe', ['-NoProfile', '-Command', ps], { timeout: 120_000 }, (err, stdout) => {
if (err) return resolve(null);
const p = stdout.trim();
resolve(p || null);
});
} else {
resolve(null);
}
});
}
/**
* @param {ApiErrorCode} code
* @param {string} message
* @param {Omit<ApiError, 'code' | 'message'>} [init]
*/
function createSseErrorPayload(code, message, init = {}) {
return { message, error: createCompatApiError(code, message, init) };
}
const UPLOAD_DIR = path.join(os.tmpdir(), 'od-uploads');
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
fs.mkdirSync(ARTIFACTS_DIR, { recursive: true });
const upload = multer({
storage: multer.diskStorage({
destination: UPLOAD_DIR,
filename: (_req, file, cb) => {
file.originalname = decodeMultipartFilename(file.originalname);
const safe = sanitizeName(file.originalname);
cb(
null,
`${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${safe}`,
);
},
}),
limits: { fileSize: 20 * 1024 * 1024 },
});
const importUpload = multer({
storage: multer.diskStorage({
destination: UPLOAD_DIR,
filename: (_req, file, cb) => {
file.originalname = decodeMultipartFilename(file.originalname);
const safe = sanitizeName(file.originalname);
cb(
null,
`${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${safe}`,
);
},
}),
limits: { fileSize: 100 * 1024 * 1024 },
});
// Project-scoped multi-file upload. Lands files directly in the project
// folder (flat — same shape FileWorkspace expects), so the composer's
// pasted/dropped/picked images become referenceable filenames the agent
// can Read or @-mention without any cross-folder gymnastics.
const projectUpload = multer({
storage: multer.diskStorage({
destination: async (req, _file, cb) => {
try {
const dir = await ensureProject(PROJECTS_DIR, req.params.id);
cb(null, dir);
} catch (err) {
cb(err, '');
}
},
filename: (_req, file, cb) => {
// multer@1 hands us latin1-decoded multipart filenames; restore the
// original UTF-8 so the response (and the on-disk name) preserves
// non-ASCII characters instead of mangling them. Then run the
// shared sanitiser and prepend a base36 timestamp so multiple
// uploads with the same original name don't clobber each other.
file.originalname = decodeMultipartFilename(file.originalname);
const safe = sanitizeName(file.originalname);
cb(null, `${Date.now().toString(36)}-${safe}`);
},
}),
limits: { fileSize: 200 * 1024 * 1024 }, // 200MB — covers the largest design assets we expect (PPTX/PDF/raw images)
});
function handleProjectUpload(req, res, next) {
projectUpload.array('files', 12)(req, res, (err) => {
if (err) {
return sendMulterError(res, err);
}
next();
});
}
function sendMulterError(res, err) {
if (err instanceof multer.MulterError) {
const code = err.code || 'UPLOAD_ERROR';
const statusByCode = {
LIMIT_FILE_SIZE: 413,
LIMIT_FILE_COUNT: 400,
LIMIT_UNEXPECTED_FILE: 400,
LIMIT_PART_COUNT: 400,
LIMIT_FIELD_KEY: 400,
LIMIT_FIELD_VALUE: 400,
LIMIT_FIELD_COUNT: 400,
};
const errorByCode = {
LIMIT_FILE_SIZE: 'file too large',
LIMIT_FILE_COUNT: 'too many files',
LIMIT_UNEXPECTED_FILE: 'unexpected file field',
LIMIT_PART_COUNT: 'too many form parts',
LIMIT_FIELD_KEY: 'field name too long',
LIMIT_FIELD_VALUE: 'field value too long',
LIMIT_FIELD_COUNT: 'too many form fields',
};
const status = statusByCode[code] ?? 400;
const message = errorByCode[code] ?? 'upload failed';
return sendApiError(
res,
status,
code === 'LIMIT_FILE_SIZE' ? 'PAYLOAD_TOO_LARGE' : 'BAD_REQUEST',
message,
{ details: { legacyCode: code } },
);
}
if (err) {
return sendApiError(res, 500, 'INTERNAL_ERROR', 'upload failed');
}
return sendApiError(res, 500, 'INTERNAL_ERROR', 'upload failed');
}
const mediaTasks = new Map();
const TASK_TTL_AFTER_DONE_MS = 10 * 60 * 1000;
function createMediaTask(taskId, projectId, info = {}) {
const task = {
id: taskId,
projectId,
status: 'queued',
surface: info.surface,
model: info.model,
progress: [],
file: null,
error: null,
startedAt: Date.now(),
endedAt: null,
waiters: new Set(),
};
mediaTasks.set(taskId, task);
return task;
}
function appendTaskProgress(task, line) {
task.progress.push(line);
notifyTaskWaiters(task);
}
function notifyTaskWaiters(task) {
const wakers = Array.from(task.waiters);
for (const w of wakers) {
try {
w();
} catch {
// Never let one bad waiter block the rest.
}
}
if (
(task.status === 'done' || task.status === 'failed') &&
!task._gcScheduled
) {
task._gcScheduled = true;
setTimeout(() => {
if (task.waiters.size === 0) mediaTasks.delete(task.id);
}, TASK_TTL_AFTER_DONE_MS).unref?.();
}
}
export function createSseResponse(
res,
{ keepAliveIntervalMs = SSE_KEEPALIVE_INTERVAL_MS } = {},
) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders?.();
const canWrite = () => !res.destroyed && !res.writableEnded;
const writeKeepAlive = () => {
if (canWrite()) {
res.write(': keepalive\n\n');
return true;
}
return false;
};
let heartbeat = null;
if (keepAliveIntervalMs > 0) {
heartbeat = setInterval(writeKeepAlive, keepAliveIntervalMs);
heartbeat.unref?.();
}
const cleanup = () => {
if (heartbeat) {
clearInterval(heartbeat);
heartbeat = null;
}
};
res.on('close', cleanup);
res.on('finish', cleanup);
return {
/** @param {ChatSseEvent['event'] | ProxySseEvent['event'] | string} event */
send(event, data, id = null) {
if (!canWrite()) return false;
if (id !== null && id !== undefined) res.write(`id: ${id}\n`);
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
return true;
},
writeKeepAlive,
cleanup,
end() {
cleanup();
if (canWrite()) {
res.end();
}
},
};
}
export async function startServer({ port = 7456, host = process.env.OD_BIND_HOST || '127.0.0.1', returnServer = false } = {}) {
let resolvedPort = port;
const app = express();
app.use(express.json({ limit: '4mb' }));
// Build the set of allowed browser origins for the current bind config.
// Shared by the global origin middleware and isLocalSameOrigin() so
// both use the same policy (loopback + explicit bind host, HTTP + HTTPS,
// OD_WEB_PORT support).
function buildAllowedOrigins() {
const ports = [resolvedPort];
const webPort = Number(process.env.OD_WEB_PORT);
if (webPort && webPort !== resolvedPort) ports.push(webPort);
const schemes = ['http', 'https'];
const loopbackHosts = ['127.0.0.1', 'localhost', '[::1]'];
return new Set(
ports.flatMap((p) => [
...schemes.flatMap((s) => loopbackHosts.map((h) => `${s}://${h}:${p}`)),
// When bound to a specific non-loopback address (e.g. Tailscale,
// LAN IP, or 0.0.0.0), allow browser requests from that address
// too so the documented --host escape hatch remains usable.
...schemes.map((s) => `${s}://${host}:${p}`),
]),
);
}
// Routes that serve content to sandboxed iframes (Origin: null) for
// read-only purposes. All other /api routes reject Origin: null.
const _NULL_ORIGIN_SAFE_GET_RE =
/^\/projects\/[^/]+\/raw\/|^\/codex-pets\/[^/]+\/spritesheet$/;
// Reject cross-origin requests to API endpoints.
// Health/version remain open for monitoring probes.
// Non-browser clients (no Origin header) are always allowed.
app.use('/api', (req, res, next) => {
const origin = req.headers.origin;
// Non-browser client → allow.
if (origin == null || origin === '') return next();
// Origin: null (sandboxed iframes). Only allowed for safe, read-only
// routes that set their own CORS headers for canvas drawing.
if (origin === 'null') {
const isSafeReadOnly =
req.method === 'GET' && _NULL_ORIGIN_SAFE_GET_RE.test(req.path);
if (!isSafeReadOnly) {
return res.status(403).json({ error: 'Origin: null not allowed for this route' });
}
return next();
}
// Fail-closed: block all browser origins until port is resolved.
if (!resolvedPort) {
return res.status(403).json({ error: 'Server initializing' });
}
if (!buildAllowedOrigins().has(String(origin))) {
return res.status(403).json({ error: 'Cross-origin requests are not allowed' });
}
next();
});
const db = openDatabase(PROJECT_ROOT, { dataDir: RUNTIME_DATA_DIR });
if (process.env.OD_CODEX_DISABLE_PLUGINS === '1') {
console.log('[od] Codex plugins disabled via OD_CODEX_DISABLE_PLUGINS=1');
}
// Warm agent-capability probes (e.g. whether the installed Claude Code
// build advertises --include-partial-messages) so the first /api/chat
// hits a populated cache even if /api/agents hasn't been called yet.
void detectAgents().catch(() => {});
if (fs.existsSync(STATIC_DIR)) {
app.use(express.static(STATIC_DIR));
}
app.get('/api/health', async (_req, res) => {
const versionInfo = await readCurrentAppVersionInfo();
res.json({ ok: true, version: versionInfo.version });
});
app.get('/api/version', async (_req, res) => {
const version = await readCurrentAppVersionInfo();
res.json({ version });
});
// ---- Projects (DB-backed) -------------------------------------------------
// Soft "what is the user looking at right now in Open Design?" channel. The
// web UI POSTs the current project + file on every route change;
// the MCP surface reads it so a coding agent in another repo can
// resolve "the design I have open" without the user typing the
// project id. In-memory only - daemon restart clears it.
/** @type {{ projectId: string; fileName: string | null; ts: number } | null} */
let activeContext = null;
const ACTIVE_CONTEXT_TTL_MS = 5 * 60 * 1000;
// Active context is private to the local machine. The daemon binds
// 0.0.0.0 by default, so without an origin check a peer on the LAN
// could read what the user is currently looking at (GET) or spoof
// it to redirect MCP fallbacks (POST). The web proxies same-origin
// and the MCP runs in-process via 127.0.0.1, so both legitimate
// callers pass the check.
app.post('/api/active', (req, res) => {
if (!isLocalSameOrigin(req, resolvedPort)) {
return res.status(403).json({ error: 'cross-origin request rejected' });
}
try {
const body = req.body || {};
if (body.active === false) {
activeContext = null;
res.json({ active: false });
return;
}
const projectId = typeof body.projectId === 'string' ? body.projectId : '';
if (!projectId) {
sendApiError(res, 400, 'BAD_REQUEST', 'projectId is required');
return;
}
const fileName =
typeof body.fileName === 'string' && body.fileName.length > 0
? body.fileName
: null;
activeContext = { projectId, fileName, ts: Date.now() };
res.json({ active: true, ...activeContext });
} catch (err) {
sendApiError(res, 400, 'BAD_REQUEST', String(err));
}
});
app.get('/api/active', (req, res) => {
if (!isLocalSameOrigin(req, resolvedPort)) {
return res.status(403).json({ error: 'cross-origin request rejected' });
}
if (!activeContext || Date.now() - activeContext.ts > ACTIVE_CONTEXT_TTL_MS) {
activeContext = null;
res.json({ active: false });
return;
}
const project = getProject(db, activeContext.projectId);
res.json({
active: true,
projectId: activeContext.projectId,
projectName: project?.name ?? null,
fileName: activeContext.fileName,
ts: activeContext.ts,
ageMs: Date.now() - activeContext.ts,
});
});
// Surfaces the absolute paths to `node` + `apps/daemon/dist/cli.js`
// so the Settings → MCP server panel can render snippets that work
// even when `od` isn't on the user's PATH (the common case for
// source clones - and macOS/Linux ship a /usr/bin/od octal-dump
// tool that shadows ours anyway). Computed from import.meta.url so
// both src/ (tsx dev) and dist/ (built) launches resolve to the
// same dist/cli.js path. Cached for 5s because the panel pings on
// every open and the path lookup + two existsSync calls are cheap
// but not free, and these paths cannot change without a daemon
// restart anyway.
const INSTALL_INFO_TTL_MS = 5000;
let installInfoCache: { t: number; payload: object } | null = null;
app.get('/api/mcp/install-info', (req, res) => {
if (!isLocalSameOrigin(req, resolvedPort)) {
return res.status(403).json({ error: 'cross-origin request rejected' });
}
const now = Date.now();
if (installInfoCache && now - installInfoCache.t < INSTALL_INFO_TTL_MS) {
return res.json(installInfoCache.payload);
}
let cliPath;
try {
cliPath = fileURLToPath(new URL('../dist/cli.js', import.meta.url));
} catch (err) {
return sendApiError(res, 500, 'CLI_RESOLVE_FAILED', String(err));
}
const cliExists = fs.existsSync(cliPath);
// process.execPath is the absolute path to the node binary that
// is running the daemon RIGHT NOW. We prefer it over bare `node`
// because IDE-spawned MCP clients inherit a minimal PATH from the
// OS launcher (Spotlight, Dock, etc.) that often does not see
// user-level node installs (nvm, fnm, asdf). On rare occasions
// (uninstall mid-session, exotic embeds) the path may not exist
// by the time the user copies the snippet; catch that and warn.
const nodeExists = fs.existsSync(process.execPath);
const hints: string[] = [];
if (!cliExists) {
hints.push(
'apps/daemon/dist/cli.js is missing. Run `pnpm --filter @open-design/daemon build` (or just `pnpm build`) and refresh.',
);
}
if (!nodeExists) {
hints.push(
`Node binary at ${process.execPath} no longer exists. Reinstall Node and restart the daemon.`,
);
}
const payload = {
command: process.execPath,
args: [cliPath, 'mcp', '--daemon-url', `http://127.0.0.1:${resolvedPort}`],
daemonUrl: `http://127.0.0.1:${resolvedPort}`,
// Surface platform so the install panel can localize path hints
// (~/.cursor vs %USERPROFILE%\.cursor) and keyboard shortcuts
// (Cmd vs Ctrl). One of 'darwin' | 'linux' | 'win32' in
// practice; the panel falls back to POSIX wording for anything
// else.
platform: process.platform,
cliExists,
nodeExists,
buildHint: hints.length ? hints.join(' ') : null,
};
installInfoCache = { t: now, payload };
res.json(payload);
});
app.get('/api/projects', (_req, res) => {
try {
const latestRunStatuses = listLatestProjectRunStatuses(db);
const awaitingInputProjects = listProjectsAwaitingInput(db);
const activeRunStatuses = new Map();
for (const run of design.runs.list()) {
if (!run.projectId) continue;
const runStatus = projectStatusFromRun(run);
if (design.runs.isTerminal(run.status)) {
const existing = latestRunStatuses.get(run.projectId);
if (!existing || run.updatedAt > (existing.updatedAt ?? 0)) {
latestRunStatuses.set(run.projectId, runStatus);
}
} else {
const existing = activeRunStatuses.get(run.projectId);
if (!existing || run.updatedAt > (existing.updatedAt ?? 0)) {
activeRunStatuses.set(run.projectId, runStatus);
}
}
}
/** @type {import('@open-design/contracts').ProjectsResponse} */
const body = {
projects: listProjects(db).map((project) => ({
...project,
status: composeProjectDisplayStatus(
activeRunStatuses.get(project.id) ??
latestRunStatuses.get(project.id) ?? { value: 'not_started' },
awaitingInputProjects,
project.id,
),
})),
};
res.json(body);
} catch (err) {
sendApiError(res, 500, 'INTERNAL_ERROR', String(err));
}
});
function projectStatusFromRun(run) {
return {
value: normalizeProjectDisplayStatus(run.status),
updatedAt: run.updatedAt,
runId: run.id,
};
}
app.post('/api/projects', async (req, res) => {
try {
const { id, name, skillId, designSystemId, pendingPrompt, metadata } =
req.body || {};
if (typeof id !== 'string' || !/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
return sendApiError(res, 400, 'BAD_REQUEST', 'invalid project id');
}
if (typeof name !== 'string' || !name.trim()) {
return sendApiError(res, 400, 'BAD_REQUEST', 'name required');
}
const now = Date.now();
const project = insertProject(db, {
id,
name: name.trim(),
skillId: skillId ?? null,
designSystemId: designSystemId ?? null,
pendingPrompt: pendingPrompt || null,
metadata:
metadata && typeof metadata === 'object'
? {
...metadata,
...(Array.isArray(metadata.linkedDirs)
? (() => {
const v = validateLinkedDirs(metadata.linkedDirs);
return v.error ? {} : { linkedDirs: v.dirs };
})()
: {}),
}
: null,
createdAt: now,
updatedAt: now,
});
// Seed a default conversation so the UI always has somewhere to write.
const cid = randomId();
insertConversation(db, {
id: cid,
projectId: id,
title: null,
createdAt: now,
updatedAt: now,
});
// For "from template" projects, seed the chosen template's snapshot
// HTML into the new project folder so the agent can Read/edit files
// on disk (the system prompt also embeds them, but a real on-disk
// copy lets the agent treat them as the project's working state).
if (
metadata &&
typeof metadata === 'object' &&
metadata.kind === 'template' &&
typeof metadata.templateId === 'string'
) {
const tpl = getTemplate(db, metadata.templateId);
if (tpl && Array.isArray(tpl.files) && tpl.files.length > 0) {
await ensureProject(PROJECTS_DIR, id);
for (const f of tpl.files) {
if (
!f ||
typeof f.name !== 'string' ||
typeof f.content !== 'string'
) {
continue;
}
try {
await writeProjectFile(