@songsid/agend 2.4.0-beta.16 → 2.4.0-beta.18

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 (172) hide show
  1. package/dist/auth-api.js +2 -0
  2. package/dist/auth-api.js.map +1 -1
  3. package/dist/backend/claude-code.d.ts +10 -1
  4. package/dist/backend/claude-code.js +7 -2
  5. package/dist/backend/claude-code.js.map +1 -1
  6. package/dist/backend/claude-transcript-errors.d.ts +4 -0
  7. package/dist/backend/claude-transcript-errors.js +5 -1
  8. package/dist/backend/claude-transcript-errors.js.map +1 -1
  9. package/dist/backend/types.d.ts +6 -0
  10. package/dist/backend/types.js.map +1 -1
  11. package/dist/build-provenance.json +1 -1
  12. package/dist/claude-credential-launch.d.ts +1 -0
  13. package/dist/claude-credential-launch.js +13 -2
  14. package/dist/claude-credential-launch.js.map +1 -1
  15. package/dist/claude-credential-vault.d.ts +7 -1
  16. package/dist/claude-credential-vault.js +26 -1
  17. package/dist/claude-credential-vault.js.map +1 -1
  18. package/dist/claude-request-observation.d.ts +7 -0
  19. package/dist/claude-request-observation.js +26 -0
  20. package/dist/claude-request-observation.js.map +1 -0
  21. package/dist/cli-audited.js +11 -8
  22. package/dist/cli-audited.js.map +1 -1
  23. package/dist/daemon.d.ts +8 -0
  24. package/dist/daemon.js +68 -13
  25. package/dist/daemon.js.map +1 -1
  26. package/dist/fleet-context.d.ts +1 -0
  27. package/dist/fleet-manager.d.ts +28 -0
  28. package/dist/fleet-manager.js +222 -10
  29. package/dist/fleet-manager.js.map +1 -1
  30. package/dist/fleet-windows-runtime.d.ts +1 -1
  31. package/dist/fleet-windows-runtime.js +1 -1
  32. package/dist/fleet-windows-runtime.js.map +1 -1
  33. package/dist/fleet-yaml-stringify.d.ts +3 -0
  34. package/dist/fleet-yaml-stringify.js +79 -0
  35. package/dist/fleet-yaml-stringify.js.map +1 -0
  36. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +17 -3
  37. package/dist/host-monitoring-alert-policy.d.ts +71 -0
  38. package/dist/host-monitoring-alert-policy.js +150 -0
  39. package/dist/host-monitoring-alert-policy.js.map +1 -0
  40. package/dist/host-monitoring-alert-resources.d.ts +11 -0
  41. package/dist/host-monitoring-alert-resources.js +16 -0
  42. package/dist/host-monitoring-alert-resources.js.map +1 -0
  43. package/dist/host-monitoring-alert-settings.d.ts +14 -0
  44. package/dist/host-monitoring-alert-settings.js +63 -0
  45. package/dist/host-monitoring-alert-settings.js.map +1 -0
  46. package/dist/host-monitoring-alert-store.d.ts +49 -0
  47. package/dist/host-monitoring-alert-store.js +228 -0
  48. package/dist/host-monitoring-alert-store.js.map +1 -0
  49. package/dist/host-monitoring-alert-text.d.ts +7 -0
  50. package/dist/host-monitoring-alert-text.js +10 -0
  51. package/dist/host-monitoring-alert-text.js.map +1 -0
  52. package/dist/host-monitoring-alerts.d.ts +76 -0
  53. package/dist/host-monitoring-alerts.js +261 -0
  54. package/dist/host-monitoring-alerts.js.map +1 -0
  55. package/dist/host-monitoring-config.d.ts +2 -1
  56. package/dist/host-monitoring-config.js +8 -3
  57. package/dist/host-monitoring-config.js.map +1 -1
  58. package/dist/host-monitoring-footprint-policy.d.ts +45 -0
  59. package/dist/host-monitoring-footprint-policy.js +150 -0
  60. package/dist/host-monitoring-footprint-policy.js.map +1 -0
  61. package/dist/host-monitoring-footprint.d.ts +42 -0
  62. package/dist/host-monitoring-footprint.js +169 -0
  63. package/dist/host-monitoring-footprint.js.map +1 -0
  64. package/dist/host-monitoring-history-files.d.ts +2 -0
  65. package/dist/host-monitoring-history-files.js +16 -0
  66. package/dist/host-monitoring-history-files.js.map +1 -0
  67. package/dist/host-monitoring-history-policy.d.ts +57 -0
  68. package/dist/host-monitoring-history-policy.js +107 -0
  69. package/dist/host-monitoring-history-policy.js.map +1 -0
  70. package/dist/host-monitoring-history-store.d.ts +52 -0
  71. package/dist/host-monitoring-history-store.js +178 -0
  72. package/dist/host-monitoring-history-store.js.map +1 -0
  73. package/dist/host-monitoring-history-worker.d.ts +1 -0
  74. package/dist/host-monitoring-history-worker.js +66 -0
  75. package/dist/host-monitoring-history-worker.js.map +1 -0
  76. package/dist/host-monitoring-history.d.ts +80 -0
  77. package/dist/host-monitoring-history.js +301 -0
  78. package/dist/host-monitoring-history.js.map +1 -0
  79. package/dist/host-monitoring-platform.d.ts +73 -0
  80. package/dist/host-monitoring-platform.js +273 -0
  81. package/dist/host-monitoring-platform.js.map +1 -0
  82. package/dist/host-monitoring-process-identity.d.ts +8 -0
  83. package/dist/host-monitoring-process-identity.js +81 -0
  84. package/dist/host-monitoring-process-identity.js.map +1 -0
  85. package/dist/host-monitoring-runtime.d.ts +42 -0
  86. package/dist/host-monitoring-runtime.js +95 -0
  87. package/dist/host-monitoring-runtime.js.map +1 -0
  88. package/dist/host-monitoring-settings-store.d.ts +5 -0
  89. package/dist/host-monitoring-settings-store.js +49 -0
  90. package/dist/host-monitoring-settings-store.js.map +1 -0
  91. package/dist/host-monitoring.d.ts +108 -0
  92. package/dist/host-monitoring.js +157 -0
  93. package/dist/host-monitoring.js.map +1 -0
  94. package/dist/instance-lifecycle.js +2 -2
  95. package/dist/instance-lifecycle.js.map +1 -1
  96. package/dist/needs-you-hub.d.ts +1 -0
  97. package/dist/needs-you-hub.js +1 -0
  98. package/dist/needs-you-hub.js.map +1 -1
  99. package/dist/needs-you.d.ts +3 -2
  100. package/dist/needs-you.js +1 -0
  101. package/dist/needs-you.js.map +1 -1
  102. package/dist/public-web-gateway.js +11 -1
  103. package/dist/public-web-gateway.js.map +1 -1
  104. package/dist/runtime-cli-install.js +17 -16
  105. package/dist/runtime-cli-install.js.map +1 -1
  106. package/dist/settings-api.d.ts +5 -0
  107. package/dist/settings-api.js +70 -7
  108. package/dist/settings-api.js.map +1 -1
  109. package/dist/settings-baseline.d.ts +1 -0
  110. package/dist/settings-baseline.js +6 -4
  111. package/dist/settings-baseline.js.map +1 -1
  112. package/dist/settings-change.js +8 -0
  113. package/dist/settings-change.js.map +1 -1
  114. package/dist/settings-effect.d.ts +4 -0
  115. package/dist/settings-effect.js +25 -4
  116. package/dist/settings-effect.js.map +1 -1
  117. package/dist/topic-commands.js +4 -0
  118. package/dist/topic-commands.js.map +1 -1
  119. package/dist/transcript-monitor.d.ts +1 -0
  120. package/dist/transcript-monitor.js +18 -0
  121. package/dist/transcript-monitor.js.map +1 -1
  122. package/dist/ui/accounts-view.js +7 -5
  123. package/dist/ui/chat-store.js +21 -4
  124. package/dist/ui/claude-credentials.js +12 -1
  125. package/dist/ui/fleet-office-pack.js +2 -2
  126. package/dist/ui/fleet-office-play.js +142 -3
  127. package/dist/ui/fleet-office-skin.js +67 -2
  128. package/dist/ui/fleet-office-store.js +41 -0
  129. package/dist/ui/fleet-office-zones.js +15 -8
  130. package/dist/ui/fleet-office.js +126 -21
  131. package/dist/ui/host-alerts.js +23 -0
  132. package/dist/ui/host-footprint.js +17 -0
  133. package/dist/ui/host-health-model.js +42 -0
  134. package/dist/ui/host-health.js +79 -0
  135. package/dist/ui/host-time.js +5 -0
  136. package/dist/ui/panel-chat.js +101 -43
  137. package/dist/ui/panel-fleet.js +24 -11
  138. package/dist/ui/panel-hub.js +5 -1
  139. package/dist/ui/panel-needs.js +27 -16
  140. package/dist/ui/panel-settings.js +4 -3
  141. package/dist/ui/search-dialog.js +8 -1
  142. package/dist/ui/settings-capabilities.js +2 -0
  143. package/dist/ui/settings-host-alerts.js +22 -0
  144. package/dist/ui/settings-host-monitoring.js +37 -18
  145. package/dist/ui/settings-registry.js +4 -1
  146. package/dist/ui/shared/accounts.css +8 -4
  147. package/dist/ui/shared/agent-sheet.js +5 -2
  148. package/dist/ui/shared/app-i18n.js +2 -2
  149. package/dist/ui/shared/app-route.js +1 -1
  150. package/dist/ui/shared/app.css +87 -9
  151. package/dist/ui/shared/app.js +1 -0
  152. package/dist/ui/shared/chat-render.js +24 -9
  153. package/dist/ui/shared/chat-strings.js +4 -4
  154. package/dist/ui/shared/chat-thread.js +45 -11
  155. package/dist/ui/shared/instance-nav.js +47 -5
  156. package/dist/ui/shared/jump-idle.js +36 -0
  157. package/dist/ui/shared/theme.js +6 -2
  158. package/dist/ui/shared/ui-menu.js +17 -11
  159. package/dist/web-api.d.ts +3 -0
  160. package/dist/web-api.js +249 -4
  161. package/dist/web-api.js.map +1 -1
  162. package/dist/web-chat-history.d.ts +47 -2
  163. package/dist/web-chat-history.js +149 -11
  164. package/dist/web-chat-history.js.map +1 -1
  165. package/dist/web-guest-access.js +4 -4
  166. package/dist/web-guest-access.js.map +1 -1
  167. package/dist/web-shell-routes.d.ts +1 -1
  168. package/dist/web-shell-routes.js +1 -1
  169. package/dist/web-shell-routes.js.map +1 -1
  170. package/dist/web-upload.d.ts +1 -1
  171. package/dist/web-upload.js.map +1 -1
  172. package/package.json +1 -1
@@ -0,0 +1,169 @@
1
+ import { bindLinuxRootIdentities } from './host-monitoring-process-identity.js';
2
+ import { spawn } from './child-process.js';
3
+ import { lstat } from 'node:fs/promises';
4
+ import { cpus } from 'node:os';
5
+ import { FootprintAttribution, parseFootprintProcesses, FOOTPRINT_BYTES, FOOTPRINT_ROOTS } from './host-monitoring-footprint-policy.js';
6
+ /** Separate from disk probes: fixed columns, no command line, no shell, one bounded pipe. */
7
+ export const runFootprintProcesses = () => {
8
+ let result, closed, child, ended = false, bytes = 0, parts = [];
9
+ const answer = new Promise(resolve => result = resolve), stopped = new Promise(resolve => closed = resolve);
10
+ const finish = (value) => { if (ended)
11
+ return; ended = true; result(value); };
12
+ const cancel = () => { finish(null); child?.kill('SIGKILL'); };
13
+ const timer = setTimeout(cancel, 1500);
14
+ timer.unref();
15
+ try {
16
+ child = spawn('/bin/ps', ['-ww', '-A', '-o', 'pid=,ppid=,rss=,time=,lstart='], { env: { PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LC_ALL: 'C', LANG: 'C', TZ: 'UTC' }, stdio: ['ignore', 'pipe', 'ignore'] });
17
+ child.stdout.on('data', (chunk) => { bytes += chunk.length; if (bytes > FOOTPRINT_BYTES) {
18
+ parts = [];
19
+ cancel();
20
+ }
21
+ else if (!ended)
22
+ parts.push(chunk); });
23
+ child.on('error', () => finish(null));
24
+ child.on('close', code => { clearTimeout(timer); finish(code === 0 ? Buffer.concat(parts).toString('utf8') : null); parts = []; closed(); });
25
+ }
26
+ catch {
27
+ clearTimeout(timer);
28
+ finish(null);
29
+ closed();
30
+ }
31
+ return { result: answer, stopped, cancel };
32
+ };
33
+ /** A single 60-second flight. Logical timeout never releases physical process/stat ownership. */
34
+ export class HostFootprint {
35
+ options;
36
+ enabled = false;
37
+ timer = null;
38
+ flight = null;
39
+ cancel = null;
40
+ epoch = 0;
41
+ policy = new FootprintAttribution();
42
+ value = { enabled: false, status: 'off', reading: null };
43
+ constructor(options) {
44
+ this.options = options;
45
+ }
46
+ snapshot() { const copy = structuredClone(this.value); if (copy.status === 'ok' && copy.reading && (this.options.now ?? Date.now)() - copy.reading.sampledAt >= 120000)
47
+ copy.status = 'stale'; return copy; }
48
+ configure(enabled) {
49
+ if (enabled === this.enabled)
50
+ return;
51
+ this.enabled = enabled;
52
+ this.epoch++;
53
+ if (!enabled) {
54
+ if (this.timer)
55
+ clearInterval(this.timer);
56
+ this.timer = null;
57
+ this.cancel?.();
58
+ this.value = { enabled: false, status: this.flight ? 'stopping' : 'off', reading: null };
59
+ this.policy.reset();
60
+ return;
61
+ }
62
+ this.value = { enabled: true, status: 'starting', reading: null };
63
+ this.timer = setInterval(() => this.sample(), 60000);
64
+ this.timer.unref();
65
+ this.sample();
66
+ }
67
+ async stop() { this.configure(false); await this.flight; }
68
+ sample() {
69
+ if (!this.enabled || this.flight)
70
+ return;
71
+ const epoch = this.epoch, wall = (this.options.now ?? Date.now)(), mono = (this.options.monotonic ?? (() => performance.now()))();
72
+ let inputs;
73
+ try {
74
+ inputs = this.options.roots();
75
+ if (inputs.length > FOOTPRINT_ROOTS)
76
+ throw Error();
77
+ }
78
+ catch {
79
+ this.value = { enabled: true, status: 'unavailable', reading: null, reason: 'root_limit' };
80
+ return;
81
+ }
82
+ let probe;
83
+ try {
84
+ probe = (this.options.runner ?? runFootprintProcesses)();
85
+ }
86
+ catch {
87
+ this.value = { enabled: true, status: 'unavailable', reading: null, reason: 'process_unavailable' };
88
+ return;
89
+ }
90
+ let expired = false;
91
+ const timeout = setTimeout(() => { expired = true; probe.cancel(); if (this.enabled && epoch === this.epoch)
92
+ this.value = { enabled: true, status: 'unavailable', reading: null, reason: 'sample_timeout' }; }, 2000);
93
+ timeout.unref();
94
+ this.cancel = () => { expired = true; probe.cancel(); };
95
+ const task = (async () => {
96
+ try {
97
+ const processes = parseFootprintProcesses(await probe.result);
98
+ if (!processes || expired)
99
+ throw Error();
100
+ // Injected inventories stay pure unless they explicitly provide an identity reader. Native Linux always binds.
101
+ const binder = this.options.identities ?? (!this.options.runner && process.platform === 'linux' ? bindLinuxRootIdentities : undefined);
102
+ const rejected = binder ? await binder(processes, inputs, () => !expired && this.enabled && epoch === this.epoch) : new Set();
103
+ if (expired || !this.enabled || epoch !== this.epoch)
104
+ return;
105
+ // Metadata only, at most four exact known files per root; eight asynchronous calls at a time.
106
+ const metadata = new Map(), inodes = new Map();
107
+ const files = inputs.filter(root => root.pid > 1 && !rejected.has(root.pid)).flatMap(root => root.files.slice(0, 4).map(path => ({ root: root.id, path }))), seenPaths = new Set();
108
+ let cursor = 0;
109
+ for (const root of inputs)
110
+ metadata.set(root.id, 0);
111
+ await Promise.all(Array.from({ length: Math.min(8, files.length) }, async () => { while (cursor < files.length && !expired) {
112
+ const item = files[cursor++];
113
+ try {
114
+ const info = await lstat(item.path);
115
+ if (!info.isFile() || info.isSymbolicLink())
116
+ throw Error();
117
+ const key = `${info.dev}:${info.ino}`;
118
+ const owners = inodes.get(key) ?? new Set();
119
+ owners.add(item.root);
120
+ inodes.set(key, owners);
121
+ if (!seenPaths.has(key)) {
122
+ seenPaths.add(key);
123
+ metadata.set(item.root, metadata.get(item.root) === null ? null : metadata.get(item.root) + info.size);
124
+ }
125
+ else
126
+ metadata.set(item.root, null);
127
+ }
128
+ catch (error) {
129
+ if (error.code !== 'ENOENT')
130
+ metadata.set(item.root, null);
131
+ }
132
+ } }));
133
+ if (expired || !this.enabled || epoch !== this.epoch)
134
+ return;
135
+ const currentRoots = this.options.roots();
136
+ if (currentRoots.length > FOOTPRINT_ROOTS)
137
+ throw Error('root_limit');
138
+ const current = new Map(currentRoots.map(root => [root.id, root]));
139
+ const roots = inputs.map(root => { const live = current.get(root.id); return !rejected.has(root.pid) && live && live.owner === root.owner && live.pid === root.pid ? root : { ...root, pid: 0 }; });
140
+ const reading = this.policy.sample(processes, roots, this.options.fleetPid ?? process.pid, wall, mono, (this.options.logicalCpus ?? (() => cpus().length))(), [...inputs.map(root => root.pid), ...currentRoots.map(root => root.pid)]);
141
+ for (const owners of inodes.values())
142
+ if (owners.size > 1)
143
+ for (const id of owners)
144
+ metadata.set(id, null);
145
+ for (const row of reading.rows)
146
+ row.managedBytes = row.rssBytes === null ? null : metadata.get(row.id) ?? null;
147
+ this.value = { enabled: true, status: 'ok', reading };
148
+ this.options.changed?.();
149
+ }
150
+ catch {
151
+ if (this.enabled && epoch === this.epoch) {
152
+ this.policy.reset();
153
+ this.value = { enabled: true, status: 'unavailable', reading: null, reason: 'process_unavailable' };
154
+ }
155
+ }
156
+ finally {
157
+ await probe.stopped;
158
+ clearTimeout(timeout);
159
+ }
160
+ })();
161
+ this.flight = task;
162
+ void task.then(() => { if (this.flight !== task)
163
+ return; this.flight = null; this.cancel = null; if (!this.enabled)
164
+ this.value = { enabled: false, status: 'off', reading: null };
165
+ else if (epoch !== this.epoch)
166
+ this.sample(); }, () => { });
167
+ }
168
+ }
169
+ //# sourceMappingURL=host-monitoring-footprint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-monitoring-footprint.js","sourceRoot":"","sources":["../src/host-monitoring-footprint.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,uBAAuB,EAAC,MAAM,uCAAuC,CAAC;AAC9E,OAAO,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E,GAAC,IAAG,IAAI,CAAC,MAAM,KAAG,IAAI;YAAC,OAAO,CAAA,IAAI,CAAC,MAAM,GAAC,IAAI,CAAC,CAAA,IAAI,CAAC,MAAM,GAAC,IAAI,CAAC,CAAA,IAAG,CAAC,IAAI,CAAC,OAAO;YAAC,IAAI,CAAC,KAAK,GAAC,EAAC,OAAO,EAAC,KAAK,EAAC,MAAM,EAAC,KAAK,EAAC,OAAO,EAAC,IAAI,EAAC,CAAC;aAAK,IAAG,KAAK,KAAG,IAAI,CAAC,KAAK;YAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAA,CAAC,EAAC,GAAE,EAAE,GAAuD,CAAC,CAAC,CAAC;IACnQ,CAAC;CACD"}
@@ -0,0 +1,2 @@
1
+ export declare const historyFiles: (path: string) => string[];
2
+ export declare function cleanupHistory(path: string, remove?: (path: string) => Promise<void>): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { unlink } from 'node:fs/promises';
2
+ export const historyFiles = (path) => ['', '-wal', '-shm', '-journal', '.incidents', '.incidents.tmp'].map(s => path + s);
3
+ export async function cleanupHistory(path, remove = unlink) {
4
+ let failed = false;
5
+ for (const name of historyFiles(path))
6
+ try {
7
+ await remove(name);
8
+ }
9
+ catch (error) {
10
+ if (error.code !== 'ENOENT')
11
+ failed = true;
12
+ }
13
+ if (failed)
14
+ throw Error('history_cleanup_failed');
15
+ }
16
+ //# sourceMappingURL=host-monitoring-history-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-monitoring-history-files.js","sourceRoot":"","sources":["../src/host-monitoring-history-files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAW,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,gBAAgB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA,EAAE,CAAA,IAAI,GAAC,CAAC,CAAC,CAAC;AAC7H,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAW,EAAC,MAAM,GAA8B,MAAM;IACzF,IAAI,MAAM,GAAC,KAAK,CAAC;IACjB,KAAI,MAAM,IAAI,IAAI,YAAY,CAAC,IAAI,CAAC;QAAE,IAAI,CAAC;YAAA,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC;QAAA,CAAC;QAAC,OAAM,KAAK,EAAE,CAAC;YAAA,IAAI,KAA+B,CAAC,IAAI,KAAG,QAAQ;gBAAC,MAAM,GAAC,IAAI,CAAC;QAAA,CAAC;IAC/I,IAAG,MAAM;QAAC,MAAM,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,57 @@
1
+ import type { HostHealthSnapshot } from './host-monitoring.js';
2
+ export declare const HISTORY_BYTES: number;
3
+ export declare const HISTORY_PAGE_BYTES = 4096;
4
+ export declare const HISTORY_SHM_BUDGET: number;
5
+ export declare const HISTORY_RAW_MS: number;
6
+ export declare const HISTORY_ROLLUP_MS: number;
7
+ export declare const HISTORY_BUCKET_MS: number;
8
+ export declare const HISTORY_MAX_BUCKETS = 240;
9
+ /** Leave room for one worst-case WAL and later bounded incident files, not just the database. */
10
+ export declare function historyBudget(maxBytes?: number): {
11
+ maxBytes: number;
12
+ softBytes: number;
13
+ lowBytes: number;
14
+ reserveBytes: number;
15
+ maxPages: number;
16
+ dbBytes: number;
17
+ walBytes: number;
18
+ worstBytes: number;
19
+ };
20
+ export type HistoryPause = 'disk_unavailable' | 'backing_drive_unknown' | 'low_space' | 'recovering_space';
21
+ export declare class HistoryWatermark {
22
+ private low;
23
+ private recoveringAt;
24
+ /** Monotonic time controls recovery; wall-clock adjustments cannot finish it early. */
25
+ permit(snapshot: HostHealthSnapshot, monotonicNow: number): {
26
+ ok: true;
27
+ } | {
28
+ ok: false;
29
+ reason: HistoryPause;
30
+ };
31
+ }
32
+ export declare const agentHistorySeries: (value: string) => boolean;
33
+ export declare const HISTORY_MAX_POINTS = 832;
34
+ export interface HistoryPoint {
35
+ series: string;
36
+ at: number;
37
+ sourceAt: number;
38
+ value: number;
39
+ }
40
+ export declare const historySeries: (value: unknown) => value is string;
41
+ /** Only numerical telemetry and opaque volume ids cross into history. No paths/names/native text. */
42
+ export declare function hostHistoryPoints(snapshot: HostHealthSnapshot, at: number): HistoryPoint[];
43
+ export declare const HISTORY_RANGES: {
44
+ readonly '1h': number;
45
+ readonly '24h': number;
46
+ readonly '7d': number;
47
+ readonly '30d': number;
48
+ };
49
+ export type HistoryRange = keyof typeof HISTORY_RANGES;
50
+ export declare function historyQuery(range: unknown, series: unknown, now: number): {
51
+ series: string[];
52
+ start: number;
53
+ end: number;
54
+ resolution: number;
55
+ step: number;
56
+ buckets: number;
57
+ };
@@ -0,0 +1,107 @@
1
+ export const HISTORY_BYTES = 64 * 1024 ** 2;
2
+ export const HISTORY_PAGE_BYTES = 4096;
3
+ export const HISTORY_SHM_BUDGET = 128 * 1024;
4
+ export const HISTORY_RAW_MS = 24 * 60 * 60 * 1000;
5
+ export const HISTORY_ROLLUP_MS = 30 * HISTORY_RAW_MS;
6
+ export const HISTORY_BUCKET_MS = 5 * 60 * 1000;
7
+ export const HISTORY_MAX_BUCKETS = 240;
8
+ const GiB = 1024 ** 3;
9
+ /** Leave room for one worst-case WAL and later bounded incident files, not just the database. */
10
+ export function historyBudget(maxBytes = HISTORY_BYTES) {
11
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1024 ** 2 || maxBytes > HISTORY_BYTES)
12
+ throw Error('invalid_history_budget');
13
+ const reserveBytes = Math.min(4 * 1024 ** 2, Math.floor(maxBytes / 4));
14
+ const maxPages = Math.floor((maxBytes - reserveBytes - HISTORY_SHM_BUDGET - 32) / (2 * HISTORY_PAGE_BYTES + 24));
15
+ const dbBytes = maxPages * HISTORY_PAGE_BYTES, walBytes = 32 + maxPages * (HISTORY_PAGE_BYTES + 24);
16
+ return { maxBytes, softBytes: Math.floor(maxBytes * 7 / 8), lowBytes: Math.floor(maxBytes * 3 / 4), reserveBytes, maxPages, dbBytes, walBytes,
17
+ worstBytes: dbBytes + walBytes + HISTORY_SHM_BUDGET + reserveBytes };
18
+ }
19
+ export class HistoryWatermark {
20
+ low = false;
21
+ recoveringAt = null;
22
+ /** Monotonic time controls recovery; wall-clock adjustments cannot finish it early. */
23
+ permit(snapshot, monotonicNow) {
24
+ const unavailable = (reason) => { this.recoveringAt = null; return { ok: false, reason }; };
25
+ if (snapshot.disks.status !== 'ok' || !snapshot.disks.value)
26
+ return unavailable('disk_unavailable');
27
+ const volumes = snapshot.disks.value.volumes;
28
+ const state = volumes.find(v => v.roles.includes('state'));
29
+ const valid = (n) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0;
30
+ if (!state || !valid(state.availableBytes))
31
+ return unavailable('disk_unavailable');
32
+ const free = [state.availableBytes];
33
+ if (snapshot.platform === 'wsl') {
34
+ const backing = volumes.find(v => v.roles.includes('wsl-backing'));
35
+ if (snapshot.disks.value.backingDrive !== 'identified' || !backing || !valid(backing.availableBytes))
36
+ return unavailable('backing_drive_unknown');
37
+ free.push(backing.availableBytes);
38
+ }
39
+ if (free.some(n => n < 2 * GiB)) {
40
+ this.low = true;
41
+ return unavailable('low_space');
42
+ }
43
+ if (!this.low)
44
+ return { ok: true };
45
+ if (free.some(n => n <= 4 * GiB))
46
+ return unavailable('recovering_space');
47
+ if (this.recoveringAt === null || monotonicNow < this.recoveringAt)
48
+ this.recoveringAt = monotonicNow;
49
+ if (monotonicNow - this.recoveringAt < 10 * 60 * 1000)
50
+ return { ok: false, reason: 'recovering_space' };
51
+ this.low = false;
52
+ this.recoveringAt = null;
53
+ return { ok: true };
54
+ }
55
+ }
56
+ export const agentHistorySeries = (value) => /^agent\.[a-f0-9]{16}\.(?:cpu|rss|managed)$/.test(value);
57
+ export const HISTORY_MAX_POINTS = 832;
58
+ export const historySeries = (value) => typeof value === 'string' &&
59
+ /^(?:agent\.[a-f0-9]{16}\.(?:cpu|rss|managed)|cpu\.used|memory\.(?:available|pressure)|swap\.free|disk\.[a-f0-9]{16}\.(?:available|used))$/.test(value);
60
+ /** Only numerical telemetry and opaque volume ids cross into history. No paths/names/native text. */
61
+ export function hostHistoryPoints(snapshot, at) {
62
+ if (!snapshot.enabled || snapshot.state !== 'sampling' || !Number.isSafeInteger(at) || at < 0)
63
+ return [];
64
+ const points = [];
65
+ const add = (series, value, sourceAt, max = Number.MAX_SAFE_INTEGER) => {
66
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= max && sourceAt !== null && Number.isSafeInteger(sourceAt) && sourceAt >= 0)
67
+ points.push({ series, at, sourceAt, value });
68
+ };
69
+ if (snapshot.cpu.status === 'ok')
70
+ add('cpu.used', snapshot.cpu.value?.usedPercent, snapshot.cpu.sampledAt, 100);
71
+ if (snapshot.memory.status === 'ok' && snapshot.memory.value) {
72
+ const memory = snapshot.memory.value;
73
+ add('memory.available', memory.availableBytes, snapshot.memory.sampledAt);
74
+ add('swap.free', memory.swapFreeBytes, snapshot.memory.sampledAt);
75
+ add('memory.pressure', { normal: 1, elevated: 2, critical: 3 }[memory.pressure], snapshot.memory.sampledAt, 3);
76
+ }
77
+ if (snapshot.disks.status === 'ok')
78
+ for (const disk of snapshot.disks.value?.volumes.slice(0, 8) ?? []) {
79
+ if (!/^[a-f0-9]{16}$/.test(disk.id))
80
+ continue;
81
+ add(`disk.${disk.id}.available`, disk.availableBytes, disk.sampledAt);
82
+ add(`disk.${disk.id}.used`, disk.usedPercent, disk.sampledAt, 100);
83
+ }
84
+ const footprint = snapshot.footprint;
85
+ if (footprint?.enabled && footprint.status === 'ok' && footprint.reading)
86
+ for (const row of footprint.reading.rows.slice(0, 128)) {
87
+ if (!/^[a-f0-9]{16}$/.test(row.id))
88
+ continue;
89
+ const start = points.length;
90
+ add(`agent.${row.id}.cpu`, row.cpuPercent, footprint.reading.sampledAt, 100);
91
+ add(`agent.${row.id}.rss`, row.rssBytes, footprint.reading.sampledAt);
92
+ add(`agent.${row.id}.managed`, row.managedBytes, footprint.reading.sampledAt);
93
+ for (let i = start; i < points.length; i++)
94
+ points[i].at = footprint.reading.sampledAt;
95
+ }
96
+ return points;
97
+ }
98
+ export const HISTORY_RANGES = { '1h': 60 * 60 * 1000, '24h': HISTORY_RAW_MS, '7d': 7 * HISTORY_RAW_MS, '30d': HISTORY_ROLLUP_MS };
99
+ export function historyQuery(range, series, now) {
100
+ if (typeof range !== 'string' || !Object.hasOwn(HISTORY_RANGES, range) || !Array.isArray(series) || series.length < 1 || series.length > 24 || !series.every(historySeries) || new Set(series).size !== series.length || !Number.isSafeInteger(now) || now < 0)
101
+ throw Error('invalid_history_query');
102
+ const duration = HISTORY_RANGES[range], resolution = range === '1h' ? (series.some(agentHistorySeries) ? 60_000 : 30_000) : HISTORY_BUCKET_MS;
103
+ const step = Math.max(resolution, Math.ceil(duration / HISTORY_MAX_BUCKETS / resolution) * resolution);
104
+ const start = Math.max(0, now - duration);
105
+ return { series: [...series], start, end: now, resolution, step, buckets: Math.max(1, Math.ceil((now - start) / step)) };
106
+ }
107
+ //# sourceMappingURL=host-monitoring-history-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-monitoring-history-policy.js","sourceRoot":"","sources":["../src/host-monitoring-history-policy.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC;AAC5C,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;AACvC,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,GAAG,IAAI,CAAC;AAC7C,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAClD,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,GAAG,cAAc,CAAC;AACrD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,GAAG,I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AuB,CAAC,CAAC;IAC1Q,MAAM,QAAQ,GAAC,cAAc,CAAC,KAAqB,CAAC,EAAC,UAAU,GAAC,KAAK,KAAG,IAAI,CAAA,CAAC,CAAA,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA,CAAC,CAAA,MAAM,CAAA,CAAC,CAAA,MAAM,CAAC,CAAA,CAAC,CAAA,iBAAiB,CAAC;IAC/I,MAAM,IAAI,GAAC,IAAI,CAAC,GAAG,CAAC,UAAU,EAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,GAAC,mBAAmB,GAAC,UAAU,CAAC,GAAC,UAAU,CAAC,CAAC;IAC9F,MAAM,KAAK,GAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAC,GAAG,GAAC,QAAQ,CAAC,CAAC;IACrC,OAAO,EAAC,MAAM,EAAC,CAAC,GAAG,MAAM,CAAa,EAAC,KAAK,EAAC,GAAG,EAAC,GAAG,EAAC,UAAU,EAAC,IAAI,EAAC,OAAO,EAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,GAAC,KAAK,CAAC,GAAC,IAAI,CAAC,CAAC,EAAC,CAAC;AACxH,CAAC"}
@@ -0,0 +1,52 @@
1
+ import { type HistoryPoint } from './host-monitoring-history-policy.js';
2
+ export { historyFiles, cleanupHistory } from './host-monitoring-history-files.js';
3
+ export interface HistoryStats {
4
+ bytes: number;
5
+ rows: number;
6
+ maxBytes: number;
7
+ dbBudget: number;
8
+ trimmed: boolean;
9
+ }
10
+ export interface HistoryBucket {
11
+ at: number;
12
+ min: number | null;
13
+ max: number | null;
14
+ average: number | null;
15
+ count: number;
16
+ sourceAt: number | null;
17
+ }
18
+ export interface HistoryAnswer {
19
+ start: number;
20
+ end: number;
21
+ step: number;
22
+ series: Array<{
23
+ id: string;
24
+ buckets: HistoryBucket[];
25
+ }>;
26
+ stats: HistoryStats;
27
+ }
28
+ interface Options {
29
+ maxBytes?: number;
30
+ maxRows?: number;
31
+ }
32
+ /** A hard DB quota reserves an entire non-spilling transaction WAL, SHM and incident headroom. */
33
+ export declare class HostHistoryStore {
34
+ private readonly path;
35
+ private db;
36
+ private readonly budget;
37
+ private readonly maxRows;
38
+ private trimmed;
39
+ constructor(path: string, options?: Options);
40
+ /** Exact names only; rejects foreign/symlinked/oversized files before opening SQLite. */
41
+ private files;
42
+ private checkpoint;
43
+ stats(): HistoryStats;
44
+ private removeOldest;
45
+ append(points: HistoryPoint[], now: number): {
46
+ written: number;
47
+ paused: boolean;
48
+ stats: HistoryStats;
49
+ };
50
+ query(range: unknown, series: unknown, now: number): HistoryAnswer;
51
+ close(): void;
52
+ }
@@ -0,0 +1,178 @@
1
+ // SQLite is synchronous: production imports this only inside the dedicated history worker.
2
+ import Database from 'better-sqlite3';
3
+ import { closeSync, lstatSync, openSync } from 'node:fs';
4
+ import { agentHistorySeries, HISTORY_MAX_POINTS, historyBudget, historyQuery, historySeries, HISTORY_BUCKET_MS, HISTORY_PAGE_BYTES, HISTORY_RAW_MS, HISTORY_ROLLUP_MS, HISTORY_SHM_BUDGET } from './host-monitoring-history-policy.js';
5
+ export { historyFiles, cleanupHistory } from './host-monitoring-history-files.js';
6
+ import { historyFiles } from './host-monitoring-history-files.js';
7
+ /** A hard DB quota reserves an entire non-spilling transaction WAL, SHM and incident headroom. */
8
+ export class HostHistoryStore {
9
+ path;
10
+ db;
11
+ budget;
12
+ maxRows;
13
+ trimmed = false;
14
+ constructor(path, options = {}) {
15
+ this.path = path;
16
+ this.budget = historyBudget(options.maxBytes);
17
+ this.maxRows = options.maxRows ?? 100_000;
18
+ if (!Number.isSafeInteger(this.maxRows) || this.maxRows < 16 || this.maxRows > 100_000)
19
+ throw Error('history_invalid_rows');
20
+ this.files(true);
21
+ this.db = new Database(path, { fileMustExist: true, timeout: 0 });
22
+ try {
23
+ this.db.pragma(`page_size = ${HISTORY_PAGE_BYTES}`);
24
+ if (this.db.pragma('page_size', { simple: true }) !== HISTORY_PAGE_BYTES)
25
+ throw Error('history_page_size');
26
+ this.db.pragma('busy_timeout = 0');
27
+ this.db.pragma('temp_store = MEMORY');
28
+ this.db.pragma('cache_size = -1024');
29
+ // Without dirty-page spill, one transaction emits at most one frame per DB page.
30
+ this.db.pragma('cache_spill = OFF');
31
+ this.db.pragma('journal_mode = WAL');
32
+ this.db.pragma('wal_autocheckpoint = 0');
33
+ this.db.pragma('synchronous = NORMAL');
34
+ if (Number(this.db.pragma(`max_page_count = ${this.budget.maxPages}`, { simple: true })) > this.budget.maxPages)
35
+ throw Error('history_cap');
36
+ const version = Number(this.db.pragma('user_version', { simple: true }));
37
+ if (version !== 0 && version !== 1)
38
+ throw Error('history_version');
39
+ this.db.exec(`CREATE TABLE IF NOT EXISTS monitoring_points (
40
+ resolution INTEGER NOT NULL, series TEXT NOT NULL, at INTEGER NOT NULL,
41
+ lo REAL NOT NULL, hi REAL NOT NULL, total REAL NOT NULL, n INTEGER NOT NULL, source_at INTEGER NOT NULL,
42
+ PRIMARY KEY (resolution,series,at)
43
+ ) WITHOUT ROWID;
44
+ CREATE INDEX IF NOT EXISTS monitoring_points_time ON monitoring_points(resolution,at);
45
+ PRAGMA user_version = 1;`);
46
+ if (!this.checkpoint())
47
+ throw Error('history_busy');
48
+ }
49
+ catch (error) {
50
+ this.db.close();
51
+ throw error;
52
+ }
53
+ }
54
+ /** Exact names only; rejects foreign/symlinked/oversized files before opening SQLite. */
55
+ files(create = false) {
56
+ let bytes = 0, wal = 0, reserved = 0;
57
+ for (const [i, name] of historyFiles(this.path).entries()) {
58
+ let info;
59
+ try {
60
+ info = lstatSync(name);
61
+ }
62
+ catch (error) {
63
+ if (error.code === 'ENOENT')
64
+ continue;
65
+ throw error;
66
+ }
67
+ if (!info.isFile() || info.nlink !== 1 || (process.getuid && (info.uid !== process.getuid() || (info.mode & 0o077) !== 0)))
68
+ throw Error('history_private_file_required');
69
+ bytes += info.size;
70
+ if (i >= 4)
71
+ reserved += info.size;
72
+ if (i === 0 && info.size > this.budget.dbBytes)
73
+ throw Error('history_cap');
74
+ if (i === 1) {
75
+ wal = info.size;
76
+ if (wal > this.budget.walBytes)
77
+ throw Error('history_cap');
78
+ }
79
+ if (i === 2 && info.size > HISTORY_SHM_BUDGET)
80
+ throw Error('history_cap');
81
+ if (i === 3 && info.size)
82
+ throw Error('history_unexpected_journal');
83
+ }
84
+ if (bytes > this.budget.maxBytes || reserved > this.budget.reserveBytes)
85
+ throw Error('history_cap');
86
+ if (create) {
87
+ try {
88
+ closeSync(openSync(this.path, 'wx', 0o600));
89
+ }
90
+ catch (error) {
91
+ if (error.code !== 'EEXIST')
92
+ throw error;
93
+ }
94
+ }
95
+ return { bytes, wal };
96
+ }
97
+ checkpoint() {
98
+ this.files();
99
+ const result = this.db.pragma('wal_checkpoint(TRUNCATE)');
100
+ return result[0]?.busy === 0 && this.files().wal === 0;
101
+ }
102
+ stats() {
103
+ return { bytes: this.files().bytes, rows: Number(this.db.prepare('SELECT count(*) n FROM monitoring_points').get().n), maxBytes: this.budget.maxBytes, dbBudget: this.budget.dbBytes, trimmed: this.trimmed };
104
+ }
105
+ removeOldest(limit) {
106
+ const removed = this.db.prepare(`DELETE FROM monitoring_points WHERE (resolution,series,at) IN
107
+ (SELECT resolution,series,at FROM monitoring_points ORDER BY at,resolution LIMIT ?)`).run(limit).changes;
108
+ if (removed)
109
+ this.trimmed = true;
110
+ return removed;
111
+ }
112
+ append(points, now) {
113
+ if (points.length > HISTORY_MAX_POINTS || !Number.isSafeInteger(now) || now < 0 || points.some(p => !historySeries(p.series) || !Number.isSafeInteger(p.at) || p.at < 0 || p.at > now || !Number.isSafeInteger(p.sourceAt) || p.sourceAt < 0 || !Number.isFinite(p.value) || p.value < 0 || p.value > Number.MAX_SAFE_INTEGER))
114
+ throw Error('history_invalid_points');
115
+ // A pinned WAL must close before another write. Never accumulate a second transaction behind it.
116
+ const pressure = this.files().bytes >= this.budget.softBytes;
117
+ if (!this.checkpoint())
118
+ return { written: 0, paused: true, stats: this.stats() };
119
+ const prune = this.db.transaction(() => {
120
+ // The entire DB and row population are capped; expiry completes in this worker transaction.
121
+ for (const [resolution, cutoff] of [[30_000, now - HISTORY_RAW_MS], [HISTORY_BUCKET_MS, now - HISTORY_ROLLUP_MS]])
122
+ this.db.prepare('DELETE FROM monitoring_points WHERE resolution=? AND at<?').run(resolution, cutoff);
123
+ this.db.prepare("DELETE FROM monitoring_points WHERE series LIKE 'agent.%' AND ((resolution=60000 AND at<?) OR (resolution=300000 AND at<?))").run(now - 6 * 60 * 60 * 1000, now - 7 * HISTORY_RAW_MS);
124
+ // At the soft mark prune oldest history, then release WAL below the low mark.
125
+ // DB+reserve+SHM alone is deliberately smaller than that low mark.
126
+ if (pressure)
127
+ this.removeOldest(2000);
128
+ const count = this.stats().rows;
129
+ if (count + points.length * 2 > this.maxRows)
130
+ this.removeOldest(Math.min(2000, Math.max(points.length * 2, count - Math.floor(this.maxRows * .9))));
131
+ const pages = Number(this.db.pragma('page_count', { simple: true })), free = Number(this.db.pragma('freelist_count', { simple: true }));
132
+ const growthPages = Math.min(128, Math.max(8, Math.floor(this.budget.maxPages / 8)));
133
+ if (this.budget.maxPages - pages + free < growthPages)
134
+ this.removeOldest(2000);
135
+ });
136
+ prune();
137
+ if (!this.checkpoint())
138
+ return { written: 0, paused: true, stats: this.stats() };
139
+ const current = this.stats();
140
+ if (current.rows + points.length * 2 > this.maxRows)
141
+ return { written: 0, paused: true, stats: current };
142
+ const put = this.db.prepare(`INSERT INTO monitoring_points VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(resolution,series,at)
143
+ DO UPDATE SET lo=excluded.lo,hi=excluded.hi,total=excluded.total,n=excluded.n,source_at=excluded.source_at`);
144
+ const aggregate = this.db.prepare(`SELECT min(lo) lo,max(hi) hi,sum(total) total,sum(n) n,max(source_at) source_at
145
+ FROM monitoring_points WHERE resolution IN (30000,60000) AND series=? AND at>=? AND at<?`);
146
+ this.db.transaction(() => {
147
+ const changed = new Map();
148
+ for (const p of points) {
149
+ const resolution = agentHistorySeries(p.series) ? 60000 : 30000;
150
+ const at = Math.floor(p.at / resolution) * resolution;
151
+ put.run(resolution, p.series, at, p.value, p.value, p.value, 1, p.sourceAt);
152
+ const roll = Math.floor(at / HISTORY_BUCKET_MS) * HISTORY_BUCKET_MS;
153
+ changed.set(`${p.series}:${roll}`, { series: p.series, at: roll });
154
+ }
155
+ for (const p of changed.values()) {
156
+ const a = aggregate.get(p.series, p.at, p.at + HISTORY_BUCKET_MS);
157
+ put.run(HISTORY_BUCKET_MS, p.series, p.at, a.lo, a.hi, a.total, a.n, a.source_at);
158
+ }
159
+ })();
160
+ const truncated = this.checkpoint(), stats = this.stats();
161
+ // Checkpointing releases journal bytes first; history retention/row pruning reuses allocated DB pages.
162
+ if (stats.bytes > this.budget.maxBytes || (pressure && truncated && stats.bytes > this.budget.lowBytes))
163
+ throw Error('history_cap');
164
+ return { written: points.length, paused: !truncated, stats };
165
+ }
166
+ query(range, series, now) {
167
+ const q = historyQuery(range, series, now);
168
+ const select = this.db.prepare(`SELECT CAST((at-?)/? AS INTEGER) bucket,min(lo) lo,max(hi) hi,sum(total) total,sum(n) n,max(source_at) source_at
169
+ FROM monitoring_points WHERE resolution=? AND series=? AND at>=? AND at<? GROUP BY bucket ORDER BY bucket LIMIT 241`);
170
+ return { start: q.start, end: q.end, step: q.step, series: q.series.map(id => {
171
+ const rows = select.all(q.start, q.step, range === '1h' ? (agentHistorySeries(id) ? 60000 : 30000) : q.resolution, id, q.start, q.end);
172
+ const byBucket = new Map(rows.map(r => [r.bucket, r]));
173
+ return { id, buckets: Array.from({ length: q.buckets }, (_, i) => { const r = byBucket.get(i); return { at: q.start + i * q.step, min: r?.lo ?? null, max: r?.hi ?? null, average: r && r.n ? r.total / r.n : null, count: r?.n ?? 0, sourceAt: r?.source_at ?? null }; }) };
174
+ }), stats: this.stats() };
175
+ }
176
+ close() { this.db.close(); }
177
+ }
178
+ //# sourceMappingURL=host-monitoring-history-store.js.map