@jini-ai/desktop-host 0.7.3-next.1 → 0.7.3-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +217 -1
  3. package/dist/electron/electron-shell.js +5 -7
  4. package/dist/electron/handoff/index.d.ts +54 -0
  5. package/dist/electron/handoff/index.js +32 -0
  6. package/dist/electron/memory-sampler.d.ts +28 -0
  7. package/dist/electron/memory-sampler.js +41 -0
  8. package/dist/electron/partitions/cache-maintenance.d.ts +280 -0
  9. package/dist/electron/partitions/cache-maintenance.js +239 -0
  10. package/dist/electron/partitions/claim-sources.d.ts +54 -0
  11. package/dist/electron/partitions/claim-sources.js +36 -0
  12. package/dist/electron/partitions/holder-registry.d.ts +116 -0
  13. package/dist/electron/partitions/holder-registry.js +130 -0
  14. package/dist/electron/partitions/index.d.ts +10 -0
  15. package/dist/electron/partitions/index.js +10 -0
  16. package/dist/electron/partitions/maintenance-marker.d.ts +61 -0
  17. package/dist/electron/partitions/maintenance-marker.js +85 -0
  18. package/dist/electron/partitions/partition-inventory.d.ts +23 -0
  19. package/dist/electron/partitions/partition-inventory.js +19 -0
  20. package/dist/electron/partitions/partition-pass.d.ts +114 -0
  21. package/dist/electron/partitions/partition-pass.js +414 -0
  22. package/dist/electron/partitions/partition-root.d.ts +42 -0
  23. package/dist/electron/partitions/partition-root.js +52 -0
  24. package/dist/electron/partitions/profile-interlock.d.ts +141 -0
  25. package/dist/electron/partitions/profile-interlock.js +273 -0
  26. package/dist/electron/partitions/retirement-ledger.d.ts +116 -0
  27. package/dist/electron/partitions/retirement-ledger.js +149 -0
  28. package/dist/electron/preferences/index.d.ts +5 -0
  29. package/dist/electron/preferences/index.js +5 -0
  30. package/dist/electron/preferences/ipc.d.ts +35 -0
  31. package/dist/electron/preferences/ipc.js +21 -0
  32. package/dist/electron/preferences/menu.d.ts +103 -0
  33. package/dist/electron/preferences/menu.js +67 -0
  34. package/dist/electron/preferences/preference-file.d.ts +63 -0
  35. package/dist/electron/preferences/preference-file.js +51 -0
  36. package/dist/electron/preferences/values.d.ts +25 -0
  37. package/dist/electron/preferences/values.js +18 -0
  38. package/dist/electron/preload/index.d.ts +3 -0
  39. package/dist/electron/preload/index.js +2 -0
  40. package/dist/electron/preload/ipc-subscribe.d.ts +34 -0
  41. package/dist/electron/preload/ipc-subscribe.js +18 -0
  42. package/dist/electron/selftest/index.d.ts +3 -0
  43. package/dist/electron/selftest/index.js +3 -0
  44. package/dist/electron/selftest/selftest-tracker.d.ts +82 -0
  45. package/dist/electron/selftest/selftest-tracker.js +67 -0
  46. package/dist/electron/session-bootstrap/exchange.d.ts +50 -0
  47. package/dist/electron/session-bootstrap/exchange.js +41 -0
  48. package/dist/electron/session-bootstrap/header-arming.d.ts +18 -0
  49. package/dist/electron/session-bootstrap/header-arming.js +13 -0
  50. package/dist/electron/session-bootstrap/index.d.ts +11 -0
  51. package/dist/electron/session-bootstrap/index.js +10 -0
  52. package/dist/electron/session-bootstrap/partition.d.ts +17 -0
  53. package/dist/electron/session-bootstrap/partition.js +24 -0
  54. package/dist/electron/session-bootstrap/probe.d.ts +40 -0
  55. package/dist/electron/session-bootstrap/probe.js +29 -0
  56. package/dist/electron/session-bootstrap/types.d.ts +62 -0
  57. package/dist/electron/session-bootstrap/types.js +7 -0
  58. package/dist/electron/updates/desktop-updater.d.ts +90 -0
  59. package/dist/electron/updates/desktop-updater.js +124 -0
  60. package/dist/electron/updates/index.d.ts +4 -0
  61. package/dist/electron/updates/index.js +4 -0
  62. package/dist/electron/updates/instance-presence-strict.d.ts +27 -0
  63. package/dist/electron/updates/instance-presence-strict.js +46 -0
  64. package/dist/electron/updates/native-notices.d.ts +89 -0
  65. package/dist/electron/updates/native-notices.js +41 -0
  66. package/dist/electron/updates/update-check-now.d.ts +117 -0
  67. package/dist/electron/updates/update-check-now.js +88 -0
  68. package/dist/electron/usability/find-in-page-ipc.d.ts +3 -6
  69. package/dist/electron/usability/window-bounds-store.js +14 -12
  70. package/dist/electron/usability/zoom-menu.d.ts +1 -1
  71. package/dist/electron/webview/index.d.ts +2 -0
  72. package/dist/electron/webview/index.js +2 -0
  73. package/dist/electron/webview/webview-types.d.ts +66 -0
  74. package/dist/electron/webview/webview-types.js +12 -0
  75. package/dist/electron/windows/app-window.d.ts +83 -0
  76. package/dist/electron/windows/app-window.js +62 -0
  77. package/dist/electron/windows/dock-icon.d.ts +34 -0
  78. package/dist/electron/windows/dock-icon.js +32 -0
  79. package/dist/electron/windows/index.d.ts +3 -0
  80. package/dist/electron/windows/index.js +3 -0
  81. package/dist/logging.js +3 -1
  82. package/dist/node-toolchain/boot-setup.d.ts +63 -0
  83. package/dist/node-toolchain/boot-setup.js +59 -0
  84. package/dist/node-toolchain/index.d.ts +2 -0
  85. package/dist/node-toolchain/index.js +1 -0
  86. package/dist/shell/auto-update-controller.d.ts +34 -0
  87. package/dist/shell/auto-update-controller.js +27 -0
  88. package/dist/shell/copied-site-databases.d.ts +71 -0
  89. package/dist/shell/copied-site-databases.js +60 -0
  90. package/dist/shell/find-in-page-verify.d.ts +33 -0
  91. package/dist/shell/find-in-page-verify.js +30 -0
  92. package/dist/shell/find-menu.d.ts +33 -0
  93. package/dist/shell/find-menu.js +36 -0
  94. package/dist/shell/guest-navigation.d.ts +47 -0
  95. package/dist/shell/guest-navigation.js +58 -0
  96. package/dist/shell/instance-presence.d.ts +20 -0
  97. package/dist/shell/instance-presence.js +26 -0
  98. package/dist/shell/js-backslide-guard.d.ts +42 -0
  99. package/dist/shell/js-backslide-guard.js +44 -0
  100. package/dist/shell/node-toolchain.d.ts +34 -0
  101. package/dist/shell/node-toolchain.js +50 -0
  102. package/dist/shell/pty-helpers.d.ts +25 -0
  103. package/dist/shell/pty-helpers.js +50 -0
  104. package/dist/shell/site-presence.d.ts +32 -0
  105. package/dist/shell/site-presence.js +42 -0
  106. package/dist/shell/speech/mac-on-device-transcriber.d.ts +24 -0
  107. package/dist/shell/speech/mac-on-device-transcriber.js +81 -0
  108. package/dist/shell/speech/speech-ipc.d.ts +52 -0
  109. package/dist/shell/speech/speech-ipc.js +40 -0
  110. package/dist/shell/spellcheck-menu.d.ts +84 -0
  111. package/dist/shell/spellcheck-menu.js +63 -0
  112. package/dist/shell/supervised-site-url.d.ts +20 -0
  113. package/dist/shell/supervised-site-url.js +22 -0
  114. package/dist/speech/macos/mac-on-device-transcriber.d.ts +2 -1
  115. package/dist/speech/speech-bridge.d.ts +1 -8
  116. package/dist/speech/transcription-port.d.ts +1 -9
  117. package/dist/tauri/tauri-shell.js +8 -10
  118. package/package.json +154 -7
@@ -0,0 +1,280 @@
1
+ import type { StrictRead } from './claim-sources.js';
2
+ import type { HolderRecord, PartitionFsPort } from './holder-registry.js';
3
+ import type { CodeCacheMark } from './maintenance-marker.js';
4
+ import type { PartitionInterlock, PartitionWriterContext } from './profile-interlock.js';
5
+ /**
6
+ * Cache maintenance for site partitions. Every mutation here is cache-only (`Cache`, `Code Cache`) and
7
+ * gated by packaged evidence that the bundled Electron keeps sign-in stores (Cookies, Local Storage,
8
+ * IndexedDB) when that exact operation runs. Only `'go'` permits a mutation; `'no-go'` and `'unknown'`
9
+ * leave everything as it is.
10
+ */
11
+ export type EvidenceVerdict = 'go' | 'no-go' | 'unknown';
12
+ export interface PackagedEvidence {
13
+ cap: EvidenceVerdict;
14
+ clearOps: {
15
+ clearCache: EvidenceVerdict;
16
+ clearCodeCaches: EvidenceVerdict;
17
+ };
18
+ }
19
+ export type SizeRead = {
20
+ state: 'measured';
21
+ bytes: number;
22
+ } | {
23
+ state: 'unknown';
24
+ reason: string;
25
+ };
26
+ export interface CacheFsPort {
27
+ /** Recursive; must not fail when the folder exists. */
28
+ mkdir(required: {
29
+ path: string;
30
+ }): Promise<void>;
31
+ rename(required: {
32
+ oldPath: string;
33
+ newPath: string;
34
+ }): Promise<void>;
35
+ }
36
+ export interface TimeoutClock {
37
+ sleep(required: {
38
+ ms: number;
39
+ }): Promise<void>;
40
+ }
41
+ export type CacheClearMark = {
42
+ state: 'done';
43
+ capBytes: number;
44
+ } | {
45
+ state: 'pending';
46
+ capBytes: number;
47
+ attempts: number;
48
+ lastReason: string;
49
+ } | {
50
+ state: 'absent';
51
+ } | {
52
+ state: 'unknown';
53
+ reason: string;
54
+ };
55
+ export interface CacheClearMarker {
56
+ readCacheClear(required: {
57
+ partition: string;
58
+ }): Promise<CacheClearMark>;
59
+ markCacheClear(required: {
60
+ partition: string;
61
+ capBytes: number;
62
+ outcome: {
63
+ state: 'done';
64
+ } | {
65
+ state: 'pending';
66
+ reason: string;
67
+ };
68
+ }): Promise<void>;
69
+ }
70
+ export interface PartitionLocation {
71
+ name: string;
72
+ dir: string;
73
+ }
74
+ /** Boot: the partition is unheld and the caller holds the writer lock (the partition pass `maintenance` hook). */
75
+ export interface BootCacheInterlock {
76
+ phase: 'boot';
77
+ writer: Pick<PartitionWriterContext, 'assertHeld' | 'setTarget'>;
78
+ readHoldersStrict: () => Promise<StrictRead<HolderRecord[]>>;
79
+ /** Lowercase hex; names the aside folder so the next pass sweeps it as cache-only. */
80
+ newToken: () => string;
81
+ }
82
+ /** Open: runs only as the interlock's `openMaintenance` hook, after its other-holder check and before first use. */
83
+ export interface OpenCacheInterlock {
84
+ phase: 'open';
85
+ session: {
86
+ clearCache(): Promise<void>;
87
+ };
88
+ clock: TimeoutClock;
89
+ }
90
+ export type Settlement = {
91
+ state: 'resolved';
92
+ } | {
93
+ state: 'rejected';
94
+ reason: string;
95
+ };
96
+ export type PendingReason = 'busy' | 'held' | 'holders-unknown' | 'unmeasured' | 'missing' | 'failed' | 'timeout';
97
+ export type CacheClearMode = 'one-time' | 'periodic';
98
+ export type CacheClearResult = {
99
+ state: 'cleared';
100
+ mode: CacheClearMode;
101
+ bytes: number;
102
+ aside: string | null;
103
+ } | {
104
+ state: 'below-threshold';
105
+ mode: CacheClearMode;
106
+ bytes: number;
107
+ } | {
108
+ state: 'already-done';
109
+ } | {
110
+ state: 'pending';
111
+ reason: PendingReason;
112
+ settlement?: Promise<Settlement>;
113
+ } | {
114
+ state: 'skipped';
115
+ reason: 'evidence-no-go' | 'evidence-unknown';
116
+ };
117
+ export interface ClearPartitionCacheRequired {
118
+ partition: PartitionLocation;
119
+ interlock: BootCacheInterlock | OpenCacheInterlock;
120
+ fs: CacheFsPort;
121
+ measure: (required: {
122
+ path: string;
123
+ }) => Promise<SizeRead>;
124
+ marker: CacheClearMarker;
125
+ evidence: PackagedEvidence;
126
+ capBytes: number;
127
+ }
128
+ export interface ClearPartitionCacheOptional {
129
+ fallbackMultiplier?: number;
130
+ timeoutMs?: number;
131
+ asideDirName?: string;
132
+ }
133
+ /**
134
+ * Before `app` is ready: cap the HTTP disk cache, only when packaged evidence shows the switch bounds
135
+ * every persistent partition. Anything other than `'go'` (including a missing or mismatched evidence
136
+ * file, which the host reports as `'unknown'`) sets no switch and claims no bound.
137
+ * @complexity O(1).
138
+ */
139
+ export declare function applyDesktopCacheLimits({ appendSwitch, evidence, cacheBytes }: {
140
+ appendSwitch: (name: string, value: string) => void;
141
+ evidence: PackagedEvidence;
142
+ cacheBytes: number;
143
+ }, _optional?: Record<string, never>): {
144
+ state: 'applied';
145
+ cacheBytes: number;
146
+ } | {
147
+ state: 'skipped';
148
+ reason: 'evidence-no-go' | 'evidence-unknown' | 'invalid-bytes';
149
+ };
150
+ /** Races the real operation against the clock; the result keeps the actual settlement apart from the observed timeout. */
151
+ export declare function settleWithin({ run, clock, timeoutMs }: {
152
+ run: () => Promise<void>;
153
+ clock: TimeoutClock;
154
+ timeoutMs: number;
155
+ }): Promise<Settlement | {
156
+ state: 'timed-out';
157
+ settlement: Promise<Settlement>;
158
+ }>;
159
+ /** True when any live holder record (this process included) lists the partition as intended or held. */
160
+ export declare function listedByHolder({ holders, name }: {
161
+ holders: readonly HolderRecord[];
162
+ name: string;
163
+ }, _optional?: Record<string, never>): boolean;
164
+ /**
165
+ * Renames one cache folder of an unheld partition into the aside folder, under the writer lock with the
166
+ * target fence on this partition and a fresh holder read after it. The partition pass deletes it later,
167
+ * outside the lock, by its cache-only aside name. Sign-in stores in the partition are never touched.
168
+ */
169
+ export declare function renameCacheAside({ partition, sub, interlock, fs }: {
170
+ partition: PartitionLocation;
171
+ sub: 'Cache' | 'Code Cache';
172
+ interlock: BootCacheInterlock;
173
+ fs: CacheFsPort;
174
+ }, { asideDirName }?: {
175
+ asideDirName?: string;
176
+ }): Promise<{
177
+ state: 'cleared';
178
+ aside: string;
179
+ } | {
180
+ state: 'pending';
181
+ reason: 'busy' | 'held' | 'holders-unknown' | 'missing' | 'failed';
182
+ }>;
183
+ /**
184
+ * Clears one partition's HTTP `Cache` when it is over the threshold. Boot renames the folder of an unheld
185
+ * partition aside; open awaits the measured `session.clearCache()` before first use. Done is written only
186
+ * after that clear succeeded or a measurement verified the cache is under the threshold; busy, held,
187
+ * unmeasured, failed and timed-out clears stay pending and are retried next start.
188
+ * @complexity O(1) fs operations plus one measurement.
189
+ */
190
+ export declare function clearPartitionCacheOnce(required: ClearPartitionCacheRequired, { fallbackMultiplier, timeoutMs, asideDirName }?: ClearPartitionCacheOptional): Promise<CacheClearResult>;
191
+ export interface CodeCacheMarker {
192
+ readCodeCache(): Promise<CodeCacheMark>;
193
+ writeCodeCachePending(required: {
194
+ forVersion: string;
195
+ pending: string[];
196
+ }): Promise<void>;
197
+ writeLaunchVersion(required: {
198
+ version: string;
199
+ }): Promise<void>;
200
+ settleCodeCache(required: {
201
+ partition: string;
202
+ }): Promise<void>;
203
+ }
204
+ export interface CodeCacheInterlock {
205
+ withPartitionWriter: PartitionInterlock['withPartitionWriter'];
206
+ readHoldersStrict: () => Promise<StrictRead<HolderRecord[]>>;
207
+ isManaged: (name: string) => boolean;
208
+ newToken: () => string;
209
+ }
210
+ export type CodeCacheFsPort = CacheFsPort & Pick<PartitionFsPort, 'readdir' | 'lstat' | 'realpath'>;
211
+ export interface ClearCodeCacheOnUpdateRequired {
212
+ interlock: CodeCacheInterlock;
213
+ fs: CodeCacheFsPort;
214
+ marker: CodeCacheMarker;
215
+ evidence: PackagedEvidence;
216
+ version: string;
217
+ isUpdate: boolean;
218
+ }
219
+ export type CodeCacheUpdateResult = {
220
+ state: 'ran';
221
+ update: boolean;
222
+ cleared: string[];
223
+ kept: Array<{
224
+ partition: string;
225
+ reason: PendingReason;
226
+ }>;
227
+ } | {
228
+ state: 'skipped';
229
+ reason: 'evidence-no-go' | 'evidence-unknown' | 'writer-busy' | 'root-unknown' | 'marker-failed';
230
+ };
231
+ /**
232
+ * Boot: on an update launch (flag or version change) every managed partition's `Code Cache` becomes
233
+ * pending; then, under the writer lock, each pending partition no holder lists is renamed aside. The
234
+ * rename runs only with `'go'` evidence for the code-cache clear. Never throws.
235
+ * @complexity O(partitions) fs operations.
236
+ */
237
+ export declare function clearCodeCacheOnUpdate(required: ClearCodeCacheOnUpdateRequired, { asideDirName }?: {
238
+ asideDirName?: string;
239
+ }): Promise<CodeCacheUpdateResult>;
240
+ export interface MaybeClearCodeCacheAtOpenRequired {
241
+ session: {
242
+ clearCodeCaches(options: Record<string, never>): Promise<void>;
243
+ };
244
+ /** Size of this partition's `Code Cache`; a bounded walk that answers unknown rather than guessing. */
245
+ measure: () => Promise<SizeRead>;
246
+ evidence: PackagedEvidence;
247
+ /** Bound to this partition: drops it from the update-pending list. */
248
+ marker: {
249
+ settle(): Promise<void>;
250
+ };
251
+ clock: TimeoutClock;
252
+ }
253
+ export type CodeCacheOpenResult = {
254
+ state: 'cleared';
255
+ bytes: number;
256
+ } | {
257
+ state: 'below-threshold';
258
+ bytes: number;
259
+ } | {
260
+ state: 'pending';
261
+ reason: 'failed' | 'timeout';
262
+ settlement?: Promise<Settlement>;
263
+ } | {
264
+ state: 'skipped';
265
+ reason: 'evidence-no-go' | 'evidence-unknown' | 'unmeasured';
266
+ };
267
+ /**
268
+ * Open-time code-cache clear. It runs only as the interlock's `openMaintenance` hook (step 2.5), which
269
+ * already found no other holder and has not yet marked the partition held, so no window or guest uses the
270
+ * session while it clears; it does no holders check of its own. A second window of a held site must skip
271
+ * it: that window shares the live session, whose pages are already running and may be compiling into the
272
+ * code cache, and the clear would race them; the interlock returns `already-held` without calling it.
273
+ * Success is marked only when `clearCodeCaches` resolves; a timeout is reported apart from the settlement.
274
+ * @complexity O(1) plus one measurement.
275
+ */
276
+ export declare function maybeClearCodeCacheAtOpen({ session, measure, evidence, marker, clock }: MaybeClearCodeCacheAtOpenRequired, { maxBytes, timeoutMs }?: {
277
+ maxBytes?: number;
278
+ timeoutMs?: number;
279
+ }): Promise<CodeCacheOpenResult>;
280
+ //# sourceMappingURL=cache-maintenance.d.ts.map
@@ -0,0 +1,239 @@
1
+ import path from 'node:path';
2
+ import { listCandidates } from './partition-root.js';
3
+ import { DEFAULT_ASIDE_DIR_NAME } from './partition-pass.js';
4
+ const BUSY = ['EBUSY', 'EPERM', 'EACCES'];
5
+ const code = (error) => error?.code;
6
+ const describe = (error) => String(code(error) ?? (error instanceof Error ? error.message : error));
7
+ const evidenceSkip = (verdict) => ({ state: 'skipped', reason: verdict === 'no-go' ? 'evidence-no-go' : 'evidence-unknown' });
8
+ /**
9
+ * Before `app` is ready: cap the HTTP disk cache, only when packaged evidence shows the switch bounds
10
+ * every persistent partition. Anything other than `'go'` (including a missing or mismatched evidence
11
+ * file, which the host reports as `'unknown'`) sets no switch and claims no bound.
12
+ * @complexity O(1).
13
+ */
14
+ export function applyDesktopCacheLimits({ appendSwitch, evidence, cacheBytes }, _optional = {}) {
15
+ if (evidence.cap !== 'go')
16
+ return evidenceSkip(evidence.cap);
17
+ if (!Number.isSafeInteger(cacheBytes) || cacheBytes <= 0)
18
+ return { state: 'skipped', reason: 'invalid-bytes' };
19
+ appendSwitch('disk-cache-size', String(cacheBytes));
20
+ return { state: 'applied', cacheBytes };
21
+ }
22
+ /** Races the real operation against the clock; the result keeps the actual settlement apart from the observed timeout. */
23
+ export async function settleWithin({ run, clock, timeoutMs }) {
24
+ const settlement = Promise.resolve().then(run)
25
+ .then(() => ({ state: 'resolved' }), error => ({ state: 'rejected', reason: describe(error) }));
26
+ const timer = clock.sleep({ ms: timeoutMs }).then(() => 'timeout');
27
+ const first = await Promise.race([settlement, timer]);
28
+ return first === 'timeout' ? { state: 'timed-out', settlement } : first;
29
+ }
30
+ /** True when any live holder record (this process included) lists the partition as intended or held. */
31
+ export function listedByHolder({ holders, name }, _optional = {}) {
32
+ return holders.some(h => h.intents.includes(name) || h.held.includes(name));
33
+ }
34
+ /**
35
+ * Renames one cache folder of an unheld partition into the aside folder, under the writer lock with the
36
+ * target fence on this partition and a fresh holder read after it. The partition pass deletes it later,
37
+ * outside the lock, by its cache-only aside name. Sign-in stores in the partition are never touched.
38
+ */
39
+ export async function renameCacheAside({ partition, sub, interlock, fs }, { asideDirName = DEFAULT_ASIDE_DIR_NAME } = {}) {
40
+ const asideDir = path.join(path.dirname(partition.dir), asideDirName);
41
+ const aside = path.join(asideDir, `${partition.name}.${sub}.${interlock.newToken()}`);
42
+ try {
43
+ await interlock.writer.setTarget({ target: partition.name });
44
+ const holders = await interlock.readHoldersStrict();
45
+ if (holders.state === 'unknown')
46
+ return { state: 'pending', reason: 'holders-unknown' };
47
+ if (listedByHolder({ holders: holders.value, name: partition.name }))
48
+ return { state: 'pending', reason: 'held' };
49
+ await interlock.writer.assertHeld();
50
+ await fs.mkdir({ path: asideDir });
51
+ await fs.rename({ oldPath: path.join(partition.dir, sub), newPath: aside });
52
+ return { state: 'cleared', aside };
53
+ }
54
+ catch (error) {
55
+ const errno = code(error);
56
+ if (errno === 'ENOENT')
57
+ return { state: 'pending', reason: 'missing' };
58
+ return { state: 'pending', reason: errno !== undefined && BUSY.includes(errno) ? 'busy' : 'failed' };
59
+ }
60
+ }
61
+ async function clearAtOpen(interlock, timeoutMs) {
62
+ const outcome = await settleWithin({ run: () => interlock.session.clearCache(), clock: interlock.clock, timeoutMs });
63
+ if (outcome.state === 'resolved')
64
+ return { state: 'cleared', aside: null };
65
+ if (outcome.state === 'rejected')
66
+ return { state: 'pending', reason: 'failed' };
67
+ return { state: 'pending', reason: 'timeout', settlement: outcome.settlement };
68
+ }
69
+ /**
70
+ * GO cap: the switch bounds the cache, so one clear brings an old oversized cache under it and is latched
71
+ * per profile and cap. NO-GO cap with GO clear evidence: periodic enforcement at `capBytes × multiplier`,
72
+ * re-measured every boot and open and never latched. Periodic enforcement is not a disk bound: between
73
+ * checks Chromium may grow the cache without limit, a busy or held partition is skipped, and a site left
74
+ * open never reaches the next check, so savings are reported as periodic and no cap is claimed.
75
+ */
76
+ function planClear(evidence, capBytes, multiplier) {
77
+ return evidence.cap === 'go' ? { mode: 'one-time', threshold: capBytes } : { mode: 'periodic', threshold: capBytes * multiplier };
78
+ }
79
+ /** A marker that cannot be read counts as not done: clearing a re-creatable cache twice is harmless. */
80
+ async function alreadyDone(marker, name, capBytes) {
81
+ try {
82
+ const mark = await marker.readCacheClear({ partition: name });
83
+ return mark.state === 'done' && mark.capBytes === capBytes;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ /** Marker writes never block boot or open; a lost write leaves the partition pending, never falsely done. */
90
+ async function mark(required, mode, outcome) {
91
+ if (mode !== 'one-time')
92
+ return;
93
+ try {
94
+ await required.marker.markCacheClear({ partition: required.partition.name, capBytes: required.capBytes, outcome });
95
+ }
96
+ catch { /* stays pending: the next start re-measures */ }
97
+ }
98
+ /**
99
+ * Clears one partition's HTTP `Cache` when it is over the threshold. Boot renames the folder of an unheld
100
+ * partition aside; open awaits the measured `session.clearCache()` before first use. Done is written only
101
+ * after that clear succeeded or a measurement verified the cache is under the threshold; busy, held,
102
+ * unmeasured, failed and timed-out clears stay pending and are retried next start.
103
+ * @complexity O(1) fs operations plus one measurement.
104
+ */
105
+ export async function clearPartitionCacheOnce(required, { fallbackMultiplier = 2, timeoutMs = 10_000, asideDirName = DEFAULT_ASIDE_DIR_NAME } = {}) {
106
+ const { partition, evidence, capBytes } = required;
107
+ if (evidence.clearOps.clearCache !== 'go')
108
+ return evidenceSkip(evidence.clearOps.clearCache);
109
+ const plan = planClear(evidence, capBytes, fallbackMultiplier);
110
+ if (plan.mode === 'one-time' && (await alreadyDone(required.marker, partition.name, capBytes)))
111
+ return { state: 'already-done' };
112
+ const size = await required.measure({ path: path.join(partition.dir, 'Cache') }).catch((error) => ({ state: 'unknown', reason: describe(error) }));
113
+ if (size.state === 'unknown') {
114
+ await mark(required, plan.mode, { state: 'pending', reason: 'unmeasured' });
115
+ return { state: 'pending', reason: 'unmeasured' };
116
+ }
117
+ if (size.bytes <= plan.threshold) {
118
+ await mark(required, plan.mode, { state: 'done' });
119
+ return { state: 'below-threshold', mode: plan.mode, bytes: size.bytes };
120
+ }
121
+ return actOnOversizedCache(required, { mode: plan.mode, bytes: size.bytes }, { timeoutMs, asideDirName });
122
+ }
123
+ async function actOnOversizedCache(required, { mode, bytes }, { timeoutMs, asideDirName }) {
124
+ const { partition, interlock } = required;
125
+ const act = interlock.phase === 'boot'
126
+ ? await renameCacheAside({ partition, sub: 'Cache', interlock, fs: required.fs }, { asideDirName })
127
+ : await clearAtOpen(interlock, timeoutMs);
128
+ if (act.state === 'cleared') {
129
+ await mark(required, mode, { state: 'done' });
130
+ return { state: 'cleared', mode, bytes, aside: act.aside };
131
+ }
132
+ await mark(required, mode, { state: 'pending', reason: act.reason });
133
+ return act;
134
+ }
135
+ /** The managed, contained partition folders under the root; `null` when the root cannot be read for sure. */
136
+ async function listManaged(pass) {
137
+ const root = await pass.ctx.resolveRoot();
138
+ if (root.state === 'absent')
139
+ return { root: '', names: [] };
140
+ if (root.state !== 'ok')
141
+ return null;
142
+ const list = await listCandidates({ root: root.root, fs: pass.required.fs, isManaged: pass.required.interlock.isManaged });
143
+ return list.state === 'ok' ? { root: root.root, names: list.candidates.map(c => c.name) } : null;
144
+ }
145
+ /**
146
+ * Pending is durable before the launch version moves: a crash between the two re-detects the update next
147
+ * start and re-adds the same partitions (idempotent), whereas the reverse order could lose the clears.
148
+ */
149
+ async function recordUpdate(pass, pending, names) {
150
+ const next = [...new Set([...pending, ...names])];
151
+ try {
152
+ await pass.required.marker.writeCodeCachePending({ forVersion: pass.required.version, pending: next });
153
+ await pass.required.marker.writeLaunchVersion({ version: pass.required.version });
154
+ return next;
155
+ }
156
+ catch {
157
+ return null;
158
+ }
159
+ }
160
+ /** Renames `Code Cache` of each pending, unheld partition; busy and held ones stay pending for the next start. */
161
+ async function clearPending(pass, root, pending, present) {
162
+ const { interlock, fs, marker } = pass.required;
163
+ const boot = { phase: 'boot', writer: pass.ctx, readHoldersStrict: interlock.readHoldersStrict, newToken: interlock.newToken };
164
+ const cleared = [], kept = [];
165
+ for (const name of pending) {
166
+ // A pending partition that is gone, or no longer a contained managed folder, has nothing to clear here.
167
+ if (!present.has(name)) {
168
+ await marker.settleCodeCache({ partition: name }).catch(() => { });
169
+ continue;
170
+ }
171
+ const result = await renameCacheAside({ partition: { name, dir: path.join(root, name) }, sub: 'Code Cache', interlock: boot, fs }, { asideDirName: pass.asideDirName });
172
+ // ENOENT: no code cache from the old version remains, which is what the update clear is for.
173
+ if (result.state === 'pending' && result.reason !== 'missing') {
174
+ kept.push({ partition: name, reason: result.reason });
175
+ continue;
176
+ }
177
+ await marker.settleCodeCache({ partition: name }).catch(() => { });
178
+ cleared.push(name);
179
+ }
180
+ return { cleared, kept };
181
+ }
182
+ async function codeCacheUnderWriter(pass) {
183
+ const { marker, evidence, version, isUpdate } = pass.required;
184
+ const read = await marker.readCodeCache();
185
+ // An unreadable record counts as an update launch: strictly more clears of a re-creatable cache.
186
+ const state = read.state === 'ok' ? read : { lastLaunchVersion: null, pending: [] };
187
+ const update = isUpdate || state.lastLaunchVersion !== version;
188
+ const managed = await listManaged(pass);
189
+ if (!managed)
190
+ return { state: 'skipped', reason: 'root-unknown' };
191
+ const pending = update ? await recordUpdate(pass, state.pending, managed.names) : state.pending;
192
+ if (!pending)
193
+ return { state: 'skipped', reason: 'marker-failed' };
194
+ if (evidence.clearOps.clearCodeCaches !== 'go')
195
+ return evidenceSkip(evidence.clearOps.clearCodeCaches);
196
+ const { cleared, kept } = await clearPending(pass, managed.root, pending, new Set(managed.names));
197
+ return { state: 'ran', update, cleared, kept };
198
+ }
199
+ /**
200
+ * Boot: on an update launch (flag or version change) every managed partition's `Code Cache` becomes
201
+ * pending; then, under the writer lock, each pending partition no holder lists is renamed aside. The
202
+ * rename runs only with `'go'` evidence for the code-cache clear. Never throws.
203
+ * @complexity O(partitions) fs operations.
204
+ */
205
+ export async function clearCodeCacheOnUpdate(required, { asideDirName = DEFAULT_ASIDE_DIR_NAME } = {}) {
206
+ try {
207
+ const outcome = await required.interlock.withPartitionWriter({ run: ctx => codeCacheUnderWriter({ required, ctx, asideDirName }) });
208
+ return outcome.state === 'ran' ? outcome.value : { state: 'skipped', reason: 'writer-busy' };
209
+ }
210
+ catch {
211
+ return { state: 'skipped', reason: 'writer-busy' };
212
+ }
213
+ }
214
+ /**
215
+ * Open-time code-cache clear. It runs only as the interlock's `openMaintenance` hook (step 2.5), which
216
+ * already found no other holder and has not yet marked the partition held, so no window or guest uses the
217
+ * session while it clears; it does no holders check of its own. A second window of a held site must skip
218
+ * it: that window shares the live session, whose pages are already running and may be compiling into the
219
+ * code cache, and the clear would race them; the interlock returns `already-held` without calling it.
220
+ * Success is marked only when `clearCodeCaches` resolves; a timeout is reported apart from the settlement.
221
+ * @complexity O(1) plus one measurement.
222
+ */
223
+ export async function maybeClearCodeCacheAtOpen({ session, measure, evidence, marker, clock }, { maxBytes = 64 * 2 ** 20, timeoutMs = 10_000 } = {}) {
224
+ if (evidence.clearOps.clearCodeCaches !== 'go')
225
+ return evidenceSkip(evidence.clearOps.clearCodeCaches);
226
+ const size = await measure().catch((error) => ({ state: 'unknown', reason: describe(error) }));
227
+ if (size.state === 'unknown')
228
+ return { state: 'skipped', reason: 'unmeasured' };
229
+ if (size.bytes <= maxBytes)
230
+ return { state: 'below-threshold', bytes: size.bytes };
231
+ const outcome = await settleWithin({ run: () => session.clearCodeCaches({}), clock, timeoutMs });
232
+ if (outcome.state === 'rejected')
233
+ return { state: 'pending', reason: 'failed' };
234
+ if (outcome.state === 'timed-out')
235
+ return { state: 'pending', reason: 'timeout', settlement: outcome.settlement };
236
+ await marker.settle().catch(() => { });
237
+ return { state: 'cleared', bytes: size.bytes };
238
+ }
239
+ //# sourceMappingURL=cache-maintenance.js.map
@@ -0,0 +1,54 @@
1
+ import type { ReadPresenceStrictInput } from '../updates/instance-presence-strict.js';
2
+ /** Every claim reader answers `ok` with a complete value or `unknown`; there is no partial answer. */
3
+ export type StrictRead<T> = {
4
+ state: 'ok';
5
+ value: T;
6
+ } | {
7
+ state: 'unknown';
8
+ reason: string;
9
+ };
10
+ /** A host-supplied set of partition directory names that must be kept (tracked list, catalog, ...). */
11
+ export interface PartitionClaimSource {
12
+ name: string;
13
+ read(): Promise<StrictRead<readonly string[]>>;
14
+ }
15
+ /** A host-supplied set of other live instances of the same profile (for example updater presence). */
16
+ export interface InstanceClaimSource {
17
+ name: string;
18
+ read(): Promise<StrictRead<readonly {
19
+ pid: number;
20
+ }[]>>;
21
+ }
22
+ export interface PartitionClaimSources {
23
+ partitions: readonly PartitionClaimSource[];
24
+ instances: readonly InstanceClaimSource[];
25
+ }
26
+ export interface HolderClaims {
27
+ pid: number;
28
+ intents: readonly string[];
29
+ held: readonly string[];
30
+ }
31
+ export type ClaimsRead = {
32
+ state: 'ok';
33
+ claimed: string[];
34
+ otherInstances: number[];
35
+ } | {
36
+ state: 'unknown';
37
+ reasons: string[];
38
+ };
39
+ /** Adapt the strict updater-presence reader as an instance claim source. @complexity O(n) records. */
40
+ export declare function presenceClaimSource({ directory, fs, liveness }: ReadPresenceStrictInput, { name }?: {
41
+ name?: string;
42
+ }): InstanceClaimSource;
43
+ /**
44
+ * Union of every live holder's intents and held partitions (this process included), every partition
45
+ * source, and every other live instance. One `unknown` source makes the whole answer `unknown`:
46
+ * an unknown claim never authorizes mutation, so it must not be narrowed to "no claim".
47
+ * @complexity O(total claims).
48
+ */
49
+ export declare function readClaimsStrict({ selfPid, holders, sources }: {
50
+ selfPid: number;
51
+ holders: () => Promise<StrictRead<readonly HolderClaims[]>>;
52
+ sources: PartitionClaimSources;
53
+ }, _optional?: Record<string, never>): Promise<ClaimsRead>;
54
+ //# sourceMappingURL=claim-sources.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { readPresenceStrict } from '../updates/instance-presence-strict.js';
2
+ /** Adapt the strict updater-presence reader as an instance claim source. @complexity O(n) records. */
3
+ export function presenceClaimSource({ directory, fs, liveness }, { name = 'presence' } = {}) {
4
+ return { name, read: async () => readPresenceStrict({ directory, fs, liveness }) };
5
+ }
6
+ async function tallySource(tally, name, read, add) {
7
+ const result = await read();
8
+ if (result.state === 'unknown')
9
+ tally.reasons.push(`${name}: ${result.reason}`);
10
+ else
11
+ result.value.forEach(add);
12
+ }
13
+ /**
14
+ * Union of every live holder's intents and held partitions (this process included), every partition
15
+ * source, and every other live instance. One `unknown` source makes the whole answer `unknown`:
16
+ * an unknown claim never authorizes mutation, so it must not be narrowed to "no claim".
17
+ * @complexity O(total claims).
18
+ */
19
+ export async function readClaimsStrict({ selfPid, holders, sources }, _optional = {}) {
20
+ const tally = { reasons: [], claimed: new Set(), others: new Set() };
21
+ const addInstance = (pid) => { if (pid !== selfPid)
22
+ tally.others.add(pid); };
23
+ await tallySource(tally, 'holders', holders, holder => {
24
+ for (const partition of [...holder.intents, ...holder.held])
25
+ tally.claimed.add(partition);
26
+ addInstance(holder.pid);
27
+ });
28
+ for (const source of sources.partitions)
29
+ await tallySource(tally, source.name, () => source.read(), p => tally.claimed.add(p));
30
+ for (const source of sources.instances)
31
+ await tallySource(tally, source.name, () => source.read(), ({ pid }) => addInstance(pid));
32
+ if (tally.reasons.length > 0)
33
+ return { state: 'unknown', reasons: tally.reasons };
34
+ return { state: 'ok', claimed: [...tally.claimed].sort(), otherInstances: [...tally.others].sort((a, b) => a - b) };
35
+ }
36
+ //# sourceMappingURL=claim-sources.js.map