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
5034 lines (4778 loc) · 187 KB
/
Copy pathserver.ts
File metadata and controls
5034 lines (4778 loc) · 187 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 type { DesktopExportPdfInput, DesktopExportPdfResult } from '@open-design/sidecar-proto';
import express from 'express';
import multer from 'multer';
import { execFile, spawn } from 'node:child_process';
import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import net from 'node:net';
import {
composeSystemPrompt,
renderCodexImagegenOverride,
shouldRenderCodexImagegenOverride,
} from './prompts/system.js';
import { expandHomePrefix, resolveProjectRelativePath } from './home-expansion.js';
import { createCommandInvocation } from '@open-design/platform';
import { SIDECAR_DEFAULTS, SIDECAR_ENV } from '@open-design/sidecar-proto';
import {
buildLiveArtifactsMcpServersForAgent,
checkPromptArgvBudget,
checkWindowsCmdShimCommandLineBudget,
checkWindowsDirectExeCommandLineBudget,
detectAgents,
getAgentDef,
isKnownModel,
applyAgentLaunchEnv,
resolveAgentLaunch,
sanitizeCustomModel,
spawnEnvForAgent,
} from './agents.js';
import { migrateLegacyDataDirSync } from './legacy-data-migrator.js';
import { findSkillById, listSkills, splitDerivedSkillId } from './skills.js';
import { validateLinkedDirs } from './linked-dirs.js';
import { installFromTarget, uninstallById, sanitizeRepoName } from './library-install.js';
import { buildWindowsFolderDialogCommand, parseFolderDialogStdout } from './native-folder-dialog.js';
import { listCodexPets, readCodexPetSpritesheet } from './codex-pets.js';
import { syncCommunityPets } from './community-pets-sync.js';
import {
listDesignSystems,
readDesignSystem,
resolveDesignSystemAssets,
} from './design-systems.js';
import {
composeMemoryBody,
deleteMemoryEntry,
extractFromMessage,
listMemoryEntries,
maskMemoryExtractionConfig,
memoryDir,
memoryEvents,
readMemoryConfig,
readMemoryEntry,
readMemoryIndex,
upsertMemoryEntry,
writeMemoryConfig,
writeMemoryIndex,
} from './memory.js';
import {
clearExtractions as clearMemoryExtractions,
listExtractions as listMemoryExtractions,
removeExtraction as removeMemoryExtraction,
} from './memory-extractions.js';
import { attachAcpSession } from './acp.js';
import { attachPiRpcSession } from './pi-rpc.js';
import { createClaudeStreamHandler } from './claude-stream.js';
import { diagnoseClaudeCliFailure } from './claude-diagnostics.js';
import { loadCritiqueConfigFromEnv } from './critique/config.js';
import { reconcileStaleRuns } from './critique/persistence.js';
import { runOrchestrator } from './critique/orchestrator.js';
import { createRunRegistry } from './critique/run-registry.js';
import { handleCritiqueInterrupt } from './critique/interrupt-handler.js';
import { handleCritiqueArtifact } from './critique/artifact-handler.js';
import { getCritiqueMetrics, register } from './metrics/index.js';
import { readConformanceHistory } from './critique/conformance-history.js';
import { evaluateRollout } from './critique/ratchet.js';
import {
isCritiqueEnabled,
parseEnvEnabled,
parseRolloutPhase,
type SkillCritiquePolicy,
} from './critique/rollout.js';
import { createCopilotStreamHandler } from './copilot-stream.js';
import { createJsonEventStreamHandler } from './json-event-stream.js';
import { classifyAgentAuthFailure, cursorAuthGuidance } from './runtimes/auth.js';
import { createQoderStreamHandler } from './qoder-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 { reportRunCompletedFromDaemon } from './langfuse-bridge.js';
import {
createAnalyticsService,
readAnalyticsContext,
readPublicConfigResponse,
} from './analytics.js';
import {
redactSecrets,
testAgentConnection,
testProviderConnection,
validateBaseUrl,
} from './connectionTest.js';
import { listProviderModels } from './providerModels.js';
import { importClaudeDesignZip } from './claude-design-import.js';
import {
finalizeDesignPackage,
FinalizePackageLockedError,
FinalizeUpstreamError,
} from './finalize-design.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 { buildDesktopPdfExportInput } from './pdf-export.js';
import { generateMedia } from './media.js';
import { listElevenLabsVoiceOptions } from './elevenlabs-voices.js';
import { searchResearch, ResearchError } from './research/index.js';
import { renderResearchCommandContract } from './prompts/research-contract.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 {
deleteMediaTask,
getMediaTask,
insertMediaTask,
listMediaTasksByProject,
listRecentMediaTasks,
reconcileMediaTasksOnBoot,
updateMediaTask,
} from './media-tasks.js';
import {
MCP_TEMPLATES,
buildAcpMcpServers,
buildClaudeMcpJson,
isManagedProjectCwd,
readMcpConfig,
writeMcpConfig,
} from './mcp-config.js';
import {
beginAuth,
exchangeCodeForToken,
PendingAuthCache,
refreshAccessToken,
} from './mcp-oauth.js';
import {
clearToken,
getToken,
isTokenExpired,
readAllTokens,
setToken,
} from './mcp-tokens.js';
import { agentCliEnvForAgent, readAppConfig, writeAppConfig } from './app-config.js';
import { OrbitService, formatLocalProjectTimestamp, renderOrbitTemplateSystemPrompt } from './orbit.js';
import { buildOrbitNoLiveArtifactSummary } from './orbit-agent-summary.js';
import {
RoutineService,
validateSchedule as validateRoutineSchedule,
validateTarget as validateRoutineTarget,
} from './routines.js';
import { buildMcpInstallPayload } from './mcp-install-info.js';
import {
buildProjectArchive,
buildBatchArchive,
decodeMultipartFilename,
deleteProjectFile,
detectEntryFile,
ensureProject,
isSafeId,
listFiles,
mimeFor,
parseByteRange,
projectDir,
readProjectFile,
renameProjectFile,
removeProjectDir,
sanitizeName,
searchProjectFiles,
resolveProjectDir,
resolveProjectFilePath,
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,
insertRoutine,
insertRoutineRun,
insertTemplate,
findTemplateByNameAndProject,
updateTemplate,
listProjectsAwaitingInput,
listConversations,
listDeployments,
listLatestProjectRunStatuses,
listMessages,
listPreviewComments,
listProjects,
listRoutines,
listRoutineRuns,
listTabs,
listTemplates,
getLatestRoutineRun,
getRoutine,
deleteRoutine as dbDeleteRoutine,
openDatabase,
setTabs,
updateConversation,
updatePreviewCommentStatus,
updateProject,
updateRoutine,
updateRoutineRun,
upsertDeployment,
upsertMessage,
upsertPreviewComment,
} from './db.js';
import {
createLiveArtifact,
deleteLiveArtifact,
ensureLiveArtifactPreview,
getLiveArtifact,
LiveArtifactRefreshLockError,
LiveArtifactStoreValidationError,
listLiveArtifacts,
listLiveArtifactRefreshLogEntries,
readLiveArtifactCode,
recoverStaleLiveArtifactRefreshes,
updateLiveArtifact,
} from './live-artifacts/store.js';
import { LiveArtifactRefreshUnavailableError, refreshLiveArtifact } from './live-artifacts/refresh-service.js';
import { LiveArtifactRefreshAbortError } from './live-artifacts/refresh.js';
import { registerConnectorRoutes } from './connectors/routes.js';
import { registerActiveContextRoutes } from './active-context-routes.js';
import { registerMcpRoutes } from './mcp-routes.js';
import { registerLiveArtifactRoutes } from './live-artifact-routes.js';
import { registerDeployRoutes, registerDeploymentCheckRoutes } from './deploy-routes.js';
import { registerMediaRoutes } from './media-routes.js';
import { registerProjectRoutes, registerProjectArtifactRoutes, registerProjectFileRoutes, registerProjectUploadRoutes } from './project-routes.js';
import { registerFinalizeRoutes, registerImportRoutes, registerProjectExportRoutes } from './import-export-routes.js';
import { registerChatRoutes } from './chat-routes.js';
import { registerStaticResourceRoutes } from './static-resource-routes.js';
import { registerRoutineRoutes, routineDbRowToContract } from './routine-routes.js';
import { assertServerContextSatisfiesRoutes } from './route-context-contract.js';
import { configureConnectorCredentialStore, ConnectorServiceError, FileConnectorCredentialStore } from './connectors/service.js';
import { composioConnectorProvider } from './connectors/composio.js';
import { configureComposioConfigStore } from './connectors/composio-config.js';
import { CHAT_TOOL_ENDPOINTS, CHAT_TOOL_OPERATIONS, toolTokenRegistry } from './tool-tokens.js';
import {
aggregateCloudflarePagesStatus,
buildDeployFileSet,
checkDeploymentUrl,
CLOUDFLARE_PAGES_PROVIDER_ID,
cloudflarePagesProjectNameForProject,
DeployError,
deployToCloudflarePages,
deployToVercel,
isDeployProviderId,
listCloudflarePagesZones,
prepareDeployPreflight,
publicDeployConfigForProvider,
readDeployConfig,
readCloudflarePagesDomain,
VERCEL_PROVIDER_ID,
writeDeployConfig,
} from './deploy.js';
import {
allowedBrowserPorts,
configuredAllowedOrigins,
isAllowedBrowserOrigin,
isLocalSameOrigin,
} from './origin-validation.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 */
/** @typedef {import('@open-design/contracts').ProjectConversationCreatedSsePayload} ProjectConversationCreatedSsePayload */
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);
const DAEMON_CLI_PATH_ENV = 'OD_DAEMON_CLI_PATH';
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, '../..');
}
function cleanOptionalPath(value: string | undefined): string | null {
return typeof value === 'string' && value.trim().length > 0
? path.resolve(value)
: null;
}
export function resolveDaemonCliPath(env: NodeJS.ProcessEnv = process.env): string {
const configured = cleanOptionalPath(env[DAEMON_CLI_PATH_ENV]) ?? cleanOptionalPath(env.OD_BIN);
if (configured) return configured;
const packageJsonPath = require.resolve('@open-design/daemon/package.json');
return path.join(path.dirname(packageJsonPath), 'dist', 'cli.js');
}
const PROJECT_ROOT = resolveProjectRoot(__dirname);
const RESOURCE_ROOT_ENV = 'OD_RESOURCE_ROOT';
let desktopAuthSecret: Buffer | null = null;
let desktopAuthEverRegistered = process.env.OD_REQUIRE_DESKTOP_AUTH === '1';
const consumedImportNonces = new Map<string, number>();
const DESKTOP_IMPORT_TOKEN_TTL_MS = 60_000;
const DESKTOP_IMPORT_TOKEN_FIELD_SEP = '~';
export function setDesktopAuthSecret(secret: Buffer | null): void {
desktopAuthSecret = secret;
if (secret != null) {
desktopAuthEverRegistered = true;
}
consumedImportNonces.clear();
}
export function isDesktopAuthRegistered(): boolean {
return desktopAuthSecret != null;
}
export function isDesktopAuthGateActive(): boolean {
return desktopAuthEverRegistered;
}
export function resetDesktopAuthForTests(): void {
desktopAuthSecret = null;
desktopAuthEverRegistered = process.env.OD_REQUIRE_DESKTOP_AUTH === '1';
consumedImportNonces.clear();
}
function pruneExpiredImportNonces(now: number): void {
for (const [nonce, exp] of consumedImportNonces) {
if (exp <= now) consumedImportNonces.delete(nonce);
}
}
function timingSafeStringEquals(a: string, b: string): boolean {
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
}
export function signDesktopImportToken(
secret: Buffer,
baseDir: string,
options: { nonce: string; exp: string },
): string {
const signature = createHmac('sha256', secret)
.update(`${baseDir}\n${options.nonce}\n${options.exp}`)
.digest('base64url');
return [options.nonce, options.exp, signature].join(DESKTOP_IMPORT_TOKEN_FIELD_SEP);
}
type DesktopImportTokenVerification =
| { ok: true; nonce: string; exp: number }
| { ok: false; reason: string };
export function verifyDesktopImportToken(
secret: Buffer,
baseDir: string,
token: string,
now: number,
consumedNonces: Map<string, number>,
): DesktopImportTokenVerification {
if (typeof token !== 'string' || token.length === 0) {
return { ok: false, reason: 'token missing' };
}
const parts = token.split(DESKTOP_IMPORT_TOKEN_FIELD_SEP);
if (parts.length !== 3) {
return { ok: false, reason: 'token shape invalid' };
}
const [nonce, expISO, signature] = parts;
if (nonce.length === 0 || expISO.length === 0 || signature.length === 0) {
return { ok: false, reason: 'token shape invalid' };
}
const expMs = Date.parse(expISO);
if (!Number.isFinite(expMs)) {
return { ok: false, reason: 'token expiry invalid' };
}
if (expMs <= now) {
return { ok: false, reason: 'token expired' };
}
if (expMs - now > DESKTOP_IMPORT_TOKEN_TTL_MS * 2) {
return { ok: false, reason: 'token expiry exceeds permitted window' };
}
const expected = createHmac('sha256', secret)
.update(`${baseDir}\n${nonce}\n${expISO}`)
.digest('base64url');
if (!timingSafeStringEquals(expected, signature)) {
return { ok: false, reason: 'token signature invalid' };
}
if (consumedNonces.has(nonce)) {
return { ok: false, reason: 'token nonce already used' };
}
return { ok: true, nonce, exp: expMs };
}
export function composeLiveInstructionPrompt({
daemonSystemPrompt,
runtimeToolPrompt,
clientSystemPrompt,
finalPromptOverride,
}) {
const override =
typeof finalPromptOverride === 'string'
? finalPromptOverride.trim()
: '';
const parts = [daemonSystemPrompt, runtimeToolPrompt, clientSystemPrompt]
.map((part) => (typeof part === 'string' ? part.trim() : ''))
.map((part) =>
override && part.includes(override)
? part.split(override).join('').trim()
: part,
)
.filter(Boolean);
if (override) {
parts.push(override);
}
return parts.join('\n\n---\n\n');
}
export function resolveResearchCommandContract(research, message) {
if (!research || !research.enabled) return '';
const researchQuery =
typeof research.query === 'string' && research.query.trim()
? research.query
: message;
return renderResearchCommandContract({
query: researchQuery,
maxSources:
typeof research.maxSources === 'number' ? research.maxSources : undefined,
});
}
export function resolveCodexGeneratedImagesDir(
agentId,
metadata,
env = process.env,
homeDir = os.homedir(),
) {
if (!shouldRenderCodexImagegenOverride(agentId, metadata)) return null;
const rawCodexHome =
typeof env?.CODEX_HOME === 'string' && env.CODEX_HOME.trim().length > 0
? env.CODEX_HOME.trim()
: path.join(homeDir, '.codex');
const codexHome = rawCodexHome.startsWith('~/')
? path.join(homeDir, rawCodexHome.slice(2))
: rawCodexHome;
return path.resolve(codexHome, 'generated_images');
}
type DirectoryStat = {
isDirectory(): boolean;
isSymbolicLink(): boolean;
};
type CodexGeneratedImagesDirValidationOptions = {
protectedDirs?: Array<string | null | undefined>;
mkdirSync?: (target: string, options: { recursive: true }) => unknown;
lstatSync?: (target: string) => DirectoryStat;
statSync?: (target: string) => DirectoryStat;
realpathSync?: (target: string) => string;
warn?: (message: string) => void;
};
function isMissingPathError(err: unknown): boolean {
return (
err &&
typeof err === 'object' &&
'code' in err &&
err.code === 'ENOENT'
);
}
function collectProtectedDirRoots(
protectedDirs: Array<string | null | undefined>,
{
realpathSync,
statSync,
}: {
realpathSync: (target: string) => string;
statSync: (target: string) => DirectoryStat;
},
): string[] {
const roots = [];
for (const raw of Array.isArray(protectedDirs) ? protectedDirs : []) {
if (typeof raw !== 'string' || raw.trim().length === 0) continue;
const resolved = path.resolve(raw);
roots.push(resolved);
try {
const canonical = realpathSync(resolved);
try {
if (statSync(canonical).isDirectory()) roots.push(canonical);
} catch {
roots.push(canonical);
}
} catch {
// A missing protected root cannot be the canonical target of a symlink.
}
}
return Array.from(new Set(roots));
}
function findContainingProtectedRoot(
candidate: string,
protectedRoots: string[],
): string | null {
return protectedRoots.find((root) => isPathWithin(root, candidate)) ?? null;
}
export function validateCodexGeneratedImagesDir(
codexGeneratedImagesDir: string | null | undefined,
{
protectedDirs = [],
mkdirSync = fs.mkdirSync,
lstatSync = fs.lstatSync,
statSync = fs.statSync,
realpathSync = fs.realpathSync.native,
warn = console.warn,
}: CodexGeneratedImagesDirValidationOptions = {},
): string | null {
if (
typeof codexGeneratedImagesDir !== 'string' ||
codexGeneratedImagesDir.trim().length === 0
) {
return null;
}
const resolved = path.resolve(codexGeneratedImagesDir);
const protectedRoots = collectProtectedDirRoots(protectedDirs, {
realpathSync,
statSync,
});
const warnSkipped = (reason: string) =>
warn(`[od] codex generated_images allowlist skipped: ${reason}`);
const protectedRoot = findContainingProtectedRoot(resolved, protectedRoots);
if (protectedRoot) {
warnSkipped(`${resolved} is inside protected root ${protectedRoot}`);
return null;
}
try {
let existingTargetStat = null;
try {
existingTargetStat = lstatSync(resolved);
} catch (err) {
if (!isMissingPathError(err)) throw err;
}
if (existingTargetStat?.isSymbolicLink()) {
warnSkipped(`${resolved} is a symlink`);
return null;
}
if (existingTargetStat && !existingTargetStat.isDirectory()) {
warnSkipped(`${resolved} is not a directory`);
return null;
}
const parent = path.dirname(resolved);
const protectedParentRoot = findContainingProtectedRoot(
parent,
protectedRoots,
);
if (protectedParentRoot) {
warnSkipped(`${parent} is inside protected root ${protectedParentRoot}`);
return null;
}
mkdirSync(parent, { recursive: true });
const canonicalParent = realpathSync(parent);
const canonicalCandidate = path.join(
canonicalParent,
path.basename(resolved),
);
const protectedCanonicalParentRoot = findContainingProtectedRoot(
canonicalCandidate,
protectedRoots,
);
if (protectedCanonicalParentRoot) {
warnSkipped(
`${canonicalCandidate} resolves inside protected root ${protectedCanonicalParentRoot}`,
);
return null;
}
mkdirSync(resolved, { recursive: true });
if (lstatSync(resolved).isSymbolicLink()) {
warnSkipped(`${resolved} is a symlink`);
return null;
}
if (!statSync(resolved).isDirectory()) {
warnSkipped(`${resolved} is not a directory`);
return null;
}
const canonicalDir = realpathSync(resolved);
const protectedCanonicalRoot = findContainingProtectedRoot(
canonicalDir,
protectedRoots,
);
if (protectedCanonicalRoot) {
warnSkipped(
`${canonicalDir} resolves inside protected root ${protectedCanonicalRoot}`,
);
return null;
}
return canonicalDir;
} catch (err) {
const message =
err instanceof Error ? err.message : String(err ?? 'unknown error');
warn(`[od] codex generated_images allowlist mkdir failed: ${message}`);
return null;
}
}
export function resolveChatExtraAllowedDirs({
agentId,
skillsDir,
designSystemsDir,
linkedDirs = [],
codexGeneratedImagesDir,
existsSync = fs.existsSync,
}: {
agentId?: string | null;
skillsDir?: string | null;
designSystemsDir?: string | null;
linkedDirs?: Array<string | null | undefined>;
codexGeneratedImagesDir?: string | null;
existsSync?: (path: string) => boolean;
}): string[] {
const isCodex =
typeof agentId === 'string' && agentId.trim().toLowerCase() === 'codex';
const candidates = isCodex
? [codexGeneratedImagesDir]
: [
skillsDir,
designSystemsDir,
...(Array.isArray(linkedDirs) ? linkedDirs : []),
];
return Array.from(
new Set(
candidates.filter(
(d) =>
typeof d === 'string' && d.length > 0 && existsSync(d),
),
),
);
}
export function resolveGrantedCodexImagegenOverride({
agentId,
metadata,
codexGeneratedImagesDir,
extraAllowedDirs = [],
}: {
agentId?: string | null;
metadata?: unknown;
codexGeneratedImagesDir?: string | null;
extraAllowedDirs?: string[];
}): string | null {
if (
typeof codexGeneratedImagesDir !== 'string' ||
codexGeneratedImagesDir.length === 0 ||
!Array.isArray(extraAllowedDirs) ||
!extraAllowedDirs.includes(codexGeneratedImagesDir)
) {
return null;
}
return renderCodexImagegenOverride(agentId, metadata);
}
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 screenshotPath = cleanString(raw.screenshotPath);
const markKind = normalizeVisualMarkKind(raw.markKind);
const intent = compactString(raw.intent, 220);
const comment = cleanString(raw.comment) || intent;
const selectionKind =
raw.selectionKind === 'visual' ? 'visual' : raw.selectionKind === 'pod' ? 'pod' : 'element';
if (!filePath || !elementId || !comment) return null;
if (selectionKind !== 'visual' && !selector) return null;
if (selectionKind === 'visual' && !screenshotPath) return null;
const podMembers = selectionKind === 'pod' ? normalizeAttachmentPodMembers(raw.podMembers) : [];
const memberCount =
selectionKind === 'pod'
? (podMembers.length > 0
? podMembers.length
: Number.isFinite(raw.memberCount)
? Math.max(0, Math.round(raw.memberCount))
: 0)
: 0;
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),
selectionKind,
memberCount,
podMembers,
screenshotPath: selectionKind === 'visual' ? screenshotPath : undefined,
markKind: selectionKind === 'visual' ? markKind : undefined,
intent: selectionKind === 'visual'
? intent || visualAnnotationIntent(markKind)
: undefined,
source: raw.source === 'board-batch' ? 'board-batch' : 'saved-comment',
};
})
.filter(Boolean)
.sort((a, b) => a.order - b.order);
}
export function renderCommentAttachmentHint(commentAttachments) {
if (!commentAttachments.length) return '';
const lines = [
'',
'',
'<attached-preview-comments>',
'Scope: treat each attachment as the default refinement target. For visual marks, inspect the screenshot and modify the marked region first. Preserve unrelated areas.',
];
for (const item of commentAttachments) {
const targetKind =
item.selectionKind === 'visual' ? 'visual' : item.selectionKind === 'pod' ? 'pod' : 'element';
lines.push(
'',
`${item.order}. ${item.elementId}`,
`targetKind: ${targetKind}`,
`file: ${item.filePath}`,
`label: ${item.label || '(unlabeled)'}`,
`position: ${formatAttachmentPosition(item.pagePosition)}`,
`currentText: ${item.currentText || '(empty)'}`,
`htmlHint: ${item.htmlHint || '(none)'}`,
`comment: ${item.comment}`,
);
if (targetKind === 'visual') {
lines.push(
`screenshot: ${item.screenshotPath}`,
`markKind: ${item.markKind || 'stroke'}`,
`intent: ${item.intent || visualAnnotationIntent(item.markKind || 'stroke')}`,
);
if (item.selector) lines.push(`selector: ${item.selector}`);
} else {
lines.splice(lines.length - 4, 0, `selector: ${item.selector}`);
}
if (targetKind === 'pod') {
lines.push(`memberCount: ${item.memberCount || item.podMembers.length || 0}`);
item.podMembers.slice(0, 8).forEach((member, memberIndex) => {
lines.push(
`member.${memberIndex + 1}: ${member.elementId} | ${member.label || '(unlabeled)'} | ${member.selector}`,
);
});
}
}
lines.push('</attached-preview-comments>');
return lines.join('\n');
}
function cleanString(value) {
return typeof value === 'string' ? value.trim() : '';
}
function normalizeVisualMarkKind(value) {
return value === 'click' || value === 'click+stroke' || value === 'stroke'
? value
: 'stroke';
}
function visualAnnotationIntent(markKind) {
if (markKind === 'click') {
return 'The screenshot has a blue focus box around the picked element; modify that picked part first.';
}
if (markKind === 'click+stroke') {
return 'The screenshot has a blue focus box and red strokes; together they identify the part the user wants changed.';
}
return 'The screenshot has red strokes that identify the visual region the user wants changed.';
}
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 normalizeAttachmentPodMembers(input) {
if (!Array.isArray(input)) return [];
return input
.map((member) => {
if (!member || typeof member !== 'object') return null;
const elementId = cleanString(member.elementId);
const selector = cleanString(member.selector);
const label = cleanString(member.label);
if (!elementId || !selector) return null;
return {
elementId,
selector,
label,
text: compactString(member.text, 160),
position: normalizeAttachmentPosition(member.position),
htmlHint: compactString(member.htmlHint, 180),
};
})
.filter(Boolean);
}
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 = resolveDaemonCliPath();
const OD_NODE_BIN = process.execPath;
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'),
);
// Renderable templates pulled out of `skills/` by the skills/design-templates
// split (PR #955) so the EntryView Templates tab gets the large rendering
// catalogue and Settings → Skills only carries functional skills the agent
// invokes mid-task. See specs/current/skills-and-design-templates.md.
const DESIGN_TEMPLATES_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'design-templates',
path.join(PROJECT_ROOT, 'design-templates'),
);
const CRAFT_DIR = resolveDaemonResourceDir(
DAEMON_RESOURCE_ROOT,
'craft',
path.join(PROJECT_ROOT, 'craft'),
);
// User-installed skills and design systems live under the runtime data dir
// so they respect OD_DATA_DIR overrides (test isolation, packaged runs).
// Defined after RUNTIME_DATA_DIR is resolved below.
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');
// expandHomePrefix is shared with media-config.ts so OD_DATA_DIR and
// OD_MEDIA_CONFIG_DIR can never split state under a $HOME-style value.
// Some launchers (systemd unit files, NixOS modules, certain Docker
// entrypoints, Windows scheduled tasks) pass OD_DATA_DIR with literal
// $HOME or ${HOME} because the variable is never expanded by a shell;
// expandHomePrefix turns those (and the ~ shorthand, with both / and \
// separators) into os.homedir() before path.resolve runs so launch
// surfaces stay consistent.
const resolved = resolveProjectRelativePath(raw, projectRoot);
try {
fs.mkdirSync(resolved, { recursive: true });
fs.accessSync(resolved, fs.constants.W_OK);
} catch (err) {
const e = err;
const currentUser = (() => {
try {