@jini-ai/platform 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 (137) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +13 -0
  3. package/dist/download-lock.d.ts +3 -1
  4. package/dist/download-lock.js +4 -4
  5. package/dist/download-maintenance.js +6 -6
  6. package/dist/download-state.js +17 -14
  7. package/dist/download-store.d.ts +34 -10
  8. package/dist/download-store.js +24 -20
  9. package/dist/download-target.d.ts +6 -2
  10. package/dist/download-target.js +7 -7
  11. package/dist/download-transfer.js +18 -12
  12. package/dist/download.js +4 -4
  13. package/dist/fetch-with-timeout.d.ts +0 -53
  14. package/dist/fetch-with-timeout.js +56 -6
  15. package/dist/fs/directory-running-lock.d.ts +4 -0
  16. package/dist/fs/directory-running-lock.js +8 -1
  17. package/dist/fs/directory-workspace.d.ts +2 -1
  18. package/dist/fs/directory-workspace.js +2 -2
  19. package/dist/fs/durable-json.d.ts +3 -16
  20. package/dist/fs/durable-json.js +4 -2
  21. package/dist/fs/guarded-reader.d.ts +10 -0
  22. package/dist/fs/guarded-reader.js +34 -1
  23. package/dist/fs/index.d.ts +4 -0
  24. package/dist/fs/index.js +4 -0
  25. package/dist/fs/leased-directory-move.d.ts +49 -0
  26. package/dist/fs/leased-directory-move.js +31 -0
  27. package/dist/fs/owned-temp-root.d.ts +74 -0
  28. package/dist/fs/owned-temp-root.js +203 -0
  29. package/dist/fs/recent-directories.d.ts +2 -1
  30. package/dist/fs/resolve-directory-target.d.ts +33 -0
  31. package/dist/fs/resolve-directory-target.js +58 -0
  32. package/dist/fs/staged-file.d.ts +40 -0
  33. package/dist/fs/staged-file.js +75 -0
  34. package/dist/fs/strict-containment.d.ts +14 -0
  35. package/dist/fs/strict-containment.js +14 -0
  36. package/dist/image/png-encode.d.ts +41 -0
  37. package/dist/image/png-encode.js +96 -0
  38. package/dist/index.d.ts +3 -1
  39. package/dist/mail/email-template-agent-tools.d.ts +150 -0
  40. package/dist/mail/email-template-agent-tools.js +86 -0
  41. package/dist/mail/email-template-tool-registrations.d.ts +73 -0
  42. package/dist/mail/email-template-tool-registrations.js +66 -0
  43. package/dist/mail/feedback-route.d.ts +50 -0
  44. package/dist/mail/feedback-route.js +46 -0
  45. package/dist/mail/feedback-setup.d.ts +44 -0
  46. package/dist/mail/feedback-setup.js +53 -0
  47. package/dist/mail/feedback-sources.d.ts +67 -0
  48. package/dist/mail/feedback-sources.js +42 -0
  49. package/dist/mail/index.d.ts +10 -1
  50. package/dist/mail/index.js +4 -0
  51. package/dist/mail/mail-status.d.ts +32 -0
  52. package/dist/mail/mail-status.js +2 -0
  53. package/dist/mail/positional-purpose-gate.d.ts +14 -0
  54. package/dist/mail/positional-purpose-gate.js +18 -0
  55. package/dist/mail/purpose-gate-probe.d.ts +18 -0
  56. package/dist/mail/purpose-gate-probe.js +22 -0
  57. package/dist/mail/resolve-mailer.d.ts +13 -1
  58. package/dist/mail/resolve-mailer.js +11 -5
  59. package/dist/mail/sql/activity.repo.d.ts +20 -0
  60. package/dist/mail/sql/activity.repo.js +133 -0
  61. package/dist/mail/sql/attempts.repo.d.ts +17 -0
  62. package/dist/mail/sql/attempts.repo.js +32 -0
  63. package/dist/mail/sql/capture.repo.d.ts +69 -0
  64. package/dist/mail/sql/capture.repo.js +119 -0
  65. package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
  66. package/dist/mail/sql/feedback-inbox.repo.js +32 -0
  67. package/dist/mail/sql/index.d.ts +12 -0
  68. package/dist/mail/sql/index.js +12 -0
  69. package/dist/mail/sql/ledger.repo.d.ts +29 -0
  70. package/dist/mail/sql/ledger.repo.js +57 -0
  71. package/dist/mail/sql/retention.d.ts +23 -0
  72. package/dist/mail/sql/retention.js +53 -0
  73. package/dist/mail/sql/site-feedback-route.d.ts +18 -0
  74. package/dist/mail/sql/site-feedback-route.js +22 -0
  75. package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
  76. package/dist/mail/sql/suppression-admin.repo.js +76 -0
  77. package/dist/mail/sql/suppression.repo.d.ts +10 -0
  78. package/dist/mail/sql/suppression.repo.js +33 -0
  79. package/dist/mail/test-send.d.ts +147 -0
  80. package/dist/mail/test-send.js +201 -0
  81. package/dist/mail/use-readiness.d.ts +104 -0
  82. package/dist/mail/use-readiness.js +140 -0
  83. package/dist/object-store/local-fs.js +34 -1
  84. package/dist/object-store/site/artifact-provider.d.ts +65 -0
  85. package/dist/object-store/site/artifact-provider.js +37 -0
  86. package/dist/object-store/site/registry.d.ts +110 -0
  87. package/dist/object-store/site/registry.js +93 -0
  88. package/dist/object-store/site/setting.d.ts +34 -0
  89. package/dist/object-store/site/setting.js +32 -0
  90. package/dist/process-probes.d.ts +11 -4
  91. package/dist/process-probes.js +3 -3
  92. package/dist/process-top-footprint.d.ts +1 -1
  93. package/dist/process.d.ts +3 -17
  94. package/dist/process.js +3 -2
  95. package/dist/retention/index.d.ts +6 -0
  96. package/dist/retention/index.js +6 -0
  97. package/dist/retention/measure-tree.d.ts +68 -0
  98. package/dist/retention/measure-tree.js +205 -0
  99. package/dist/retention/preview-store.d.ts +10 -0
  100. package/dist/retention/preview-store.js +26 -0
  101. package/dist/retention/routes.d.ts +23 -0
  102. package/dist/retention/routes.js +24 -0
  103. package/dist/retention/runner.d.ts +103 -0
  104. package/dist/retention/runner.js +164 -0
  105. package/dist/secrets/credential-sets/index.d.ts +1 -0
  106. package/dist/secrets/credential-sets/index.js +1 -0
  107. package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
  108. package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
  109. package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
  110. package/dist/secrets/index.d.ts +1 -1
  111. package/dist/secrets/index.js +1 -1
  112. package/dist/secrets/keyring.env.d.ts +1 -1
  113. package/dist/secrets/keyring.env.js +3 -5
  114. package/dist/secrets/keyring.memory.d.ts +4 -1
  115. package/dist/secrets/keyring.memory.js +4 -1
  116. package/dist/secrets/legacy-codecs.d.ts +381 -0
  117. package/dist/secrets/legacy-codecs.js +468 -0
  118. package/dist/secrets/legacy-owner.d.ts +3 -11
  119. package/dist/secrets/root-key/ensure.d.ts +154 -0
  120. package/dist/secrets/root-key/ensure.js +328 -0
  121. package/dist/secrets/root-key/files.d.ts +104 -0
  122. package/dist/secrets/root-key/files.js +166 -0
  123. package/dist/secrets/root-key/material.d.ts +132 -0
  124. package/dist/secrets/root-key/material.js +116 -0
  125. package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
  126. package/dist/secrets/root-key/ordered-keyring.js +104 -0
  127. package/dist/secrets/root-key/reconcile.d.ts +50 -0
  128. package/dist/secrets/root-key/reconcile.js +147 -0
  129. package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
  130. package/dist/secrets/root-key/site-keyring-errors.js +37 -0
  131. package/dist/secrets/root-key/sources.d.ts +79 -0
  132. package/dist/secrets/root-key/sources.js +119 -0
  133. package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
  134. package/dist/secrets/secret-sealer.aesgcm.js +107 -19
  135. package/dist/web/tool-registrations.d.ts +67 -0
  136. package/dist/web/tool-registrations.js +44 -0
  137. package/package.json +139 -7
@@ -0,0 +1,32 @@
1
+ import { SCOPE_BIT } from "@jini-ai/core/settings";
2
+ /**
3
+ * @file Which object-store provider holds the site's media bytes: `core.storage.mediaObjectStore`
4
+ * on the existing settings ledger (workspace scope, no schema change). The empty default means the
5
+ * registry default, `local`. Read once per boot when media is first touched, so a change applies
6
+ * on the next restart. The host's media blob-store env var, when set, overrides it.
7
+ *
8
+ * ## Wiring
9
+ * The host binds the settings ledger's implementations: `ensureSettingDefinitions` (the
10
+ * definition writer) and `getEffective` (the reader) arrive on each function's required args, so
11
+ * this module only type-imports their contracts from `@jini-ai/core/settings`.
12
+ */
13
+ export const STORAGE_SETTINGS_NAMESPACE = "core.storage";
14
+ export const MEDIA_OBJECT_STORE_KEY = "mediaObjectStore";
15
+ /**
16
+ * Registers the definition without replacing an owner's stored value.
17
+ * @complexity O(1), one definition.
18
+ */
19
+ export function ensureMediaObjectStoreSetting(required, _optional = {}) {
20
+ return required.ensureSettingDefinitions(required.deps, { namespace: STORAGE_SETTINGS_NAMESPACE, systemPrincipalId: required.systemPrincipalId, definitions: [
21
+ { key: MEDIA_OBJECT_STORE_KEY, schema: { type: "string" }, defaultValue: "", scopes: SCOPE_BIT.workspace },
22
+ ] });
23
+ }
24
+ /**
25
+ * The saved provider id, trimmed; `""` when unset, blank, non-string or unregistered.
26
+ * @complexity One effective setting read.
27
+ */
28
+ export async function readMediaObjectStoreSetting(required, _optional = {}) {
29
+ const effective = await required.getEffective({ deps: { repo: required.settingsRepo }, namespace: STORAGE_SETTINGS_NAMESPACE, key: MEDIA_OBJECT_STORE_KEY, scopeContext: { workspaceId: required.workspaceId } });
30
+ return typeof effective?.value === "string" ? effective.value.trim() : "";
31
+ }
32
+ //# sourceMappingURL=setting.js.map
@@ -1,6 +1,7 @@
1
1
  import type { ProcessSnapshot } from "@jini-ai/core/contracts/runtime";
2
2
  import { execFileBuffered } from "./shell.js";
3
- import type { ProcessUsage, ProcessUsagePorts, ProcessUsageOptions } from "./process.js";
3
+ import type { ProcessUsagePorts, ProcessUsageOptions } from "./process.js";
4
+ import type { ProcessUsage } from "@jini-ai/core/contracts/site/platform-process";
4
5
  /** @internal Enumerate process snapshots on POSIX via `ps`. */
5
6
  export declare function listPosixProcessSnapshots(input: ProcessUsagePorts, options: ProcessUsageOptions & {
6
7
  commandLines?: boolean;
@@ -10,11 +11,17 @@ export declare function listWindowsProcessSnapshots(input: ProcessUsagePorts, op
10
11
  commandLines?: boolean;
11
12
  }): Promise<ProcessSnapshot[]>;
12
13
  /** @internal Read only comm, never args/command, so credentials cannot enter the result. */
13
- export declare function parsePsUsage(stdout: string): ProcessUsage[];
14
+ export declare function parsePsUsage({ stdout }: {
15
+ stdout: string;
16
+ }, _optional?: Record<string, never>): ProcessUsage[];
14
17
  /** @internal Convert Windows 100ns CPU counters and retain nameless process rows. */
15
- export declare function parseCimUsage(stdout: string): ProcessUsage[];
18
+ export declare function parseCimUsage({ stdout }: {
19
+ stdout: string;
20
+ }, _optional?: Record<string, never>): ProcessUsage[];
16
21
  /** @internal Fixed executable and argv, invoked directly without a command shell. */
17
- export declare function processUsageCommand(windows: boolean): {
22
+ export declare function processUsageCommand({ windows }: {
23
+ windows: boolean;
24
+ }, _optional?: Record<string, never>): {
18
25
  command: string;
19
26
  args: string[];
20
27
  };
@@ -66,7 +66,7 @@ function validProcessUsage(usage) {
66
66
  && [pid, ppid, rssBytes, cpuSeconds].every((value) => value >= 0);
67
67
  }
68
68
  /** @internal Read only comm, never args/command, so credentials cannot enter the result. */
69
- export function parsePsUsage(stdout) {
69
+ export function parsePsUsage({ stdout }, _optional = {}) {
70
70
  return stdout.split(/\r?\n/).flatMap((line) => {
71
71
  const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S.*)$/);
72
72
  if (!match)
@@ -85,7 +85,7 @@ function cimNumber(value) {
85
85
  return typeof value === "string" && value.trim() ? Number(value) : NaN;
86
86
  }
87
87
  /** @internal Convert Windows 100ns CPU counters and retain nameless process rows. */
88
- export function parseCimUsage(stdout) {
88
+ export function parseCimUsage({ stdout }, _optional = {}) {
89
89
  if (!stdout.trim())
90
90
  return [];
91
91
  const payload = JSON.parse(stdout);
@@ -103,7 +103,7 @@ export function parseCimUsage(stdout) {
103
103
  });
104
104
  }
105
105
  /** @internal Fixed executable and argv, invoked directly without a command shell. */
106
- export function processUsageCommand(windows) {
106
+ export function processUsageCommand({ windows }, _optional = {}) {
107
107
  return windows
108
108
  ? { command: windowsPowerShell(), args: ["-NoProfile", "-NonInteractive", "-Command",
109
109
  "$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, WorkingSetSize, UserModeTime, KernelModeTime, Name | ConvertTo-Json -Compress"] }
@@ -1,4 +1,4 @@
1
- import type { ProcessPrivateMemory } from "./process.js";
1
+ import type { ProcessPrivateMemory } from "@jini-ai/core/contracts/site/platform-process";
2
2
  /** Only the requested PID table is trusted; duplicate rows invalidate that PID. O(text length + p) space/time. */
3
3
  export declare function topReadings({ text, pids }: {
4
4
  text: string;
package/dist/process.d.ts CHANGED
@@ -12,7 +12,10 @@
12
12
  */
13
13
  import { type ChildProcess } from "node:child_process";
14
14
  import type { CommandInvocationRequest, ProcessSnapshot, StopProcessesResult } from "@jini-ai/core/contracts/runtime";
15
+ import type { ProcessPrivateMemory, ProcessUsage } from "@jini-ai/core/contracts/site/platform-process";
15
16
  import { execFileBuffered } from "./shell.js";
17
+ /** Deprecated re-export: import these from `@jini-ai/core/contracts/site/platform-process`; removed at the next major. */
18
+ export type { ProcessPrivateMemory, ProcessUsage } from "@jini-ai/core/contracts/site/platform-process";
16
19
  export type ProcessStampShape = object;
17
20
  export type ProcessStampField<TStamp extends ProcessStampShape> = Extract<keyof TStamp, string>;
18
21
  export type ProcessStampContract<TStamp extends ProcessStampShape, TCriteria extends Partial<TStamp> = Partial<TStamp>> = {
@@ -28,15 +31,6 @@ export type SpawnProcessRequest = CommandInvocationRequest & {
28
31
  detached?: boolean;
29
32
  logFd?: number | null;
30
33
  };
31
- /** Display-only usage: RSS is bytes; CPU is cumulative seconds across all cores. */
32
- export type ProcessUsage = {
33
- pid: number;
34
- ppid: number;
35
- rssBytes: number;
36
- cpuSeconds: number;
37
- /** Executable basename only; empty when the OS provides no name. */
38
- name: string;
39
- };
40
34
  export type ProcessUsagePorts = {
41
35
  platform?: NodeJS.Platform;
42
36
  run?: typeof execFileBuffered;
@@ -44,14 +38,6 @@ export type ProcessUsagePorts = {
44
38
  export type ProcessUsageOptions = {
45
39
  timeoutMs?: number;
46
40
  };
47
- /** Private-memory samples are separate from RSS; unsupported hosts retain null readings. */
48
- export type ProcessPrivateMemory = {
49
- metric: "physical-footprint" | "private-working-set" | "unavailable";
50
- readings: Array<{
51
- pid: number;
52
- bytes: number | null;
53
- }>;
54
- };
55
41
  export type StampedProcessMatchCriteria<TStamp extends ProcessStampShape> = Partial<TStamp>;
56
42
  /**
57
43
  * Serialize a process stamp into `--flag=value` CLI arguments per the contract.
package/dist/process.js CHANGED
@@ -245,7 +245,7 @@ export async function listProcessSnapshots(input = {}, options = {}) {
245
245
  */
246
246
  export async function listProcessUsage(input = {}, options = {}) {
247
247
  const windows = (input.platform ?? process.platform) === "win32";
248
- const { command, args } = processUsageCommand(windows);
248
+ const { command, args } = processUsageCommand({ windows });
249
249
  try {
250
250
  const result = await (input.run ?? execFileBuffered)(command, args, {
251
251
  encoding: "utf8", timeout: options.timeoutMs ?? 5000, maxBuffer: 8 * 1024 * 1024,
@@ -253,7 +253,8 @@ export async function listProcessUsage(input = {}, options = {}) {
253
253
  });
254
254
  if (!result.ok)
255
255
  return [];
256
- return windows ? parseCimUsage(result.stdout) : parsePsUsage(result.stdout);
256
+ const { stdout } = result;
257
+ return windows ? parseCimUsage({ stdout }) : parsePsUsage({ stdout });
257
258
  }
258
259
  catch {
259
260
  return [];
@@ -0,0 +1,6 @@
1
+ /** Host-neutral storage retention: a serialized pass runner over injected policies, and a read-only
2
+ * tree measurement. Hosts own every path and every policy; nothing in this entry deletes files. */
3
+ export { RETENTION_DEFAULT_INTERVAL_MS, createRetentionRunner, type RetentionMeasurement, type RetentionPassResult, type RetentionPolicy, type RetentionPolicyKind, type RetentionPolicyOutcome, type RetentionRunner, type RetentionRunnerOptional, type RetentionRunnerRequired, type RetentionScheduler, type RetentionSweepResult, } from './runner.js';
4
+ export { measureStorageTree, nodeStorageTreeFs, type StorageTally, type StorageTarget, type StorageTreeDirectory, type StorageTreeFs, type StorageTreeIdentity, type StorageTreeMeasurement, type StorageTreeStats, } from './measure-tree.js';
5
+ export { createCleanupPreviewStore } from './preview-store.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,6 @@
1
+ /** Host-neutral storage retention: a serialized pass runner over injected policies, and a read-only
2
+ * tree measurement. Hosts own every path and every policy; nothing in this entry deletes files. */
3
+ export { RETENTION_DEFAULT_INTERVAL_MS, createRetentionRunner, } from './runner.js';
4
+ export { measureStorageTree, nodeStorageTreeFs, } from './measure-tree.js';
5
+ export { createCleanupPreviewStore } from './preview-store.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,68 @@
1
+ /** A filesystem object's identity; two names for one folder share it, a replacement does not. */
2
+ export interface StorageTreeIdentity {
3
+ readonly dev: number | bigint;
4
+ readonly ino: number | bigint;
5
+ }
6
+ export interface StorageTreeStats extends StorageTreeIdentity {
7
+ isSymbolicLink(): boolean;
8
+ isDirectory(): boolean;
9
+ isFile(): boolean;
10
+ readonly size: number;
11
+ }
12
+ /** One opened folder. Listing and child metadata are read relative to the opened folder, never by
13
+ * re-resolving its pathname, so a later swap of that pathname cannot redirect the reads. */
14
+ export interface StorageTreeDirectory {
15
+ /** Identity of the folder actually opened (never the target of a link). */
16
+ readonly identity: StorageTreeIdentity;
17
+ list(): Promise<string[]>;
18
+ /** Metadata of one child, without following it if it is a link. */
19
+ lstatChild(name: string): Promise<StorageTreeStats>;
20
+ /** False once the folder's pathname no longer names the opened folder. */
21
+ stillOpenedDirectory(): Promise<boolean>;
22
+ close(): Promise<void>;
23
+ }
24
+ /** The read port the walk needs; inject a fake to test unreadable or racing paths. `lstat` is used for
25
+ * the root only; `openDirectory` must refuse (not follow) a link at `target`. */
26
+ export interface StorageTreeFs {
27
+ lstat(target: string): Promise<StorageTreeStats>;
28
+ openDirectory(target: string): Promise<StorageTreeDirectory>;
29
+ }
30
+ export interface StorageTarget {
31
+ readonly id: string;
32
+ readonly path: string;
33
+ }
34
+ export interface StorageTally {
35
+ /** Exact bytes, or `null` when part of this tally could not be read. */
36
+ readonly bytes: number | null;
37
+ /** Bytes actually read: the lower bound when `bytes` is `null`. */
38
+ readonly knownBytes: number;
39
+ readonly files: number;
40
+ readonly unknownPaths: readonly string[];
41
+ readonly skippedSymlinks: readonly string[];
42
+ }
43
+ export interface StorageTreeMeasurement {
44
+ readonly root: string;
45
+ readonly total: StorageTally;
46
+ readonly targets: Readonly<Record<string, StorageTally>>;
47
+ readonly other: StorageTally;
48
+ }
49
+ /** The Node adapter: opens each folder without following a link and, on Linux, reads it through the
50
+ * process's own descriptor link (`/proc/self/fd/N`), which stays bound to the opened folder. Elsewhere it
51
+ * reads by pathname and `stillOpenedDirectory()` re-checks the pathname's identity afterwards.
52
+ * @example await measureStorageTree({ root, targets }, { fs: nodeStorageTreeFs }); */
53
+ export declare const nodeStorageTreeFs: StorageTreeFs;
54
+ /**
55
+ * Measures `root` once, attributing bytes to `targets`.
56
+ * @throws TypeError for a relative root or target, a repeated id or two targets naming one path.
57
+ * @throws RangeError for a target outside `root`.
58
+ * @complexity O(n · t) time for n entries and t targets, O(depth + t) extra space; one `lstat` per
59
+ * entry and one `readdir` per folder, sequential to keep disk pressure low on a serving host.
60
+ * @example await measureStorageTree({ root: siteDir, targets: [{ id: 'uploads', path: uploadsDir }] });
61
+ */
62
+ export declare function measureStorageTree({ root, targets }: {
63
+ root: string;
64
+ targets: readonly StorageTarget[];
65
+ }, { fs: treeFs }?: {
66
+ fs?: StorageTreeFs;
67
+ }): Promise<StorageTreeMeasurement>;
68
+ //# sourceMappingURL=measure-tree.d.ts.map
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @file Read-only storage measurement for one folder tree. The host passes already-resolved absolute
3
+ * paths it wants totals for ("targets"); one walk attributes every file to the closest target that
4
+ * contains it, and everything else to `other`, so the parts always add up to the walked total.
5
+ *
6
+ * Rules:
7
+ * - Symlinks are never followed (a link into another site or the whole disk would inflate the total
8
+ * and could loop). Each skipped link is listed. A folder is enumerated through an anchored,
9
+ * no-follow directory handle whose identity must match the inspected folder; when that identity
10
+ * cannot be maintained (the folder was swapped for a link or another folder mid-walk), the folder
11
+ * is reported unknown and nothing it listed is counted.
12
+ * - A path that cannot be read is reported as unknown: the affected tallies get `bytes: null` and the
13
+ * path in `unknownPaths`, while `knownBytes` keeps the lower bound. An unreadable folder is never 0.
14
+ * - A missing path is a known zero, and a file that vanishes mid-walk is simply not counted.
15
+ * - Sizes are apparent sizes (`lstat().size`), the number an owner compares against their file
16
+ * manager; hard links are counted once per name.
17
+ * Nothing here writes, opens a database or deletes.
18
+ */
19
+ import { constants as fsConstants } from 'node:fs';
20
+ import fs from 'node:fs/promises';
21
+ import path from 'node:path';
22
+ // Windows has neither flag; there the identity checks below are what catch a swapped folder.
23
+ const OPEN_DIRECTORY_NO_FOLLOW = fsConstants.O_RDONLY | (fsConstants.O_DIRECTORY ?? 0) | (fsConstants.O_NOFOLLOW ?? 0);
24
+ /** The Node adapter: opens each folder without following a link and, on Linux, reads it through the
25
+ * process's own descriptor link (`/proc/self/fd/N`), which stays bound to the opened folder. Elsewhere it
26
+ * reads by pathname and `stillOpenedDirectory()` re-checks the pathname's identity afterwards.
27
+ * @example await measureStorageTree({ root, targets }, { fs: nodeStorageTreeFs }); */
28
+ export const nodeStorageTreeFs = {
29
+ lstat: target => fs.lstat(target),
30
+ openDirectory: target => openNodeDirectory({ target }),
31
+ };
32
+ async function openNodeDirectory({ target }, _optional = {}) {
33
+ const handle = await fs.open(target, OPEN_DIRECTORY_NO_FOLLOW);
34
+ try {
35
+ const identity = await handle.stat();
36
+ if (!identity.isDirectory())
37
+ throw Object.assign(new Error('The opened path is not a folder.'), { code: 'ENOTDIR' });
38
+ const base = await descriptorPath({ fd: handle.fd, identity }) ?? target;
39
+ return {
40
+ identity,
41
+ list: () => fs.readdir(base),
42
+ lstatChild: name => fs.lstat(path.join(base, name)),
43
+ stillOpenedDirectory: async () => sameIdentity(await fs.lstat(target).catch(() => undefined), identity),
44
+ close: () => handle.close(),
45
+ };
46
+ }
47
+ catch (error) {
48
+ await handle.close();
49
+ throw error;
50
+ }
51
+ }
52
+ /** `/proc/self/fd/N` when it resolves to the opened folder, otherwise `undefined` (no procfs). */
53
+ async function descriptorPath({ fd, identity }, _optional = {}) {
54
+ const anchored = `/proc/self/fd/${fd}`;
55
+ const resolved = await fs.stat(anchored).catch(() => undefined);
56
+ return sameIdentity(resolved, identity) ? anchored : undefined;
57
+ }
58
+ function sameIdentity(a, b, _optional = {}) {
59
+ return a !== undefined && a.dev === b.dev && a.ino === b.ino;
60
+ }
61
+ /**
62
+ * Measures `root` once, attributing bytes to `targets`.
63
+ * @throws TypeError for a relative root or target, a repeated id or two targets naming one path.
64
+ * @throws RangeError for a target outside `root`.
65
+ * @complexity O(n · t) time for n entries and t targets, O(depth + t) extra space; one `lstat` per
66
+ * entry and one `readdir` per folder, sequential to keep disk pressure low on a serving host.
67
+ * @example await measureStorageTree({ root: siteDir, targets: [{ id: 'uploads', path: uploadsDir }] });
68
+ */
69
+ export async function measureStorageTree({ root, targets }, { fs: treeFs = nodeStorageTreeFs } = {}) {
70
+ const checked = validateTargets({ root, targets });
71
+ const tallies = new Map(checked.map(target => [target.id, emptyTally()]));
72
+ const other = emptyTally();
73
+ const total = emptyTally();
74
+ const ownerOf = (entry) => {
75
+ // Targets are sorted longest path first, so the first container is the closest one.
76
+ const owner = checked.find(target => contains({ parent: target.path, child: entry }));
77
+ return owner ? tallies.get(owner.id) : other;
78
+ };
79
+ const markUnknown = (entry) => {
80
+ total.unknownPaths.push(entry);
81
+ ownerOf(entry).unknownPaths.push(entry);
82
+ // Anything nested inside an unreadable folder is unknown as well, not empty.
83
+ for (const target of checked) {
84
+ if (target.path !== entry && contains({ parent: entry, child: target.path }))
85
+ tallies.get(target.id).unknownPaths.push(entry);
86
+ }
87
+ };
88
+ await walk({ root, fs: treeFs, visit: { ownerOf, markUnknown, total } });
89
+ return {
90
+ root,
91
+ total: freeze(total),
92
+ targets: Object.fromEntries([...tallies].map(([id, tally]) => [id, freeze(tally)])),
93
+ other: freeze(other),
94
+ };
95
+ }
96
+ async function walk({ root, fs: treeFs, visit }, _optional = {}) {
97
+ const folders = [];
98
+ const record = (entry, stats) => {
99
+ if (stats === 'missing')
100
+ return;
101
+ if (stats === 'unknown')
102
+ return visit.markUnknown(entry);
103
+ if (stats.isSymbolicLink()) {
104
+ visit.total.skippedSymlinks.push(entry);
105
+ visit.ownerOf(entry).skippedSymlinks.push(entry);
106
+ }
107
+ else if (stats.isDirectory()) {
108
+ folders.push({ entry, identity: stats });
109
+ }
110
+ else if (stats.isFile()) {
111
+ for (const tally of [visit.total, visit.ownerOf(entry)]) {
112
+ tally.knownBytes += stats.size;
113
+ tally.files += 1;
114
+ }
115
+ }
116
+ };
117
+ record(root, await readStats({ read: () => treeFs.lstat(root) }));
118
+ for (let folder = folders.pop(); folder !== undefined; folder = folders.pop()) {
119
+ const children = await readFolder({ fs: treeFs, folder });
120
+ if (children === 'unknown') {
121
+ visit.markUnknown(folder.entry);
122
+ continue;
123
+ }
124
+ for (const [entry, stats] of children)
125
+ record(entry, stats);
126
+ }
127
+ }
128
+ /** Lists one folder through its anchored handle. Children are only returned once the handle is proven
129
+ * to be the inspected folder both before and after the reads; otherwise the whole folder is unknown. */
130
+ async function readFolder({ fs: treeFs, folder }, _optional = {}) {
131
+ let directory;
132
+ try {
133
+ directory = await treeFs.openDirectory(folder.entry);
134
+ }
135
+ catch (error) {
136
+ return isMissing(error) ? [] : 'unknown';
137
+ }
138
+ try {
139
+ if (!sameIdentity(directory.identity, folder.identity))
140
+ return 'unknown';
141
+ const children = [];
142
+ for (const name of await directory.list()) {
143
+ children.push([path.join(folder.entry, name), await readStats({ read: () => directory.lstatChild(name) })]);
144
+ }
145
+ return (await directory.stillOpenedDirectory()) ? children : 'unknown';
146
+ }
147
+ catch (error) {
148
+ return isMissing(error) ? [] : 'unknown';
149
+ }
150
+ finally {
151
+ await directory.close().catch(() => undefined);
152
+ }
153
+ }
154
+ async function readStats({ read }, _optional = {}) {
155
+ try {
156
+ return await read();
157
+ }
158
+ catch (error) {
159
+ return isMissing(error) ? 'missing' : 'unknown';
160
+ }
161
+ }
162
+ function validateTargets({ root, targets }, _optional = {}) {
163
+ if (!path.isAbsolute(root))
164
+ throw new TypeError(`The folder to measure must be an absolute path: ${root}`);
165
+ const byPath = new Map();
166
+ const ids = new Set();
167
+ const checked = targets.map(({ id, path: target }) => {
168
+ if (!path.isAbsolute(target))
169
+ throw new TypeError(`Storage target "${id}" must be an absolute path: ${target}`);
170
+ if (ids.has(id))
171
+ throw new TypeError(`Storage target "${id}" is listed twice.`);
172
+ const resolved = path.resolve(target);
173
+ const clash = byPath.get(resolved);
174
+ if (clash !== undefined)
175
+ throw new TypeError(`Storage targets "${clash}" and "${id}" name the same path: ${resolved}`);
176
+ if (!contains({ parent: path.resolve(root), child: resolved })) {
177
+ throw new RangeError(`Storage target "${id}" is outside the folder being measured: ${resolved}`);
178
+ }
179
+ ids.add(id);
180
+ byPath.set(resolved, id);
181
+ return { id, path: resolved };
182
+ });
183
+ return checked.sort((a, b) => b.path.length - a.path.length);
184
+ }
185
+ /** Segment-aware containment: `content.db-wal` is not inside `content.db`. */
186
+ function contains({ parent, child }, _optional = {}) {
187
+ const relative = path.relative(parent, child);
188
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
189
+ }
190
+ function isMissing(error, _optional = {}) {
191
+ return typeof error === 'object' && error !== null && error.code === 'ENOENT';
192
+ }
193
+ function emptyTally(_optional = {}) {
194
+ return { knownBytes: 0, files: 0, unknownPaths: [], skippedSymlinks: [] };
195
+ }
196
+ function freeze(tally, _optional = {}) {
197
+ return {
198
+ bytes: tally.unknownPaths.length > 0 ? null : tally.knownBytes,
199
+ knownBytes: tally.knownBytes,
200
+ files: tally.files,
201
+ unknownPaths: [...tally.unknownPaths],
202
+ skippedSymlinks: [...tally.skippedSymlinks],
203
+ };
204
+ }
205
+ //# sourceMappingURL=measure-tree.js.map
@@ -0,0 +1,10 @@
1
+ import type { CleanupPreviewStore } from '@jini-ai/core/contracts/storage';
2
+ export declare function createCleanupPreviewStore({ randomToken, mono }: {
3
+ randomToken: (required: {
4
+ bytes: number;
5
+ }) => string;
6
+ mono: () => number;
7
+ }, { ttlMs }?: {
8
+ ttlMs?: number | undefined;
9
+ }): CleanupPreviewStore;
10
+ //# sourceMappingURL=preview-store.d.ts.map
@@ -0,0 +1,26 @@
1
+ export function createCleanupPreviewStore({ randomToken, mono }, { ttlMs = 900000 } = {}) {
2
+ const outstanding = new Map();
3
+ return {
4
+ put({ principal, kind, scope, payload }, _optional = {}) {
5
+ const at = mono();
6
+ for (const [key, entry] of outstanding)
7
+ if (entry.deadline <= at)
8
+ outstanding.delete(key);
9
+ const token = randomToken({ bytes: 16 });
10
+ const deadline = Math.min(at + ttlMs, payload.deadline ?? Infinity);
11
+ outstanding.set(JSON.stringify([principal, kind]), { token, scope, payload, deadline });
12
+ return { token, deadline };
13
+ },
14
+ take({ token, principal, kind, scope }, _optional = {}) {
15
+ const key = JSON.stringify([principal, kind]);
16
+ const entry = outstanding.get(key);
17
+ if (!entry || entry.token !== token || entry.scope !== scope)
18
+ return null;
19
+ outstanding.delete(key);
20
+ if (mono() >= entry.deadline)
21
+ return null;
22
+ return { payload: entry.payload, deadline: entry.deadline };
23
+ },
24
+ };
25
+ }
26
+ //# sourceMappingURL=preview-store.js.map
@@ -0,0 +1,23 @@
1
+ export declare function createStorageRoutes({ paths }: {
2
+ paths: {
3
+ report: string;
4
+ cleanup: string;
5
+ };
6
+ }, _optional?: {}): {
7
+ report: import("@jini-ai/core/contracts/server").JsonRouteSpec<Record<string, never>, object, {
8
+ measure: (required: Record<string, never>, optional: Record<string, never>) => Promise<object>;
9
+ }, undefined>;
10
+ cleanup: import("@jini-ai/core/contracts/server").JsonRouteSpec<{
11
+ dryRun?: boolean;
12
+ classes?: string[];
13
+ }, object, {
14
+ runOnce: (required: {
15
+ dryRun: boolean;
16
+ classes?: string[];
17
+ }, optional: Record<string, never>) => Promise<object>;
18
+ copy: {
19
+ invalidClass: string;
20
+ };
21
+ }, undefined>;
22
+ };
23
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { defineJsonRoute, err, ok } from '@jini-ai/core/contracts/server';
2
+ export function createStorageRoutes({ paths }, _optional = {}) {
3
+ return {
4
+ report: defineJsonRoute({
5
+ method: 'get', path: paths.report, parse: () => ok({ value: {} }),
6
+ handle: async ({ deps, authorize }) => {
7
+ await authorize({ permission: 'storage.manage' });
8
+ return ok({ value: await deps.measure({}, {}) });
9
+ },
10
+ }),
11
+ cleanup: defineJsonRoute({
12
+ method: 'post', path: paths.cleanup,
13
+ parse: raw => ok({ value: (raw.body ?? {}) }),
14
+ handle: async ({ input, deps, authorize }) => {
15
+ await authorize({ permission: 'storage.manage' });
16
+ if (input.classes?.some(kind => !['cache', 'derived', 'old-copy'].includes(kind)))
17
+ return err({ error: { code: 'INVALID_INPUT', message: deps.copy.invalidClass } });
18
+ // Measurement describes what exists; a sweep separately reports what it actually freed.
19
+ return ok({ value: await deps.runOnce({ dryRun: input.dryRun !== false, ...(input.classes === undefined ? {} : { classes: input.classes }) }, {}) });
20
+ },
21
+ }, { requireSameOrigin: true }),
22
+ };
23
+ }
24
+ //# sourceMappingURL=routes.js.map
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @file A host-neutral storage retention runner: it schedules passes over host-supplied policies and
3
+ * never touches the filesystem itself. Every collaborator (clock, scheduler, error sink, policies) is
4
+ * injected; the host decides which policies exist, where their files live and whether scheduled
5
+ * passes may clean or only measure.
6
+ *
7
+ * Pass rules:
8
+ * - Passes are serialized. A request that matches the running pass's mode joins it; a request of the
9
+ * other mode waits for it and then runs its own pass (at most one waiting pass, joined the same way).
10
+ * So a dry run always gets a measurement-only result, even when it arrives during a cleanup, and a
11
+ * confirmed cleanup always gets the result of an actual sweep, even when it arrives during a dry run.
12
+ * - A dry run calls `measure()` only and never enters `sweep()`.
13
+ * - A failing policy is reported in plain words and the next policy still runs.
14
+ * - `stop()` clears the timer, cancels a waiting pass and resolves once the running pass has finished,
15
+ * so the host can close storage right after it.
16
+ */
17
+ /** Daily, matching the plan's default pass cadence; hosts can pass their own `intervalMs`. */
18
+ export declare const RETENTION_DEFAULT_INTERVAL_MS: number;
19
+ /** The only data a runner may clean automatically. There is deliberately no `"content"` (owner data
20
+ * is removed only by an explicit owner action) and no `"history"` (chats are content). */
21
+ export type RetentionPolicyKind = 'cache' | 'derived' | 'old-copy';
22
+ /** `bytes: null` means the policy could not tell (for example an unreadable folder), never zero. */
23
+ export interface RetentionMeasurement {
24
+ readonly bytes: number | null;
25
+ readonly items?: number;
26
+ }
27
+ export interface RetentionSweepResult {
28
+ readonly freedBytes: number | null;
29
+ readonly removed: number;
30
+ }
31
+ export interface RetentionPolicy {
32
+ readonly id: string;
33
+ readonly kind: RetentionPolicyKind;
34
+ measure(): Promise<RetentionMeasurement>;
35
+ sweep(input: {
36
+ readonly now: number;
37
+ }): Promise<RetentionSweepResult>;
38
+ }
39
+ export type RetentionPolicyOutcome = {
40
+ readonly id: string;
41
+ readonly kind: RetentionPolicyKind;
42
+ readonly status: 'measured';
43
+ readonly measurement: RetentionMeasurement;
44
+ } | {
45
+ readonly id: string;
46
+ readonly kind: RetentionPolicyKind;
47
+ readonly status: 'swept';
48
+ readonly result: RetentionSweepResult;
49
+ } | {
50
+ readonly id: string;
51
+ readonly kind: RetentionPolicyKind;
52
+ readonly status: 'failed';
53
+ readonly message: string;
54
+ };
55
+ export type RetentionPassResult = {
56
+ readonly status: 'completed';
57
+ readonly dryRun: boolean;
58
+ readonly startedAt: number;
59
+ readonly finishedAt: number;
60
+ readonly policies: readonly RetentionPolicyOutcome[];
61
+ } | {
62
+ readonly status: 'stopped';
63
+ readonly dryRun: boolean;
64
+ };
65
+ export interface RetentionScheduler {
66
+ setInterval(callback: () => void, ms: number): unknown;
67
+ clearInterval(handle: unknown): void;
68
+ }
69
+ export interface RetentionRunnerRequired {
70
+ readonly policies: readonly RetentionPolicy[];
71
+ readonly clock: {
72
+ now(): number;
73
+ };
74
+ readonly scheduler: RetentionScheduler;
75
+ /** Receives plain-words errors; `policyId` is absent for pass-level failures (a scheduled pass that
76
+ * could not run, or a report that could not be delivered). */
77
+ readonly reportError: (error: Error, context: {
78
+ readonly policyId?: string;
79
+ }) => void;
80
+ }
81
+ export interface RetentionRunnerOptional {
82
+ readonly intervalMs?: number;
83
+ /** Scheduled (boot and timer) passes only measure unless the host explicitly opts in to cleaning. */
84
+ readonly scheduledDryRun?: boolean;
85
+ readonly onReport?: (report: RetentionPassResult) => void;
86
+ }
87
+ export interface RetentionRunner {
88
+ runOnce(input: {
89
+ readonly dryRun: boolean;
90
+ }): Promise<RetentionPassResult>;
91
+ start(): void;
92
+ stop(): Promise<void>;
93
+ }
94
+ /**
95
+ * Creates a runner over the given policies. Nothing runs until `start()` or `runOnce()`.
96
+ * @throws TypeError for a duplicate policy id or a kind outside cache/derived/old-copy (a JS caller
97
+ * can bypass the type, so the kind rule is enforced at runtime as well).
98
+ * @throws RangeError for an interval that is not a positive finite number.
99
+ * @complexity O(p) per pass in policies, run one at a time.
100
+ * @example createRetentionRunner({ policies, clock: Date, scheduler: globalThis, reportError }, { onReport });
101
+ */
102
+ export declare function createRetentionRunner(required: RetentionRunnerRequired, { intervalMs, scheduledDryRun, onReport }?: RetentionRunnerOptional): RetentionRunner;
103
+ //# sourceMappingURL=runner.d.ts.map