-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathapp-config.ts
More file actions
807 lines (749 loc) · 29.2 KB
/
Copy pathapp-config.ts
File metadata and controls
807 lines (749 loc) · 29.2 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
// Daemon-backed app preferences (onboarding state, agent/skill/DS selection).
//
// The web frontend pushes preferences here via PUT /api/app-config; the
// daemon persists them to <dataDir>/app-config.json (where dataDir defaults
// to <projectRoot>/.od but follows OD_DATA_DIR when set, keeping test and
// multi-namespace runs isolated). This survives browser storage resets and
// origin changes so onboarding and agent selection don't reappear unexpectedly.
//
// `agentCliEnv` is intentionally limited by allowlist below. It is the
// explicit low-level launch environment for Local CLI runs, separate from
// provider BYOK. API-key entries here configure the underlying CLI itself;
// BASE_URL is optional and, when omitted, the CLI uses its default endpoint.
// `agentCliEnvIntent` records when API-key entries were saved under that new
// CLI-override contract. Older builds labeled the same fields as proxy-only,
// so legacy standalone keys without a base URL are dropped unless this marker
// or a matching base URL proves that the user intended to activate them.
// These values are local-only and should not be logged or returned outside
// this machine.
import { readFileSync } from 'node:fs';
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { createHash, randomBytes } from 'node:crypto';
import path from 'node:path';
import { expandHomePrefix } from './home-expansion.js';
import {
readInstallationFile,
readInstallationFileSync,
resolveInstallationDir,
writeInstallationFile,
type InstallationFilePatch,
} from './installation.js';
// Plugin-system env knobs. See docs/plans/plugins-implementation.md F6 / F9.
// Phase 1 only reads them; the GC worker that enforces snapshot expiry lands
// in Phase 5. Centralized here to keep daemon modules from sprinkling magic
// numbers across the codebase.
export interface PluginEnvKnobs {
// Hard ceiling on devloop iterations per stage (spec §10.2).
maxDevloopIterations: number;
// Days before an unreferenced applied_plugin_snapshots row expires. A
// value of 0 means "keep forever" (operators can opt out of GC entirely).
snapshotUnreferencedTtlDays: number;
// Optional cap on how long even a referenced snapshot stays around once
// its run/conversation/project is terminal. Default unset -> unlimited.
snapshotRetentionDays: number | null;
// GC worker tick interval. Phase 5 reads this; Phase 1 just exposes the
// knob through `od config get` so operators can plan ahead.
snapshotGcIntervalMs: number;
}
function intFromEnv(key: string, fallback: number): number {
const raw = process.env[key];
if (typeof raw !== 'string' || raw.trim().length === 0) return fallback;
const parsed = Number(raw);
if (!Number.isFinite(parsed) || parsed < 0) return fallback;
return Math.floor(parsed);
}
function nullableIntFromEnv(key: string): number | null {
const raw = process.env[key];
if (typeof raw !== 'string' || raw.trim().length === 0) return null;
const parsed = Number(raw);
if (!Number.isFinite(parsed) || parsed < 0) return null;
return Math.floor(parsed);
}
export function readPluginEnvKnobs(): PluginEnvKnobs {
return {
maxDevloopIterations: intFromEnv('OD_MAX_DEVLOOP_ITERATIONS', 10),
snapshotUnreferencedTtlDays: intFromEnv('OD_SNAPSHOT_UNREFERENCED_TTL_DAYS', 30),
snapshotRetentionDays: nullableIntFromEnv('OD_SNAPSHOT_RETENTION_DAYS'),
snapshotGcIntervalMs: intFromEnv('OD_SNAPSHOT_GC_INTERVAL_MS', 6 * 60 * 60 * 1000),
};
}
export interface AgentModelPrefs {
model?: string;
reasoning?: string;
}
export type AgentCliEnvPrefs = Record<string, Record<string, string>>;
export type AgentCliEnvIntentPrefs = Record<string, { apiKeyOverride?: boolean }>;
export interface TelemetryPrefs {
metrics?: boolean;
content?: boolean;
artifactManifest?: boolean;
}
export interface OrbitConfigPrefs {
enabled: boolean;
time: string;
templateSkillId?: string | null;
}
export interface ProjectLocationPrefs {
id: string;
name: string;
path: string;
}
export interface AppConfigPrefs {
onboardingCompleted?: boolean;
agentId?: string | null;
agentModels?: Record<string, AgentModelPrefs>;
agentCliEnv?: AgentCliEnvPrefs;
agentCliEnvIntent?: AgentCliEnvIntentPrefs;
skillId?: string | null;
designSystemId?: string | null;
disabledSkills?: string[];
disabledDesignSystems?: string[];
installationId?: string | null;
telemetry?: TelemetryPrefs;
privacyDecisionAt?: number | null;
orbit?: OrbitConfigPrefs;
customInstructions?: string | null;
projectLocations?: ProjectLocationPrefs[];
defaultProjectLocationId?: string | null;
// Most-recently-used local working directories the user granted the agent
// read access to from the Home composer. Become a project's
// `metadata.linkedDirs` (read-only `--add-dir` awareness, no Design Files
// import). Stored most-recent-first; capped at RECENT_LINKED_DIRS_MAX.
recentLinkedDirs?: string[];
}
// Cap on how many recent working directories we remember. Keeps the picker's
// "Recent" submenu short and the config file bounded.
export const RECENT_LINKED_DIRS_MAX = 5;
const ALLOWED_KEYS: ReadonlySet<keyof AppConfigPrefs> = new Set([
'onboardingCompleted',
'agentId',
'agentModels',
'agentCliEnv',
'agentCliEnvIntent',
'skillId',
'designSystemId',
'disabledSkills',
'disabledDesignSystems',
'installationId',
'telemetry',
'privacyDecisionAt',
'orbit',
'customInstructions',
'projectLocations',
'defaultProjectLocationId',
'recentLinkedDirs',
] as const);
function configFile(dataDir: string): string {
return path.join(dataDir, 'app-config.json');
}
export function appConfigDir(projectRoot: string, env: NodeJS.ProcessEnv = process.env): string {
const raw = env.OD_DATA_DIR;
if (typeof raw !== 'string' || raw.trim().length === 0) {
return path.join(projectRoot, '.od');
}
const expanded = expandHomePrefix(raw.trim());
return path.isAbsolute(expanded) ? expanded : path.resolve(projectRoot, expanded);
}
const AGENT_MODEL_KEYS: ReadonlySet<string> = new Set(['model', 'reasoning']);
const RETIRED_AGENT_IDS: ReadonlySet<string> = new Set(['gemini']);
const TELEMETRY_KEYS: ReadonlySet<string> = new Set([
'metrics',
'content',
'artifactManifest',
]);
function validateTelemetry(raw: unknown): TelemetryPrefs | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;
const result: Record<string, boolean> = Object.create(null);
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
if (k === '__proto__' || k === 'constructor') continue;
if (!TELEMETRY_KEYS.has(k)) continue;
if (typeof v === 'boolean') result[k] = v;
}
return Object.keys(result).length > 0 ? (result as TelemetryPrefs) : undefined;
}
const AGENT_CLI_ENV_KEYS: ReadonlyMap<string, ReadonlySet<string>> = new Map([
['amr', new Set([
'VELA_BIN',
'VELA_API_URL',
'VELA_LINK_URL',
'VELA_RUNTIME_KEY',
'VELA_OPENCODE_BIN',
'OPEN_DESIGN_AMR_PROFILE',
'OPENCODE_TEST_HOME',
])],
['aider', new Set(['AIDER_BIN'])],
['claude', new Set(['CLAUDE_CONFIG_DIR', 'CLAUDE_BIN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'MMD_MODEL_ROUTES_FILE'])],
['codex', new Set(['CODEX_HOME', 'CODEX_BIN', 'OPENAI_BASE_URL', 'CODEX_API_KEY', 'OPENAI_API_KEY'])],
['copilot', new Set(['COPILOT_BIN'])],
['cursor-agent', new Set(['CURSOR_AGENT_BIN'])],
['deepseek', new Set(['DEEPSEEK_BIN'])],
['devin', new Set(['DEVIN_BIN'])],
['mimo', new Set(['MIMO_BIN'])],
['hermes', new Set(['HERMES_BIN'])],
['kimi', new Set(['KIMI_BIN'])],
['kiro', new Set(['KIRO_BIN'])],
['kilo', new Set(['KILO_BIN'])],
['kimchi', new Set(['KIMCHI_BIN', 'KIMCHI_API_KEY'])],
['opencode', new Set(['OPENCODE_BIN'])],
['pi', new Set(['PI_BIN'])],
['qoder', new Set(['QODER_BIN'])],
['qwen', new Set(['QWEN_BIN'])],
['trae-cli', new Set(['TRAE_CLI_BIN'])],
['vibe', new Set(['VIBE_BIN'])],
]);
const AGENT_CLI_AUTH_ENV_KEYS: ReadonlyMap<string, {
auth: ReadonlySet<string>;
baseUrl: ReadonlySet<string>;
}> = new Map([
['claude', {
auth: new Set(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']),
baseUrl: new Set(['ANTHROPIC_BASE_URL']),
}],
['codex', {
auth: new Set(['CODEX_API_KEY', 'OPENAI_API_KEY']),
baseUrl: new Set(['OPENAI_BASE_URL']),
}],
]);
function isValidAgentModelEntry(v: unknown): v is AgentModelPrefs {
if (!v || typeof v !== 'object' || Array.isArray(v)) return false;
const obj = v as Record<string, unknown>;
for (const k of Object.keys(obj)) {
if (!AGENT_MODEL_KEYS.has(k)) return false;
if (obj[k] !== undefined && typeof obj[k] !== 'string') return false;
}
return true;
}
function validateAgentModels(
raw: unknown,
): Record<string, AgentModelPrefs> | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;
const result: Record<string, AgentModelPrefs> = Object.create(null);
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
if (k === '__proto__' || k === 'constructor') continue;
if (isValidAgentModelEntry(v)) {
result[k] = v;
}
}
return Object.keys(result).length > 0 ? result : undefined;
}
export function validateAgentCliEnv(raw: unknown): AgentCliEnvPrefs | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;
const result: AgentCliEnvPrefs = Object.create(null);
for (const [agentId, value] of Object.entries(raw as Record<string, unknown>)) {
if (agentId === '__proto__' || agentId === 'constructor') continue;
const allowed = AGENT_CLI_ENV_KEYS.get(agentId);
if (!allowed || typeof value !== 'object' || value === null || Array.isArray(value)) {
continue;
}
const env: Record<string, string> = Object.create(null);
for (const [envKey, envValue] of Object.entries(value as Record<string, unknown>)) {
if (!allowed.has(envKey)) continue;
if (typeof envValue !== 'string') continue;
const trimmed = envValue.trim();
if (!trimmed) continue;
env[envKey] = trimmed;
}
if (Object.keys(env).length > 0) result[agentId] = env;
}
return Object.keys(result).length > 0 ? result : undefined;
}
export function validateAgentCliEnvIntent(raw: unknown): AgentCliEnvIntentPrefs | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;
const result: AgentCliEnvIntentPrefs = Object.create(null);
for (const [agentId, value] of Object.entries(raw as Record<string, unknown>)) {
if (agentId === '__proto__' || agentId === 'constructor') continue;
if (!AGENT_CLI_ENV_KEYS.has(agentId)) continue;
if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
const obj = value as Record<string, unknown>;
if (obj.apiKeyOverride === true) {
result[agentId] = { apiKeyOverride: true };
}
}
return Object.keys(result).length > 0 ? result : undefined;
}
function isValidOrbitTime(time: string): boolean {
const match = /^(\d{2}):(\d{2})$/.exec(time);
if (!match) return false;
const hours = Number(match[1]);
const minutes = Number(match[2]);
return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59;
}
function validateOrbit(raw: unknown): OrbitConfigPrefs | undefined {
if (raw === undefined || raw === null) return undefined;
if (typeof raw !== 'object' || Array.isArray(raw)) return undefined;
const obj = raw as Record<string, unknown>;
const enabled = typeof obj.enabled === 'boolean' ? obj.enabled : false;
const time = typeof obj.time === 'string' && isValidOrbitTime(obj.time)
? obj.time
: '08:00';
const orbit: OrbitConfigPrefs = { enabled, time };
if (Object.hasOwn(obj, 'templateSkillId')) {
orbit.templateSkillId = typeof obj.templateSkillId === 'string' && obj.templateSkillId.trim()
? obj.templateSkillId.trim()
: null;
}
return orbit;
}
function normalizeLocationId(raw: string, fallback: string): string {
const trimmed = raw.trim();
if (/^[A-Za-z0-9._-]{1,128}$/.test(trimmed) && trimmed !== 'default') {
return trimmed;
}
return fallback;
}
function autoProjectLocationId(pathKey: string): string {
return `loc_${createHash('sha256').update(pathKey).digest('base64url').slice(0, 16)}`;
}
function validateProjectLocations(raw: unknown): ProjectLocationPrefs[] | undefined {
if (raw === undefined || raw === null) return undefined;
if (!Array.isArray(raw)) return undefined;
const result: ProjectLocationPrefs[] = [];
const seenIds = new Set<string>();
const seenPaths = new Set<string>();
for (const item of raw) {
if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
const obj = item as Record<string, unknown>;
if (typeof obj.path !== 'string') continue;
const expanded = expandHomePrefix(obj.path.trim());
if (!expanded || !path.isAbsolute(expanded)) continue;
const normalizedPath = path.normalize(expanded);
const pathKey = process.platform === 'win32' ? normalizedPath.toLowerCase() : normalizedPath;
if (seenPaths.has(pathKey)) continue;
const id = normalizeLocationId(
typeof obj.id === 'string' ? obj.id : '',
autoProjectLocationId(pathKey),
);
if (seenIds.has(id)) continue;
const rawName = typeof obj.name === 'string' ? obj.name.trim() : '';
result.push({ id, name: rawName || path.basename(normalizedPath) || normalizedPath, path: normalizedPath });
seenIds.add(id);
seenPaths.add(pathKey);
}
return result;
}
export function agentCliEnvForAgent(
prefs: AgentCliEnvPrefs | undefined,
agentId: string,
): Record<string, string> {
if (!prefs || typeof agentId !== 'string') return {};
const env = prefs[agentId === 'byok-opencode' ? 'opencode' : agentId];
if (!env || typeof env !== 'object' || Array.isArray(env)) return {};
return { ...env };
}
function normalizeAgentCliEnvPrefs(prefs: AppConfigPrefs): AppConfigPrefs {
const agentCliEnv = prefs.agentCliEnv;
if (!agentCliEnv) {
if (!prefs.agentCliEnvIntent) return prefs;
const next = { ...prefs };
delete next.agentCliEnvIntent;
return next;
}
let nextAgentCliEnv = agentCliEnv;
let changed = false;
for (const [agentId, keys] of AGENT_CLI_AUTH_ENV_KEYS) {
const env = nextAgentCliEnv[agentId];
if (!env) continue;
const hasBaseUrl = Object.keys(env).some((key) => keys.baseUrl.has(key));
const hasExplicitApiKeyIntent = prefs.agentCliEnvIntent?.[agentId]?.apiKeyOverride === true;
if (hasBaseUrl || hasExplicitApiKeyIntent) continue;
let nextEnv = env;
for (const authKey of keys.auth) {
if (!Object.prototype.hasOwnProperty.call(nextEnv, authKey)) continue;
if (nextEnv === env) nextEnv = { ...env };
delete nextEnv[authKey];
changed = true;
}
if (nextEnv === env) continue;
nextAgentCliEnv = { ...nextAgentCliEnv };
if (Object.keys(nextEnv).length > 0) {
nextAgentCliEnv[agentId] = nextEnv;
} else {
delete nextAgentCliEnv[agentId];
}
}
let nextAgentCliEnvIntent = prefs.agentCliEnvIntent;
if (nextAgentCliEnvIntent) {
for (const agentId of Object.keys(nextAgentCliEnvIntent)) {
if (nextAgentCliEnv[agentId]) continue;
nextAgentCliEnvIntent = { ...nextAgentCliEnvIntent };
delete nextAgentCliEnvIntent[agentId];
changed = true;
}
}
const normalizedAgentCliEnv = Object.keys(nextAgentCliEnv).length > 0 ? nextAgentCliEnv : undefined;
const normalizedIntent = nextAgentCliEnvIntent && Object.keys(nextAgentCliEnvIntent).length > 0
? nextAgentCliEnvIntent
: undefined;
if (
!changed &&
normalizedAgentCliEnv === prefs.agentCliEnv &&
normalizedIntent === prefs.agentCliEnvIntent
) {
return prefs;
}
const next = { ...prefs };
if (normalizedAgentCliEnv) {
next.agentCliEnv = normalizedAgentCliEnv;
} else {
delete next.agentCliEnv;
}
if (normalizedIntent) {
next.agentCliEnvIntent = normalizedIntent;
} else {
delete next.agentCliEnvIntent;
}
return next;
}
function normalizeRetiredAgentPrefs(prefs: AppConfigPrefs): AppConfigPrefs {
let changed = false;
let next = prefs;
if (typeof next.agentId === 'string' && RETIRED_AGENT_IDS.has(next.agentId)) {
next = { ...next };
delete next.agentId;
changed = true;
}
if (next.agentModels) {
let nextAgentModels = next.agentModels;
for (const agentId of RETIRED_AGENT_IDS) {
if (!Object.prototype.hasOwnProperty.call(nextAgentModels, agentId)) continue;
if (nextAgentModels === next.agentModels) nextAgentModels = { ...next.agentModels };
delete nextAgentModels[agentId];
changed = true;
}
const normalizedAgentModels = Object.keys(nextAgentModels).length > 0 ? nextAgentModels : undefined;
if (normalizedAgentModels !== next.agentModels) {
next = next === prefs ? { ...next } : next;
if (normalizedAgentModels) {
next.agentModels = normalizedAgentModels;
} else {
delete next.agentModels;
}
}
}
return changed ? next : prefs;
}
function inferAgentCliEnvIntentForExplicitEnvWrite(prefs: AppConfigPrefs): AppConfigPrefs {
if (!prefs.agentCliEnv) return prefs;
let nextAgentCliEnvIntent = prefs.agentCliEnvIntent;
let changed = false;
for (const [agentId, keys] of AGENT_CLI_AUTH_ENV_KEYS) {
const env = prefs.agentCliEnv[agentId];
if (!env) continue;
const hasBaseUrl = Object.keys(env).some((key) => keys.baseUrl.has(key));
if (hasBaseUrl) continue;
const hasAuthKey = Object.keys(env).some((key) => keys.auth.has(key));
if (!hasAuthKey) continue;
if (nextAgentCliEnvIntent?.[agentId]?.apiKeyOverride === true) continue;
nextAgentCliEnvIntent = {
...(nextAgentCliEnvIntent ?? {}),
[agentId]: { apiKeyOverride: true },
};
changed = true;
}
if (!changed || !nextAgentCliEnvIntent) return prefs;
return { ...prefs, agentCliEnvIntent: nextAgentCliEnvIntent };
}
function applyConfigValue(
target: Record<string, unknown>,
key: keyof AppConfigPrefs,
value: unknown,
): void {
if (key === 'onboardingCompleted') {
if (typeof value === 'boolean') target[key] = value;
return;
}
if (key === 'agentId' || key === 'skillId' || key === 'designSystemId') {
if (typeof value === 'string' || value === null) target[key] = value;
return;
}
if (key === 'agentModels') {
const validated = validateAgentModels(value);
if (validated !== undefined) {
target[key] = validated;
} else {
delete target[key];
}
}
if (key === 'agentCliEnv') {
const validated = validateAgentCliEnv(value);
if (validated !== undefined) {
target[key] = validated;
} else {
delete target[key];
}
}
if (key === 'agentCliEnvIntent') {
const validated = validateAgentCliEnvIntent(value);
if (validated !== undefined) {
target[key] = validated;
} else {
delete target[key];
}
}
if (key === 'disabledSkills' || key === 'disabledDesignSystems') {
if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
target[key] = value;
} else {
delete target[key];
}
}
if (key === 'installationId') {
if (typeof value === 'string' || value === null) target[key] = value;
return;
}
if (key === 'telemetry') {
const validated = validateTelemetry(value);
if (validated !== undefined) {
target[key] = validated;
} else {
delete target[key];
}
}
if (key === 'privacyDecisionAt') {
if (
value === null ||
(typeof value === 'number' && Number.isFinite(value) && value >= 0)
) {
target[key] = value;
} else {
delete target[key];
}
return;
}
if (key === 'orbit') {
const validated = validateOrbit(value);
if (validated !== undefined) {
target[key] = validated;
} else {
delete target[key];
}
}
if (key === 'customInstructions') {
if (typeof value === 'string') {
target[key] = value.slice(0, 5000);
} else if (value === null) {
target[key] = value;
}
return;
}
if (key === 'projectLocations') {
const validated = validateProjectLocations(value);
if (validated !== undefined) {
target[key] = validated;
} else {
delete target[key];
}
return;
}
if (key === 'defaultProjectLocationId') {
if (typeof value === 'string') {
target[key] = normalizeLocationId(value, 'default');
} else if (value === null) {
target[key] = null;
} else {
delete target[key];
}
return;
}
if (key === 'recentLinkedDirs') {
if (Array.isArray(value)) {
// Keep non-empty strings, trim, de-dupe preserving most-recent-first
// order, and cap the list. Path existence/safety is enforced later by
// validateLinkedDirs when the dir is actually attached to a project, so
// a folder that was since deleted simply drops out at use time rather
// than corrupting the whole config write here.
const seen = new Set<string>();
const cleaned: string[] = [];
for (const entry of value) {
if (typeof entry !== 'string') continue;
const trimmed = entry.trim();
if (!trimmed || seen.has(trimmed)) continue;
seen.add(trimmed);
cleaned.push(trimmed);
if (cleaned.length >= RECENT_LINKED_DIRS_MAX) break;
}
target[key] = cleaned;
} else {
delete target[key];
}
return;
}
}
function filterAllowedKeys(obj: Record<string, unknown>): AppConfigPrefs {
const result: Record<string, unknown> = Object.create(null);
for (const key of Object.keys(obj)) {
if (ALLOWED_KEYS.has(key as keyof AppConfigPrefs)) {
applyConfigValue(result, key as keyof AppConfigPrefs, obj[key]);
}
}
return normalizeRetiredAgentPrefs(normalizeAgentCliEnvPrefs(result as AppConfigPrefs));
}
// Fill in telemetry defaults when the saved config has no `telemetry`
// field at all (fresh install, pre-disclosure). `metrics` / `content`
// default to true so onboarding-funnel events emit from the first
// render — without these defaults the gate at
// `analytics.ts` (`if (cfg.telemetry?.metrics !== true) return`)
// dropped every event a user fired before the post-onboarding
// disclosure modal had a chance to set them. An EXPLICIT `false`
// the user previously saved is preserved (only `undefined` gets
// the new default), so opt-out users stay opted out across the
// 0.7.x → 0.8.0 upgrade.
function applyTelemetryDefaults(prefs: AppConfigPrefs): AppConfigPrefs {
if (prefs.telemetry === undefined) {
return {
...prefs,
telemetry: { metrics: true, content: true },
};
}
return prefs;
}
export async function readAppConfig(dataDir: string): Promise<AppConfigPrefs> {
const base = await readAppConfigFileOnly(dataDir);
// Channel-root installation file is the new authoritative source for the
// identity bits that must survive a namespace-scoped data-dir wipe. It
// lives outside `<namespace>/data/` so a reinstall of the same channel
// (which might churn the namespace token, or eventually clear per-
// namespace data) keeps the same id.
//
// Migration: when this daemon is the first to boot with installation.json
// support and finds an existing installationId in the legacy app-config
// path, mirror it forward exactly once so PostHog continues to see the
// same person across the 0.7.x → 0.8.0 upgrade. Without this mirror, the
// user count would double when 0.8.0 ships.
const installationDir = resolveInstallationDir(dataDir);
const installation = await readInstallationFile(installationDir);
if (typeof installation.installationId === 'string' && installation.installationId.length > 0) {
return applyTelemetryDefaults({ ...base, installationId: installation.installationId });
}
if (typeof base.installationId === 'string' && base.installationId.length > 0) {
// Best-effort migration. A write failure here doesn't break the read —
// we still serve the legacy id. The next write through writeAppConfig
// will retry the mirror.
try {
await writeInstallationFile(installationDir, { installationId: base.installationId });
} catch {
// swallow — observability beats correctness on this path
}
}
return applyTelemetryDefaults(base);
}
// Synchronous mirror of readAppConfig for callers that cannot await — e.g.
// building the spawn env for the vela CLI inside the synchronous
// spawnEnvForAgent. It reuses the exact same parsing, validation and telemetry
// defaulting as the async path, so the consent decision and installationId can
// never drift from what the rest of the daemon (and the web analytics config)
// sees. The only intentional difference is that it skips the best-effort
// legacy→channel-root migration *write*, which is a side effect rather than
// part of the read result.
export function readAppConfigSync(dataDir: string): AppConfigPrefs {
const base = readAppConfigFileOnlySync(dataDir);
const installation = readInstallationFileSync(resolveInstallationDir(dataDir));
if (
typeof installation.installationId === 'string' &&
installation.installationId.length > 0
) {
return applyTelemetryDefaults({
...base,
installationId: installation.installationId,
});
}
return applyTelemetryDefaults(base);
}
function readAppConfigFileOnlySync(dataDir: string): AppConfigPrefs {
try {
const parsed: unknown = JSON.parse(
readFileSync(configFile(dataDir), 'utf8'),
);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return filterAllowedKeys(parsed as Record<string, unknown>);
}
return {};
} catch (err: unknown) {
const e = err as { code?: string; name?: string };
if (e.code === 'ENOENT') return {};
if (e.name === 'SyntaxError') return {};
throw err;
}
}
async function readAppConfigFileOnly(dataDir: string): Promise<AppConfigPrefs> {
try {
const raw = await readFile(configFile(dataDir), 'utf8');
const parsed: unknown = JSON.parse(raw);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return filterAllowedKeys(parsed as Record<string, unknown>);
}
console.warn('[app-config] Invalid shape in config file, returning empty');
return {};
} catch (err: unknown) {
const e = err as { code?: string; name?: string; message?: string };
if (e.code === 'ENOENT') return {};
if (e.name === 'SyntaxError') {
console.error('[app-config] Corrupted JSON, returning empty:', e.message);
return {};
}
throw err;
}
}
// Serialize concurrent writes to the same dataDir so the read-modify-write
// cycle doesn't lose updates when two PUT requests overlap.
const writeLocks = new Map<string, Promise<unknown>>();
export async function writeAppConfig(
dataDir: string,
partial: Record<string, unknown>,
): Promise<AppConfigPrefs> {
const prev = writeLocks.get(dataDir) ?? Promise.resolve();
const task = prev.catch(() => {}).then(() => doWrite(dataDir, partial));
writeLocks.set(dataDir, task);
try {
return await task;
} finally {
if (writeLocks.get(dataDir) === task) writeLocks.delete(dataDir);
}
}
async function doWrite(
dataDir: string,
partial: Record<string, unknown>,
): Promise<AppConfigPrefs> {
const existing = await readAppConfig(dataDir);
const next: Record<string, unknown> = { ...existing };
for (const key of Object.keys(partial)) {
if (!ALLOWED_KEYS.has(key as keyof AppConfigPrefs)) continue;
applyConfigValue(next, key as keyof AppConfigPrefs, partial[key]);
}
const nextWithInferredIntent = Object.prototype.hasOwnProperty.call(partial, 'agentCliEnv')
? inferAgentCliEnvIntentForExplicitEnvWrite(next as AppConfigPrefs)
: next as AppConfigPrefs;
const normalizedNext = normalizeAgentCliEnvPrefs(nextWithInferredIntent);
const normalizedNextWithoutRetiredAgents = normalizeRetiredAgentPrefs(normalizedNext);
const file = configFile(dataDir);
await mkdir(path.dirname(file), { recursive: true });
const tmp = file + '.' + randomBytes(4).toString('hex') + '.tmp';
await writeFile(tmp, JSON.stringify(normalizedNextWithoutRetiredAgents, null, 2), 'utf8');
await rename(tmp, file);
// Mirror the identity bits to the channel-root installation file so they
// survive a namespace-scoped data-dir wipe. Only fires when the caller
// explicitly touched `installationId` (avoiding noisy writes on every
// unrelated app-config update). A write failure here doesn't roll back
// the app-config write — the next read merges them transparently.
if (Object.prototype.hasOwnProperty.call(partial, 'installationId')) {
const id = normalizedNextWithoutRetiredAgents.installationId;
// Caller explicitly touched installationId — mirror the outcome
// (including the clear case) to installation.json so a future read
// doesn't keep serving the old value out of the channel-root file.
// "Delete my data" relies on this clear path.
const installPatch: InstallationFilePatch = {
installationId: typeof id === 'string' && id.length > 0 ? id : null,
};
try {
await writeInstallationFile(resolveInstallationDir(dataDir), installPatch);
} catch {
// swallow — install file mirroring is best-effort; the canonical
// app-config write already succeeded.
}
}
return normalizedNextWithoutRetiredAgents;
}