Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1088 lines (1042 loc) · 48.7 KB
/
Copy pathindex.js
File metadata and controls
1088 lines (1042 loc) · 48.7 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-check
// CoreFacade is the only product entry point. Business orchestration lives in
// application/ and storage adapters live in infrastructure/.
import { createHash } from "node:crypto";
import path from "node:path";
import { publicFileUpdateTiming, publicSkipSummary } from "../../contracts/dist/index.js";
import { createCoreApplication } from "./application/core-application.js";
import { toPublicProgress } from "./progress.js";
import { CoreError, publicHistoryIntegrity } from "./infrastructure/node-core-ports.js";
/** @typedef {{profileId: string, profileRevision?: string}} ProfileSelector */
/** @typedef {{id: string, revision: string, codexHome: string, sqliteHome?: string}} ResolvedProfile */
/** @typedef {(selector: ProfileSelector) => ResolvedProfile | Promise<ResolvedProfile>} ProfileResolver */
/** @typedef {Record<string, unknown>} JsonRecord */
/** @typedef {{stage: string, status: string, progress?: number, count?: number}} PublicProgress */
/** @typedef {{
* schemaVersion: 1,
* event: "started" | "finished",
* activityId: string,
* watchId: string,
* profileRevision?: string,
* backupId?: string,
* failedStage?: string,
* failureCode?: string,
* partialReason?: string,
* retryRecommended?: boolean,
* startedAt?: string,
* finishedAt?: string,
* reason?: string,
* outcome?: "completed" | "partial" | "failed",
* errorCode?: string,
* changedSessionFiles?: number,
* sqliteRowsUpdated?: number,
* skippedLockedRolloutFiles?: number
* skipSummary?: import("../../contracts/dist/index.js").SkipSummary,
* fileUpdateTiming?: import("../../contracts/dist/index.js").FileUpdateTiming
* }} WatchActivityEvent */
/** @typedef {{schemaVersion: 1, watchId: string, status: "stopped", startedAt: string, stoppedAt: string, stopReason: string, includeStateDb: boolean, once: boolean}} WatchStoppedSnapshot */
/** @typedef {{
* signal?: AbortSignal,
* onOperationStarted?: (value: {operationId: string, operation: "sync" | "switch" | "repair" | "restore"}) => void | Promise<void>,
* onProgress?: (event: PublicProgress) => void | Promise<void>
* }} CoreHostOperationControl */
/** @typedef {{
* getStatus: (input: JsonRecord) => Promise<unknown>,
* prepareSync: (input: JsonRecord) => Promise<unknown>,
* applySync: (input: JsonRecord, control?: CoreHostOperationControl) => Promise<unknown>,
* prepareSwitch: (input: JsonRecord) => Promise<unknown>,
* applySwitch: (input: JsonRecord, control?: CoreHostOperationControl) => Promise<unknown>,
* prepareRepair: (input: JsonRecord, control?: CoreHostOperationControl) => Promise<unknown>,
* applyRepair: (input: JsonRecord, control?: CoreHostOperationControl) => Promise<unknown>,
* listBackups: (input: JsonRecord) => Promise<unknown>,
* prepareRestore: (input: JsonRecord) => Promise<unknown>,
* applyRestore: (input: JsonRecord, control?: CoreHostOperationControl) => Promise<unknown>,
* pruneBackups: (input: JsonRecord) => Promise<unknown>,
* listHistory: (input: JsonRecord) => Promise<unknown>,
* getHistorySession: (input: JsonRecord) => Promise<unknown>,
* startWatch: (input: JsonRecord) => Promise<unknown>,
* stopWatch: (input: JsonRecord) => Promise<unknown>,
* getWatchStatus: (input?: JsonRecord) => Promise<unknown>,
* getDiagnostics: (input: JsonRecord, control?: CoreHostOperationControl) => Promise<unknown>
* }} CoreFacade */
const PROFILE_ID_PATTERN = /^[A-Za-z0-9._-]{1,80}$/;
/** @param {unknown} value @returns {value is Record<string, unknown>} */
function isRecord(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/** @param {unknown} input */
function requireProfileSelector(input) {
if (!isRecord(input) || !isRecord(input.profile)) {
throw new CoreError("INVALID_INPUT", "A trusted profile selector is required.");
}
const selector = input.profile;
const allowedKeys = new Set(["profileId", "profileRevision"]);
if (Object.keys(selector).some((key) => !allowedKeys.has(key))
|| typeof selector.profileId !== "string"
|| !PROFILE_ID_PATTERN.test(selector.profileId)
|| (selector.profileRevision !== undefined
&& (typeof selector.profileRevision !== "string"
|| !selector.profileRevision
|| selector.profileRevision.length > 512))) {
throw new CoreError("INVALID_INPUT", "The profile selector is invalid.");
}
return /** @type {ProfileSelector} */ ({
profileId: selector.profileId,
...(selector.profileRevision === undefined
? {}
: { profileRevision: selector.profileRevision })
});
}
/** @param {ResolvedProfile} value @param {ProfileSelector} selector */
function validateResolvedProfile(value, selector) {
if (!isRecord(value)
|| typeof value.id !== "string"
|| value.id !== selector.profileId
|| !PROFILE_ID_PATTERN.test(value.id)
|| typeof value.revision !== "string"
|| !value.revision
|| value.revision.length > 512
|| typeof value.codexHome !== "string"
|| !path.isAbsolute(value.codexHome)
|| (value.sqliteHome !== undefined
&& (typeof value.sqliteHome !== "string" || !path.isAbsolute(value.sqliteHome)))) {
throw new CoreError("INVALID_INPUT", "The trusted profile resolver returned an invalid profile.");
}
if (selector.profileRevision !== undefined && selector.profileRevision !== value.revision) {
throw new CoreError("PROFILE_CHANGED", "The selected profile changed. Prepare the operation again.");
}
return Object.freeze({
id: value.id,
revision: value.revision,
codexHome: path.resolve(value.codexHome),
...(value.sqliteHome ? { sqliteHome: path.resolve(value.sqliteHome) } : {})
});
}
/** @param {ResolvedProfile} profile @param {string} [revision] */
function rootProfileInput(profile, revision = profile.revision) {
return {
codexHome: profile.codexHome,
...(profile.sqliteHome ? { sqliteHome: profile.sqliteHome } : {}),
profileId: profile.id,
profileRevision: revision
};
}
/** @param {unknown} value @param {ResolvedProfile} profile */
function withPublicProfile(value, profile) {
if (!isRecord(value)) return value;
return { ...value, profile: { id: profile.id, revision: profile.revision } };
}
/** @param {unknown} value */
function publicWarnings(value) {
if (!Array.isArray(value)) return [];
/** @type {string[]} */
const result = [];
for (const warning of value.filter((entry) => typeof entry === "string")) {
let projected;
if (warning.startsWith("Backup inventory refresh failed:")) {
projected = "Backup inventory refresh failed.";
} else if (warning.startsWith("Automatic backup cleanup failed:")) {
projected = "Automatic backup cleanup failed.";
} else if (warning.startsWith("Encrypted content warning:")) {
projected = "Some encrypted histories may require their original Provider or account for continuation.";
} else if (/^\d+ rollout file\(s\) are currently locked/.test(warning)) {
projected = "One or more rollout files are locked and may be skipped.";
} else if (warning.startsWith("Provider \"") && warning.includes("has no model field")) {
projected = "The selected Provider has no default model; the root model will remain unchanged.";
} else if (warning === "Project visibility diagnostics are unavailable; the write operation will still validate and protect the global state with backup-first recovery.") {
projected = "Project visibility diagnostics are unavailable; backup-first protection remains enabled.";
} else if (warning === "SQLite Home relocation is explicit; config.toml will not be restored.") {
projected = "SQLite Home relocation is confirmed; config.toml will not be restored.";
} else if (/^Restore skipped (config|globalState|sqlite|rollout): the selected backup did not capture this target\.$/.test(warning)) {
projected = warning;
} else if (warning.startsWith("The operation stopped during ")) {
projected = "The operation made only part of the requested change. Retry it to converge, or restore the managed backup.";
} else {
projected = "The operation produced an additional warning.";
}
if (!result.includes(projected)) result.push(projected);
}
return result;
}
/** @param {unknown} value */
function publicOperationState(value) {
if (!isRecord(value)) return null;
/** @type {Record<string, string>} */
const result = {};
for (const key of [
"operationId",
"operation",
"actor",
"runtime",
"startedAt",
"busyScope",
"lockState",
"errorCode"
]) {
const candidate = value[key];
if (typeof candidate === "string") result[key] = candidate;
}
return result;
}
const DIAGNOSTIC_IDENTIFIER = /^[A-Za-z0-9._()-]{1,200}$/;
const DIAGNOSTIC_TRANSACTION_STATES = new Set([
"prepared",
"applying",
"applied",
"skipped",
"committing",
"committed-pending-ack",
"rollback-pending",
"rollingBack",
"recovery-required",
"recoveryRequired",
"unknown"
]);
/** @param {unknown} value */
function diagnosticIdentifier(value) {
return typeof value === "string" && DIAGNOSTIC_IDENTIFIER.test(value) ? value : null;
}
/** @param {unknown} value */
function diagnosticDistribution(value) {
const source = isRecord(value) ? value : {};
/** @param {unknown} counts */
const project = (counts) => Object.fromEntries(
Object.entries(isRecord(counts) ? counts : {})
.filter(([provider, count]) =>
DIAGNOSTIC_IDENTIFIER.test(provider)
&& Number.isSafeInteger(count)
&& Number(count) >= 0
)
.slice(0, 512)
);
return {
sessions: project(source.sessions),
archived_sessions: project(source.archived_sessions)
};
}
/** @param {unknown} value */
function diagnosticOperationState(value) {
if (!isRecord(value)) return null;
/** @type {Record<string, string>} */
const result = {};
if (typeof value.operationId === "string"
&& /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.operationId)) {
result.operationId = value.operationId;
}
if (typeof value.operation === "string"
&& ["sync", "switch", "repair", "restore", "prune", "watch", "unknown"].includes(value.operation)) {
result.operation = value.operation;
}
if (typeof value.actor === "string"
&& ["manual", "watch", "external"].includes(value.actor)) result.actor = value.actor;
if (typeof value.startedAt === "string" && value.startedAt.length <= 64) {
result.startedAt = value.startedAt;
}
if (typeof value.busyScope === "string"
&& ["codex-home", "state-db"].includes(value.busyScope)) result.busyScope = value.busyScope;
const lockState = diagnosticIdentifier(value.lockState);
if (lockState && lockState.length <= 80) result.lockState = lockState;
if (typeof value.errorCode === "string" && /^[A-Z0-9_]{1,80}$/.test(value.errorCode)) {
result.errorCode = value.errorCode;
}
return result;
}
/** @param {unknown} value @param {boolean} [includeLocalDisplayPaths] */
function publicStatus(value, includeLocalDisplayPaths = false) {
if (!isRecord(value)) return value;
const rolloutCounts = isRecord(value.rolloutCounts) ? value.rolloutCounts : {};
const sqliteCounts = value.sqliteCounts ?? {};
const provider = typeof value.currentProvider === "string" && value.currentProvider
? value.currentProvider
: "openai";
/** @param {unknown} distribution */
const matchesProvider = (distribution) => isRecord(distribution)
&& ["sessions", "archived_sessions"].every((scope) => {
const counts = isRecord(distribution[scope]) ? distribution[scope] : {};
return Object.entries(counts).every(([candidate, count]) => Number(count) === 0 || candidate === provider);
});
const operation = publicOperationState(value.operationInProgress);
const locked = Array.isArray(value.lockedRolloutFiles)
? value.lockedRolloutFiles.filter((entry) => typeof entry === "string").map((entry) => path.basename(entry))
: [];
const pending = Array.isArray(value.pendingTransactions)
? value.pendingTransactions.filter(isRecord).map((transaction) => ({
operationId: typeof transaction.operationId === "string" ? transaction.operationId : null,
operationKind: typeof transaction.operationKind === "string" ? transaction.operationKind : "sync",
state: typeof transaction.state === "string" ? transaction.state : "unknown",
sourceBackupId: typeof transaction.sourceBackupId === "string" ? transaction.sourceBackupId : null,
preRestoreSnapshotId: typeof transaction.preRestoreSnapshotId === "string"
? transaction.preRestoreSnapshotId
: null
}))
: [];
const backupSummary = isRecord(value.backupSummary) ? value.backupSummary : {};
const blocked = isRecord(value.statusReadBlocked) && typeof value.statusReadBlocked.reason === "string"
? { reason: value.statusReadBlocked.reason }
: undefined;
const sqliteReadable = isRecord(sqliteCounts) && sqliteCounts.unreadable !== true;
const storageRevision = typeof value.storageRevision === "string" && value.storageRevision
? value.storageRevision
: compositeRevision(JSON.stringify({
schemaVersion: 1,
profileRevision: isRecord(value.profile) ? value.profile.revision ?? null : null,
operation,
blocked: blocked ?? null
}));
return {
schemaVersion: 1,
snapshotAt: value.snapshotAt,
// With no last-complete cache, a fail-closed lock inspection can happen
// before the internal scanner has a storage revision. Emit a deterministic
// degraded revision so clients can cache the blocked snapshot without
// mistaking it for a complete scan.
storageRevision,
profile: value.profile,
currentProvider: provider,
...(isRecord(value.sessionActivity) ? { sessionActivity: publicSessionActivity(value.sessionActivity) } : {}),
...(isRecord(value.syncSessionUsage) ? {
syncSessionUsage: value.syncSessionUsage.state === "checked"
&& typeof value.syncSessionUsage.count === "number"
&& Number.isSafeInteger(value.syncSessionUsage.count) && value.syncSessionUsage.count >= 0
? { state: "checked", count: value.syncSessionUsage.count }
: { state: value.syncSessionUsage.state === "unsupported" ? "unsupported" : "unavailable", count: null }
} : {}),
...(typeof value.currentModel === "string" || value.currentModel === null
? { currentModel: value.currentModel }
: {}),
rolloutCounts,
...(isRecord(value.modelCounts) ? { modelCounts: value.modelCounts } : {}),
sqliteCounts,
codexHomeSource: "profile",
// A fail-closed status read can be blocked before storage resolution has
// produced a source label (for example, immediately after a Utility
// Process dies while holding the Home lock). The public Status contract
// still requires a non-empty source and must not collapse that safe
// degraded snapshot into INVALID_INPUT.
sqliteHomeSource: typeof value.sqliteHomeSource === "string" && value.sqliteHomeSource
? value.sqliteHomeSource
: "unknown",
// Local desktop display only: use the same completed snapshot as the counts.
// This trusted factory option is never part of a Renderer request.
...(includeLocalDisplayPaths && typeof value.codexHome === "string" && typeof value.sqliteHome === "string"
? { displayPaths: {
codexHome: value.codexHome,
sqliteHome: value.sqliteHome,
stateDbPath: isRecord(value.stateDbLocation) && typeof value.stateDbLocation.path === "string"
? value.stateDbLocation.path
: null
} }
: {}),
backupSummary: {
count: Number.isSafeInteger(backupSummary.count) ? backupSummary.count : 0,
totalBytes: Number.isSafeInteger(backupSummary.totalBytes) ? backupSummary.totalBytes : 0
},
pendingRecovery: pending.some((transaction) => transaction.operationKind === "restore")
|| value.pendingRecovery === true,
pendingTransactions: pending,
operationInProgress: operation,
...(value.staleLockDetected === true ? { staleLockDetected: true } : {}),
rolloutScanComplete: value.rolloutScanComplete === true && locked.length === 0,
lockedRolloutFiles: locked,
...(publicSkipSummary(value.skipSummary) ? { skipSummary: publicSkipSummary(value.skipSummary) } : {}),
currentProviderImplicit: value.currentProviderImplicit === true,
configuredProviders: Array.isArray(value.configuredProviders)
? value.configuredProviders.filter((entry) => typeof entry === "string")
: [],
alignment: {
aligned: Boolean(!operation
&& !blocked
&& sqliteReadable
&& value.rolloutScanComplete === true
&& locked.length === 0
&& matchesProvider(rolloutCounts)
&& matchesProvider(sqliteCounts)),
sqliteReadable,
targetProvider: provider
},
...(blocked ? { statusReadBlocked: blocked } : {})
};
}
/** @param {unknown} value */
function publicSessionActivity(value) {
if (!isRecord(value)) return undefined;
return value.state === "checked" && typeof value.count === "number"
&& Number.isSafeInteger(value.count) && value.count >= 0
? { state: "checked", count: value.count }
: { state: value.state === "unsupported" ? "unsupported" : "unavailable", count: null };
}
/** @param {unknown} value */
function publicPlan(value) {
if (!isRecord(value)) return value;
const target = isRecord(value.target) ? value.target : {};
const impact = isRecord(value.impact) ? value.impact : {};
/** @type {Record<string, unknown>} */
const publicTarget = {};
for (const key of ["provider", "model", "modelMode", "previousProvider", "previousRootModel", "backupId"]) {
const candidate = target[key];
if (typeof candidate === "string" || candidate === null) publicTarget[key] = candidate;
}
for (const key of ["restoreConfig", "restoreDatabase", "restoreSessions", "allowSqliteHomeRelocation"]) {
if (typeof target[key] === "boolean") publicTarget[key] = target[key];
}
if (Array.isArray(target.targets)) {
publicTarget.targets = target.targets.filter((entry) => (
typeof entry === "string"
&& ["models", "cwd", "userEvent", "workspaceRoots"].includes(entry)
));
}
if (value.operation === "repair") {
if (target.scope === "all" || target.scope === "selected") publicTarget.scope = target.scope;
if (Array.isArray(target.sessionIds)) {
publicTarget.sessionIds = target.sessionIds.filter((id) => typeof id === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(id)).slice(0, 100);
}
}
/** @type {Record<string, unknown>} */
const publicImpact = {};
if (publicSkipSummary(impact.skipSummary)) publicImpact.skipSummary = publicSkipSummary(impact.skipSummary);
if (isRecord(impact.sessionActivity)) publicImpact.sessionActivity = publicSessionActivity(impact.sessionActivity);
for (const [key, candidate] of Object.entries(impact)) {
if (typeof candidate === "boolean" || (Number.isSafeInteger(candidate) && Number(candidate) >= 0)) {
publicImpact[key] = candidate;
}
}
if (Array.isArray(impact.lockedRolloutFiles)) {
publicImpact.lockedRolloutFiles = impact.lockedRolloutFiles
.filter((entry) => typeof entry === "string")
.map((entry) => path.basename(entry));
}
if (value.operation === "repair" && Array.isArray(impact.workspaceSettingsChangeKinds)) {
const allowed = ["savedRoots", "projectOrder", "activeRoots", "labels", "openTargets", "settingsBackup"];
const changeKinds = impact.workspaceSettingsChangeKinds;
publicImpact.workspaceSettingsChangeKinds = allowed.filter((kind) => changeKinds.includes(kind));
}
if (value.operation === "repair" && Array.isArray(impact.repairPreview)) {
publicImpact.repairPreview = impact.repairPreview.filter(isRecord).slice(0, 100).flatMap((entry) => {
if (typeof entry.sessionId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(entry.sessionId)) return [];
const changes = Array.isArray(entry.changes) ? entry.changes.filter(isRecord).filter((change) => (
["models", "cwd", "userEvent"].includes(String(change.target))
&& typeof change.before === "string" && /^[A-Za-z0-9._:/-]{1,160}$/.test(change.before)
&& typeof change.after === "string" && /^[A-Za-z0-9._:/-]{1,160}$/.test(change.after)
)).slice(0, 3).map((change) => ({ target: change.target, before: change.before, after: change.after })) : [];
return [{ sessionId: entry.sessionId, changes }];
});
}
return {
schemaVersion: 1,
planId: value.planId,
operation: value.operation,
createdAt: value.createdAt,
expiresAt: value.expiresAt,
profile: value.profile,
storageRevision: value.storageRevision,
configRevision: value.configRevision,
rolloutRevision: value.rolloutRevision,
stateDbRevision: value.stateDbRevision,
...(typeof value.backupRevision === "string" ? { backupRevision: value.backupRevision } : {}),
target: publicTarget,
impact: publicImpact,
warnings: publicWarnings(value.warnings),
requiresConfirmation: value.requiresConfirmation === true
};
}
/** @param {unknown} value */
function publicOperationResult(value) {
if (!isRecord(value)) return value;
const backup = isRecord(value.backup) && typeof value.backup.backupId === "string"
? { backupId: value.backup.backupId }
: null;
const source = isRecord(value.result) ? value.result : {};
/** @type {Record<string, unknown>} */
const result = {};
const skipSummary = publicSkipSummary(source.skipSummary);
if (skipSummary) result.skipSummary = skipSummary;
const fileUpdateTiming = publicFileUpdateTiming(source.fileUpdateTiming);
if (fileUpdateTiming) result.fileUpdateTiming = fileUpdateTiming;
for (const key of [
"targetProvider",
"targetModel",
"modelSource",
"partialReason",
"failedStage",
"failureCode",
"restoreOperationId",
"preRestoreSnapshotId",
"restoreJournalState"
]) {
const candidate = source[key];
if (typeof candidate === "string" || candidate === null) result[key] = candidate;
}
if (Number.isSafeInteger(source.restoreVersion) && Number(source.restoreVersion) >= 1) {
result.restoreVersion = Number(source.restoreVersion);
}
if (typeof source.commitAcknowledgementRecovered === "boolean") {
result.commitAcknowledgementRecovered = source.commitAcknowledgementRecovered;
}
for (const key of ["noop", "retryRecommended", "configUpdated"]) {
if (typeof source[key] === "boolean") result[key] = source[key];
}
if (Array.isArray(source.resolvedOperationIds)) {
result.resolvedOperationCount = source.resolvedOperationIds
.filter((entry) => typeof entry === "string" && entry.length > 0).length;
}
for (const key of [
"backupDurationMs",
"unconfirmedSessionFiles",
"changedSessionFiles",
"inPlaceSessionFiles",
"rewrittenSessionFiles",
"sqliteRowsUpdated",
"sqliteProviderRowsUpdated",
"sqliteModelRowsUpdated",
"sqliteUserEventRowsUpdated",
"sqliteCwdRowsUpdated",
"updatedWorkspaceRoots",
"savedWorkspaceRootCount"
]) {
const candidate = source[key];
if (Number.isSafeInteger(candidate) && Number(candidate) >= 0) result[key] = candidate;
}
if (Array.isArray(source.skippedLockedRolloutFiles)) {
result.skippedLockedRolloutFiles = source.skippedLockedRolloutFiles
.filter((entry) => typeof entry === "string")
.map((entry) => path.basename(entry));
}
if (Array.isArray(source.skippedChangedRolloutFiles)) {
result.skippedChangedRolloutFiles = source.skippedChangedRolloutFiles
.filter((entry) => typeof entry === "string")
.map((entry) => path.basename(entry));
}
if (Array.isArray(source.repairTargets)) {
result.repairTargets = source.repairTargets.filter((entry) => (
typeof entry === "string"
&& ["models", "cwd", "userEvent", "workspaceRoots"].includes(entry)
));
}
if (value.operation === "repair" && isRecord(source.verification)) {
const verification = source.verification;
result.verification = {
status: ["verified", "remaining", "unavailable"].includes(String(verification.status)) ? verification.status : "unavailable",
...Object.fromEntries(["remainingRolloutFiles", "remainingSqliteRows", "remainingWorkspaceRoots", "skippedSessions"].map((key) => [
key, Number.isSafeInteger(verification[key]) && Number(verification[key]) >= 0 ? verification[key] : 0
]))
};
}
return {
schemaVersion: 1,
operationId: value.operationId,
operation: value.operation,
outcome: value.outcome,
backup,
warnings: publicWarnings(value.warnings),
result
};
}
/** @param {unknown} value */
function publicBackupMetadata(value) {
const metadata = isRecord(value) ? value : {};
/** @type {Record<string, unknown>} */
const result = {};
for (const key of ["version", "namespace", "targetProvider", "createdAt"] ) {
const candidate = metadata[key];
if (typeof candidate === "string") result[key] = candidate;
else if (typeof candidate === "number" && Number.isSafeInteger(candidate)) result[key] = candidate;
}
for (const key of ["changedSessionFiles", "fileCount"] ) {
const candidate = metadata[key];
if (Number.isSafeInteger(candidate) && Number(candidate) >= 0) result[key] = Number(candidate);
}
const undoTargets = isRecord(metadata.undoTargets) ? metadata.undoTargets : null;
if (undoTargets) {
/** @type {Record<string, boolean>} */
const capturedTargetKinds = {};
for (const kind of ["config", "globalState", "sqlite", "rollout"]) {
const target = undoTargets[kind];
if (isRecord(target) && typeof target.captured === "boolean") {
capturedTargetKinds[kind] = target.captured;
}
}
if (Object.keys(capturedTargetKinds).length === 4) {
result.capturedTargetKinds = capturedTargetKinds;
}
}
return result;
}
/** Display-only grouping from recorded metadata; never resolve or follow a directory.
* @param {unknown} cwd
*/
function publicHistoryProject(cwd) {
if (typeof cwd !== "string" || !cwd || /[\x00-\x1f\x7f]/.test(cwd)) return null;
const windows = /^[A-Za-z]:[\\/]/.test(cwd) || /^\\\\/.test(cwd);
const paths = windows ? path.win32 : path.posix;
if (!paths.isAbsolute(cwd)) return null;
const normalized = paths.normalize(cwd);
const root = paths.parse(normalized).root;
const directory = normalized.length > root.length ? normalized.replace(/[\\/]+$/, "") : normalized;
const name = (paths.basename(directory) || root.replace(/[\\/]/g, "") || "/").slice(0, 160);
return { id: compositeRevision(`${windows ? "win" : "posix"}:${windows ? directory.toLowerCase() : directory}`), name };
}
/** @param {unknown} value */
function publicHistorySummary(value) {
if (!isRecord(value)) return value;
const recordedProject = isRecord(value.project)
&& typeof value.project.id === "string" && (/^[a-f0-9]{64}$/.test(value.project.id) || ["unassigned", "orphans"].includes(value.project.id))
&& typeof value.project.name === "string" && value.project.name.length > 0
&& value.project.name.length <= 160 && !/[\x00-\x1f\x7f]/.test(value.project.name)
? { id: value.project.id, name: value.project.name }
: null;
return {
id: value.id,
title: value.title,
project: recordedProject ?? publicHistoryProject(value.cwd),
...(value.nativeSessionId === undefined ? {} : { nativeSessionId: value.nativeSessionId }),
...(value.parentSessionId === undefined ? {} : { parentSessionId: value.parentSessionId }),
...(value.sessionKind === undefined ? {} : { sessionKind: value.sessionKind }),
...(typeof value.childCount === "number" && Number.isSafeInteger(value.childCount) && value.childCount >= 0
? { childCount: value.childCount }
: {}),
...(value.fileModifiedAt === undefined ? {} : { fileModifiedAt: value.fileModifiedAt }),
...(typeof value.subagentName === "string" ? { subagentName: value.subagentName } : {}),
provider: value.provider,
...(value.model === undefined ? {} : { model: value.model }),
archived: value.archived,
...(typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {}),
updatedAt: value.updatedAt,
messageCount: value.messageCount,
...(typeof value.messageCountKnown === "boolean"
? { messageCountKnown: value.messageCountKnown }
: {})
};
}
/** @param {string} value */
function compositeRevision(value) {
return createHash("sha256").update(value, "utf8").digest("hex");
}
/**
* Create the shared Core facade for a trusted host. The resolver is the only
* component allowed to translate product profile identifiers into paths.
* @param {{
* resolveProfile: ProfileResolver,
* includeLocalDisplayPaths?: boolean,
* onWatchActivity?: (event: WatchActivityEvent & {profileId: string}) => void | Promise<void>,
* onWatchStopped?: (event: {profileId: string, profileRevision: string, watch: WatchStoppedSnapshot}) => void | Promise<void>
* }} options
*/
export function createCoreFacade({ resolveProfile, onWatchActivity, onWatchStopped, includeLocalDisplayPaths = false }) {
if (typeof resolveProfile !== "function") {
throw new TypeError("createCoreFacade requires a trusted resolveProfile function.");
}
const application = createCoreApplication();
/** @param {ProfileSelector} selector */
async function resolveTrusted(selector) {
return validateResolvedProfile(await resolveProfile(selector), selector);
}
function currentProfileResolver() {
/** @param {string} profileId */
return async (profileId) => resolveTrusted({ profileId: String(profileId) });
}
/** @param {unknown} input */
async function trustedInput(input) {
const selector = requireProfileSelector(input);
const profile = await resolveTrusted(selector);
return { input: /** @type {JsonRecord} */ (input), profile };
}
/** @param {unknown} control @returns {CoreHostOperationControl | undefined} */
function trustedOperationControl(control) {
if (!isRecord(control)) return undefined;
const progressObserver = typeof control.onProgress === "function"
? /** @type {CoreHostOperationControl["onProgress"]} */ (control.onProgress)
: undefined;
const onProgress = progressObserver
? /** @param {unknown} event */ (event) => {
const projected = toPublicProgress(event);
if (projected) return progressObserver(projected);
}
: undefined;
const startedObserver = typeof control.onOperationStarted === "function"
? /** @type {CoreHostOperationControl["onOperationStarted"]} */ (control.onOperationStarted)
: undefined;
const signal = control.signal
? /** @type {AbortSignal} */ (control.signal)
: undefined;
return {
...(signal ? { signal } : {}),
...(startedObserver
? { onOperationStarted: startedObserver }
: {}),
...(onProgress ? { onProgress } : {})
};
}
/** @type {CoreFacade} */
const handlers = {
async getStatus(input) {
const trusted = await trustedInput(input);
return publicStatus(withPublicProfile(
await application.getStatus({
...rootProfileInput(trusted.profile),
// Trusted host-only optimization. This option is intentionally not
// represented in the public CoreClient/HTTP/IPC input schemas.
rolloutScanMode: "metadata"
}),
trusted.profile
), includeLocalDisplayPaths === true);
},
async prepareSync(input) {
const trusted = await trustedInput(input);
const plan = await application.prepareSync({
...rootProfileInput(trusted.profile),
...(trusted.input.keepCount === undefined ? {} : { keepCount: trusted.input.keepCount }),
profileResolver: currentProfileResolver()
});
return publicPlan(withPublicProfile(plan, trusted.profile));
},
async applySync(input, control) {
return publicOperationResult(await application.applySync(input, trustedOperationControl(control)));
},
async prepareSwitch(input) {
const trusted = await trustedInput(input);
const provider = trusted.input.provider;
const modelMode = trusted.input.modelMode;
if (typeof provider !== "string" || !provider
|| !["provider-default", "keep-root-model", "explicit"].includes(String(modelMode))) {
throw new CoreError("INVALID_INPUT", "The Switch Provider input is invalid.");
}
if ((modelMode === "explicit" && (typeof trusted.input.model !== "string" || !trusted.input.model))
|| (modelMode !== "explicit" && trusted.input.model !== undefined)) {
throw new CoreError("INVALID_INPUT", "The selected model mode and model are inconsistent.");
}
const plan = await application.prepareSwitch({
...rootProfileInput(trusted.profile),
provider,
...(modelMode === "explicit" ? { model: trusted.input.model } : {}),
...(modelMode === "keep-root-model" ? { keepRootModel: true } : {}),
...(trusted.input.keepCount === undefined ? {} : { keepCount: trusted.input.keepCount }),
profileResolver: currentProfileResolver()
});
return publicPlan(withPublicProfile(plan, trusted.profile));
},
async applySwitch(input, control) {
return publicOperationResult(await application.applySwitch(input, trustedOperationControl(control)));
},
async prepareRepair(input, control) {
const trusted = await trustedInput(input);
const targets = trusted.input.targets;
if (!Array.isArray(targets)
|| targets.length < 1
|| targets.length > 4
|| targets.some((target) => typeof target !== "string"
|| !["models", "cwd", "userEvent", "workspaceRoots"].includes(target))
|| new Set(targets).size !== targets.length) {
throw new CoreError("INVALID_INPUT", "The Repair targets are invalid.");
}
const sessionIds = trusted.input.sessionIds;
if (sessionIds !== undefined && (!Array.isArray(sessionIds)
|| sessionIds.length < 1 || sessionIds.length > 100
|| sessionIds.some((id) => typeof id !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(id))
|| new Set(sessionIds).size !== sessionIds.length || targets.includes("workspaceRoots"))) {
throw new CoreError("INVALID_INPUT", "The Repair session selection is invalid.");
}
const plan = await application.prepareRepair({
...rootProfileInput(trusted.profile),
requestControl: trustedOperationControl(control),
targets,
...(sessionIds === undefined ? {} : { sessionIds }),
...(trusted.input.keepCount === undefined ? {} : { keepCount: trusted.input.keepCount }),
profileResolver: currentProfileResolver()
});
return publicPlan(withPublicProfile(plan, trusted.profile));
},
async applyRepair(input, control) {
return publicOperationResult(await application.applyRepair(input, trustedOperationControl(control)));
},
async listBackups(input) {
const trusted = await trustedInput(input);
const inventoryValue = await application.listBackups(trusted.profile.codexHome);
const inventory = /** @type {Record<string, unknown>} */ (
isRecord(inventoryValue) ? inventoryValue : {}
);
const backups = Array.isArray(inventory.backups) ? inventory.backups : [];
return {
backups: backups.filter(isRecord).map((backupValue) => {
const backup = /** @type {Record<string, unknown>} */ (backupValue);
return {
backupId: backup.id,
sizeBytes: backup.sizeBytes,
metadata: publicBackupMetadata(backup.metadata)
};
})
};
},
async prepareRestore(input) {
const trusted = await trustedInput(input);
let executionProfile = trusted.profile;
let profileResolver = currentProfileResolver();
if (trusted.input.relocationTargetProfileId !== undefined) {
if (trusted.input.allowSqliteHomeRelocation !== true
|| trusted.input.restoreConfig !== false
|| typeof trusted.input.relocationTargetProfileId !== "string") {
throw new CoreError("INVALID_INPUT", "SQLite relocation requires an explicit target and config restore disabled.");
}
const targetId = trusted.input.relocationTargetProfileId;
const target = await resolveTrusted({ profileId: targetId });
if (!target.sqliteHome) {
throw new CoreError("INVALID_INPUT", "The relocation target profile has no explicit SQLite Home.");
}
const revision = compositeRevision(JSON.stringify([
trusted.profile.id,
trusted.profile.revision,
target.id,
target.revision
]));
executionProfile = { ...trusted.profile, sqliteHome: target.sqliteHome, revision };
profileResolver = async (/** @type {string} */ profileId) => {
const [current, currentTarget] = await Promise.all([
resolveTrusted({ profileId: String(profileId) }),
resolveTrusted({ profileId: targetId })
]);
if (!currentTarget.sqliteHome) {
throw new CoreError("PROFILE_CHANGED", "The relocation target profile changed.");
}
return {
...current,
sqliteHome: currentTarget.sqliteHome,
revision: compositeRevision(JSON.stringify([
current.id,
current.revision,
currentTarget.id,
currentTarget.revision
]))
};
};
}
const plan = await application.prepareRestore({
...rootProfileInput(executionProfile),
backupId: trusted.input.backupId,
restoreConfig: trusted.input.restoreConfig,
restoreDatabase: trusted.input.restoreDatabase,
restoreSessions: trusted.input.restoreSessions,
...(trusted.input.allowSqliteHomeRelocation === undefined
? {}
: { allowSqliteHomeRelocation: trusted.input.allowSqliteHomeRelocation }),
profileResolver
});
return publicPlan(withPublicProfile(plan, trusted.profile));
},
async applyRestore(input, control) {
return publicOperationResult(await application.applyRestore(input, trustedOperationControl(control)));
},
async pruneBackups(input) {
const trusted = await trustedInput(input);
const result = await application.pruneBackups({
codexHome: trusted.profile.codexHome,
keepCount: trusted.input.keepCount
});
if (!isRecord(result)) return result;
return { deletedCount: result.deletedCount, remainingCount: result.remainingCount, freedBytes: result.freedBytes };
},
async listHistory(input) {
const trusted = await trustedInput(input);
const { profile: _profile, sqliteHome: _untrustedSqliteHome, ...options } = trusted.input;
const resultValue = await application.listHistory(trusted.profile.codexHome, {
...options,
...(trusted.profile.sqliteHome ? { sqliteHome: trusted.profile.sqliteHome } : {})
});
if (!isRecord(resultValue)) return resultValue;
const projects = "projects" in resultValue && Array.isArray(resultValue.projects)
? resultValue.projects.map((entry) => ({
id: entry?.id,
name: entry?.name,
kind: entry?.kind,
total: entry?.total
}))
: null;
return {
...resultValue,
sessions: Array.isArray(resultValue.sessions) ? resultValue.sessions.map(publicHistorySummary) : [],
...(projects ? { projects } : {})
};
},
async getHistorySession(input) {
const trusted = await trustedInput(input);
if (typeof trusted.input.sessionId !== "string" || !trusted.input.sessionId) {
throw new CoreError("INVALID_INPUT", "sessionId is required.");
}
const metadataOnly = trusted.input.metadataOnly;
const messageLimit = trusted.input.messageLimit;
if (metadataOnly !== undefined && typeof metadataOnly !== "boolean") {
throw new CoreError("INVALID_INPUT", "metadataOnly must be a boolean.");
}
if (messageLimit !== undefined
&& (typeof messageLimit !== "number" || !Number.isSafeInteger(messageLimit) || messageLimit < 1)) {
throw new CoreError("INVALID_INPUT", "messageLimit must be a positive integer.");
}
const resultValue = await application.getHistorySession(
trusted.profile.codexHome,
trusted.input.sessionId,
{
...(typeof metadataOnly === "boolean" ? { metadataOnly } : {}),
...(typeof messageLimit === "number" ? { messageLimit } : {}),
...(trusted.profile.sqliteHome ? { sqliteHome: trusted.profile.sqliteHome } : {})
}
);
if (!isRecord(resultValue)) return resultValue;
const session = resultValue.session;
return {
...resultValue,
session: publicHistorySummary(session),
...(includeLocalDisplayPaths && isRecord(session)
&& typeof session.rolloutPath === "string" && typeof session.cwd === "string"
? { storage: { cwd: session.cwd, rolloutPath: session.rolloutPath } } : {})
};
},
async startWatch(input) {
const trusted = await trustedInput(input);
return application.startWatch({
...rootProfileInput(trusted.profile),
...(trusted.input.includeStateDb === undefined ? {} : { includeStateDb: trusted.input.includeStateDb }),
...(trusted.input.debounceMs === undefined ? {} : { debounceMs: trusted.input.debounceMs }),
...(trusted.input.once === undefined ? {} : { once: trusted.input.once }),
...(trusted.input.keepCount === undefined ? {} : { keepCount: trusted.input.keepCount }),
...(typeof onWatchActivity === "function" ? {
onActivity: /** @param {WatchActivityEvent} event */ (event) =>
onWatchActivity({ ...event, profileId: trusted.profile.id, profileRevision: trusted.profile.revision })
} : {}),
...(typeof onWatchStopped === "function" ? {
onStopped: /** @param {WatchStoppedSnapshot} watch */ (watch) =>
onWatchStopped({ profileId: trusted.profile.id, profileRevision: trusted.profile.revision, watch })
} : {})
});
},
async stopWatch(input) {
return application.stopWatch(input);
},
async getWatchStatus(input = {}) {
if (!isRecord(input)
|| Object.keys(input).some((key) => key !== "profile" && key !== "watchId")
|| (input.watchId !== undefined && typeof input.watchId !== "string")
|| (input.profile !== undefined && input.watchId !== undefined)) {
throw new CoreError("INVALID_INPUT", "Expected {}, { watchId }, or { profile } for Watch status.");
}
if (typeof input.watchId === "string") {
return application.getWatchStatus({ watchId: input.watchId });
}
if (input.profile !== undefined) {
const trusted = await trustedInput(input);
return application.getWatchStatus({
profileId: trusted.profile.id,
profileRevision: trusted.profile.revision
});
}
return application.getWatchStatus();
},
async getDiagnostics(input, control) {
const trusted = await trustedInput(input);
const value = await application.getDiagnostics({
...rootProfileInput(trusted.profile),
requestControl: trustedOperationControl(control)
});
if (!isRecord(value)) return value;
const runtime = /** @type {Record<string, unknown>} */ (isRecord(value.runtime) ? value.runtime : {});
const storage = /** @type {Record<string, unknown>} */ (isRecord(value.storage) ? value.storage : {});
const provider = /** @type {Record<string, unknown>} */ (isRecord(value.provider) ? value.provider : {});
const issues = /** @type {Record<string, unknown>} */ (isRecord(value.issues) ? value.issues : {});
const safety = /** @type {Record<string, unknown>} */ (isRecord(value.safety) ? value.safety : {});
const sqliteHomeSource = typeof storage.sqliteHomeSource === "string"
&& ["cli", "config", "env", "default"].includes(storage.sqliteHomeSource)
? storage.sqliteHomeSource
: "unknown";
const sqliteCounts = provider.sqliteCounts === null
? null
: {
...diagnosticDistribution(provider.sqliteCounts),
...(isRecord(provider.sqliteCounts) && provider.sqliteCounts.unreadable === true
? { unreadable: true }
: {})
};
return {