@jini-ai/platform 0.7.3-next.2 → 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 (136) hide show
  1. package/README.md +13 -0
  2. package/dist/download-lock.d.ts +3 -1
  3. package/dist/download-lock.js +4 -4
  4. package/dist/download-maintenance.js +6 -6
  5. package/dist/download-state.js +17 -14
  6. package/dist/download-store.d.ts +34 -10
  7. package/dist/download-store.js +24 -20
  8. package/dist/download-target.d.ts +6 -2
  9. package/dist/download-target.js +7 -7
  10. package/dist/download-transfer.js +18 -12
  11. package/dist/download.js +4 -4
  12. package/dist/fetch-with-timeout.d.ts +0 -53
  13. package/dist/fetch-with-timeout.js +56 -6
  14. package/dist/fs/directory-running-lock.d.ts +4 -0
  15. package/dist/fs/directory-running-lock.js +8 -1
  16. package/dist/fs/directory-workspace.d.ts +2 -1
  17. package/dist/fs/directory-workspace.js +2 -2
  18. package/dist/fs/durable-json.d.ts +3 -16
  19. package/dist/fs/durable-json.js +4 -2
  20. package/dist/fs/guarded-reader.d.ts +10 -0
  21. package/dist/fs/guarded-reader.js +34 -1
  22. package/dist/fs/index.d.ts +4 -0
  23. package/dist/fs/index.js +4 -0
  24. package/dist/fs/leased-directory-move.d.ts +49 -0
  25. package/dist/fs/leased-directory-move.js +31 -0
  26. package/dist/fs/owned-temp-root.d.ts +74 -0
  27. package/dist/fs/owned-temp-root.js +203 -0
  28. package/dist/fs/recent-directories.d.ts +2 -1
  29. package/dist/fs/resolve-directory-target.d.ts +33 -0
  30. package/dist/fs/resolve-directory-target.js +58 -0
  31. package/dist/fs/staged-file.d.ts +40 -0
  32. package/dist/fs/staged-file.js +75 -0
  33. package/dist/fs/strict-containment.d.ts +14 -0
  34. package/dist/fs/strict-containment.js +14 -0
  35. package/dist/image/png-encode.d.ts +41 -0
  36. package/dist/image/png-encode.js +96 -0
  37. package/dist/index.d.ts +3 -1
  38. package/dist/mail/email-template-agent-tools.d.ts +150 -0
  39. package/dist/mail/email-template-agent-tools.js +86 -0
  40. package/dist/mail/email-template-tool-registrations.d.ts +73 -0
  41. package/dist/mail/email-template-tool-registrations.js +66 -0
  42. package/dist/mail/feedback-route.d.ts +50 -0
  43. package/dist/mail/feedback-route.js +46 -0
  44. package/dist/mail/feedback-setup.d.ts +44 -0
  45. package/dist/mail/feedback-setup.js +53 -0
  46. package/dist/mail/feedback-sources.d.ts +67 -0
  47. package/dist/mail/feedback-sources.js +42 -0
  48. package/dist/mail/index.d.ts +10 -1
  49. package/dist/mail/index.js +4 -0
  50. package/dist/mail/mail-status.d.ts +32 -0
  51. package/dist/mail/mail-status.js +2 -0
  52. package/dist/mail/positional-purpose-gate.d.ts +14 -0
  53. package/dist/mail/positional-purpose-gate.js +18 -0
  54. package/dist/mail/purpose-gate-probe.d.ts +18 -0
  55. package/dist/mail/purpose-gate-probe.js +22 -0
  56. package/dist/mail/resolve-mailer.d.ts +13 -1
  57. package/dist/mail/resolve-mailer.js +11 -5
  58. package/dist/mail/sql/activity.repo.d.ts +20 -0
  59. package/dist/mail/sql/activity.repo.js +133 -0
  60. package/dist/mail/sql/attempts.repo.d.ts +17 -0
  61. package/dist/mail/sql/attempts.repo.js +32 -0
  62. package/dist/mail/sql/capture.repo.d.ts +69 -0
  63. package/dist/mail/sql/capture.repo.js +119 -0
  64. package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
  65. package/dist/mail/sql/feedback-inbox.repo.js +32 -0
  66. package/dist/mail/sql/index.d.ts +12 -0
  67. package/dist/mail/sql/index.js +12 -0
  68. package/dist/mail/sql/ledger.repo.d.ts +29 -0
  69. package/dist/mail/sql/ledger.repo.js +57 -0
  70. package/dist/mail/sql/retention.d.ts +23 -0
  71. package/dist/mail/sql/retention.js +53 -0
  72. package/dist/mail/sql/site-feedback-route.d.ts +18 -0
  73. package/dist/mail/sql/site-feedback-route.js +22 -0
  74. package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
  75. package/dist/mail/sql/suppression-admin.repo.js +76 -0
  76. package/dist/mail/sql/suppression.repo.d.ts +10 -0
  77. package/dist/mail/sql/suppression.repo.js +33 -0
  78. package/dist/mail/test-send.d.ts +147 -0
  79. package/dist/mail/test-send.js +201 -0
  80. package/dist/mail/use-readiness.d.ts +104 -0
  81. package/dist/mail/use-readiness.js +140 -0
  82. package/dist/object-store/local-fs.js +34 -1
  83. package/dist/object-store/site/artifact-provider.d.ts +65 -0
  84. package/dist/object-store/site/artifact-provider.js +37 -0
  85. package/dist/object-store/site/registry.d.ts +110 -0
  86. package/dist/object-store/site/registry.js +93 -0
  87. package/dist/object-store/site/setting.d.ts +34 -0
  88. package/dist/object-store/site/setting.js +32 -0
  89. package/dist/process-probes.d.ts +11 -4
  90. package/dist/process-probes.js +3 -3
  91. package/dist/process-top-footprint.d.ts +1 -1
  92. package/dist/process.d.ts +3 -17
  93. package/dist/process.js +3 -2
  94. package/dist/retention/index.d.ts +6 -0
  95. package/dist/retention/index.js +6 -0
  96. package/dist/retention/measure-tree.d.ts +68 -0
  97. package/dist/retention/measure-tree.js +205 -0
  98. package/dist/retention/preview-store.d.ts +10 -0
  99. package/dist/retention/preview-store.js +26 -0
  100. package/dist/retention/routes.d.ts +23 -0
  101. package/dist/retention/routes.js +24 -0
  102. package/dist/retention/runner.d.ts +103 -0
  103. package/dist/retention/runner.js +164 -0
  104. package/dist/secrets/credential-sets/index.d.ts +1 -0
  105. package/dist/secrets/credential-sets/index.js +1 -0
  106. package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
  107. package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
  108. package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
  109. package/dist/secrets/index.d.ts +1 -1
  110. package/dist/secrets/index.js +1 -1
  111. package/dist/secrets/keyring.env.d.ts +1 -1
  112. package/dist/secrets/keyring.env.js +3 -5
  113. package/dist/secrets/keyring.memory.d.ts +4 -1
  114. package/dist/secrets/keyring.memory.js +4 -1
  115. package/dist/secrets/legacy-codecs.d.ts +381 -0
  116. package/dist/secrets/legacy-codecs.js +468 -0
  117. package/dist/secrets/legacy-owner.d.ts +3 -11
  118. package/dist/secrets/root-key/ensure.d.ts +154 -0
  119. package/dist/secrets/root-key/ensure.js +328 -0
  120. package/dist/secrets/root-key/files.d.ts +104 -0
  121. package/dist/secrets/root-key/files.js +166 -0
  122. package/dist/secrets/root-key/material.d.ts +132 -0
  123. package/dist/secrets/root-key/material.js +116 -0
  124. package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
  125. package/dist/secrets/root-key/ordered-keyring.js +104 -0
  126. package/dist/secrets/root-key/reconcile.d.ts +50 -0
  127. package/dist/secrets/root-key/reconcile.js +147 -0
  128. package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
  129. package/dist/secrets/root-key/site-keyring-errors.js +37 -0
  130. package/dist/secrets/root-key/sources.d.ts +79 -0
  131. package/dist/secrets/root-key/sources.js +119 -0
  132. package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
  133. package/dist/secrets/secret-sealer.aesgcm.js +107 -19
  134. package/dist/web/tool-registrations.d.ts +67 -0
  135. package/dist/web/tool-registrations.js +44 -0
  136. package/package.json +138 -6
@@ -1,3 +1,57 @@
1
+ /**
2
+ * @module fetch-with-timeout
3
+ *
4
+ * The shared timeout wrapper for every outbound `fetch()` call this monorepo makes to a remote
5
+ * service — see the 2026-08-16 Jini failure-mode audit, Finding 2: 101 raw `fetch()` call sites
6
+ * repo-wide (corrected from the audit's own initial "67" — re-count before trusting any figure in
7
+ * a handoff), across devops deploy providers, agent-runtime providers, media-provider dispatch,
8
+ * github-client, and llm-provider, most already protected in some ad hoc way. A remote that accepts
9
+ * the TCP connection but
10
+ * never responds — a stalled load balancer, a provider having a bad day, a firewall black-holing the
11
+ * request — leaves `await fetch(...)` unresolved forever; whatever awaits it hangs indefinitely, with
12
+ * nothing to alert on. A hang like that is worse than a crash: a crash is loud.
13
+ *
14
+ * Deliberately ONE helper, not 67 call sites each hand-rolling a slightly different
15
+ * `AbortController`/`setTimeout` idiom — a caller who already has their own `AbortSignal` (a
16
+ * user-initiated cancel, a parent request's own deadline) can still supply it via `init.signal`;
17
+ * `AbortSignal.any` composes it with the timeout so either one aborts the call, and the thrown
18
+ * `FetchTimeoutError` vs. the caller's own abort reason stay distinguishable (see `fetchWithTimeout`'s
19
+ * own doc).
20
+ *
21
+ * `FETCH_TIMEOUT_MS` gives call sites a small, documented, shared vocabulary instead of inventing a
22
+ * number each time — a deploy-provider API call, an image byte-fetch, and a large asset upload
23
+ * genuinely have different reasonable ceilings. `timeoutMs` is never hidden inside the helper as an
24
+ * undocumented default with no parameter, though: every call site names one explicitly (usually one
25
+ * of these constants), because a caller reading its own code should see the number, not have to go
26
+ * find it.
27
+ *
28
+ * Deliberately excludes anything meant to stay open for a long time independent of transfer size —
29
+ * Server-Sent Events, WebSockets, long-poll. None of the 67 flagged call sites are that shape (the
30
+ * audit traced this: the repo's real streaming transports are `EventSource` on the browser side and
31
+ * a hand-rolled SSE channel server-side, both entirely separate from `fetch()`), but a future caller
32
+ * reaching for this helper for one of those would be reaching for the wrong tool — `AbortSignal.timeout`
33
+ * bounds the WHOLE call, body included, so it would sever a deliberately long-lived stream partway
34
+ * through exactly like the bug this fixes, just self-inflicted instead of accidental.
35
+ *
36
+ * **Also exported as its own subpath, `@jini-ai/platform/fetch-with-timeout`, deliberately.** This
37
+ * module has zero imports of its own — no `node:*` builtin, no `undici` — unlike the package's root
38
+ * barrel (`index.ts`), which re-exports sibling modules (`process.ts`, `fs.ts`, `terminal.ts`,
39
+ * `asset-cache.ts`, …) that import `node:child_process`, `node:fs`, etc.; the asset-cache
40
+ * dispatcher constructs its required `undici` dependency only when its synchronous factory is called.
41
+ * Importing from the root barrel in browser-bundled code is silently fine in a *production* build
42
+ * through Vite/Rollup — tree-shaking (this package sets `sideEffects: false`) proves the Node-only
43
+ * re-exports are unused and drops them before the `node:*` imports are ever resolved — but it is
44
+ * NOT fine in `vite dev` or any other unbundled-native-ESM serving mode: there is no tree-shaking on
45
+ * that path, so the browser eagerly loads and evaluates every sibling the barrel re-exports, and
46
+ * `process.ts`'s very first statement destructures `execFile`/`spawn` off `node:child_process` —
47
+ * which Vite's dev server serves as a `Proxy` that throws on first property access. The whole module
48
+ * graph fails to evaluate the instant anything imports the barrel, regardless of which export is
49
+ * actually used. Verified empirically (`esbuild --bundle --platform=browser` on the barrel: 154
50
+ * resolution errors; `vite build`: clean, 5.92kB, zero Node-only code in the output; `vite dev`
51
+ * serving `index.js`: throws at import time) — see the 2026-08-17 Jini hardening report. Browser
52
+ * call sites should import from this subpath, never the root barrel.
53
+ */
54
+ import { orFallback } from "@jini-ai/core/errors/idioms";
1
55
  /** Thrown in place of the platform's generic abort error specifically when the timeout — not a
2
56
  * caller-supplied `init.signal` — is what ended the call, so a caller can tell "this took too long"
3
57
  * apart from "I cancelled it myself" without string-matching an error message. */
@@ -111,12 +165,8 @@ async function consumeResponseText({ response, awaitCancel }, options = {}) {
111
165
  }
112
166
  /** Observe synchronous/asynchronous cancellation failure without masking the consumption outcome. */
113
167
  function cancelResponseReader({ reader, reason }) {
114
- try {
115
- return reader.cancel(reason).catch(() => { });
116
- }
117
- catch {
118
- return Promise.resolve();
119
- }
168
+ /* Preserve the consumption error. */
169
+ return orFallback({ work: () => reader.cancel(reason), fallback: undefined, step: "Cancel response reader" });
120
170
  }
121
171
  /** Reject invalid caps before consumption, including for empty responses. */
122
172
  function validateTextReadOptions({ maxResponseBytes, requireCap = false }) {
@@ -8,6 +8,7 @@ export interface DirectoryRunningRecord {
8
8
  token: string;
9
9
  scheme: "http" | "https";
10
10
  bootId?: string;
11
+ purpose?: "serve" | "maintenance";
11
12
  }
12
13
  export interface DirectoryRunningLock {
13
14
  peek(required: Record<string, never>, options?: {}): DirectoryRunningRecord | null;
@@ -40,4 +41,7 @@ export declare function createDirectoryRunningLock({ file, isAlive, remove }: {
40
41
  }, { bootIdentity }?: {
41
42
  bootIdentity?: () => BootIdentity | undefined;
42
43
  }): DirectoryRunningLock;
44
+ export declare function isServeRecord({ record }: {
45
+ record: DirectoryRunningRecord;
46
+ }, _optional?: {}): boolean;
43
47
  //# sourceMappingURL=directory-running-lock.d.ts.map
@@ -66,6 +66,8 @@ export function createDirectoryRunningLock({ file, isAlive, remove }, { bootIden
66
66
  const record = readLive();
67
67
  if (!record || record.token !== token)
68
68
  throw new Error("Running lock ownership was lost.");
69
+ if (record.purpose === "maintenance")
70
+ throw new Error("A maintenance owner has no address.");
69
71
  file.write({ value: { ...record, port } });
70
72
  } });
71
73
  },
@@ -82,7 +84,8 @@ function validRunningRecord(value) {
82
84
  if (!validRunningOwner(value))
83
85
  return false;
84
86
  const validPort = Number.isInteger(value.port) && typeof value.port === "number" && value.port >= 0 && value.port <= 65535;
85
- return validPort && (value.scheme === "http" || value.scheme === "https");
87
+ const validPurpose = [undefined, "serve", "maintenance"].includes(value.purpose);
88
+ return validPurpose && (value.purpose !== "maintenance" || value.port === 0) && validPort && (value.scheme === "http" || value.scheme === "https");
86
89
  }
87
90
  /** Address corruption must not prevent dead-holder recovery, but never guess a holder. O(1). */
88
91
  function validRunningOwner(value) {
@@ -100,4 +103,8 @@ function validRunningIdentity({ record }, _options = {}) {
100
103
  function isNonEmptyString(value) {
101
104
  return typeof value === "string" && value.length > 0;
102
105
  }
106
+ // A portless maintenance owner excludes writers but can never be an attach target.
107
+ export function isServeRecord({ record }, _optional = {}) {
108
+ return record.purpose === undefined || record.purpose === "serve";
109
+ }
103
110
  //# sourceMappingURL=directory-running-lock.js.map
@@ -33,11 +33,12 @@ export declare function createNodeDirectoryWorkspace({ homeDir, defaultFolder, e
33
33
  running: ({ path: dir }: {
34
34
  path: string;
35
35
  }, _options?: {}) => import("./directory-running-lock.js").DirectoryRunningLock;
36
- claim({ path: dir, app, port, scheme }: {
36
+ claim({ path: dir, app, port, scheme, purpose }: {
37
37
  path: string;
38
38
  app: string;
39
39
  port?: number;
40
40
  scheme?: "http" | "https";
41
+ purpose?: "serve" | "maintenance";
41
42
  }, _options?: {}): {
42
43
  acquired: boolean;
43
44
  record: import("./directory-running-lock.js").DirectoryRunningRecord;
@@ -281,9 +281,9 @@ function createWorkspaceRunningAccess({ canonicalPath, runningName, config, sett
281
281
  } }),
282
282
  };
283
283
  },
284
- claim({ path: dir, app, port = 0, scheme = "http" }, _options = {}) {
284
+ claim({ path: dir, app, port = 0, scheme = "http", purpose }, _options = {}) {
285
285
  const lock = this.running({ path: dir });
286
- return lock.claim({ record: { pid: ports.process.pid, port, app, scheme, started: new Date(ports.clock.nowMs()).toISOString(), token: randomUUID() } });
286
+ return lock.claim({ record: { pid: ports.process.pid, port, app, scheme, started: new Date(ports.clock.nowMs()).toISOString(), token: randomUUID(), ...(purpose === undefined ? {} : { purpose }) } });
287
287
  },
288
288
  };
289
289
  }
@@ -1,22 +1,9 @@
1
1
  import { type BootIdentity } from "@jini-ai/core/contracts/runtime";
2
2
  import nodeFs from "node:fs";
3
3
  import { type Clock, type Logger } from "@jini-ai/core/primitives";
4
- export type JsonFileRead = {
5
- state: "ok";
6
- value: unknown;
7
- } | {
8
- state: "missing";
9
- } | {
10
- state: "unreadable";
11
- text?: string;
12
- };
13
- export interface QuarantineNotice {
14
- label: string;
15
- consequence: string;
16
- }
17
- export interface FileLockOptions {
18
- waitMs?: number;
19
- }
4
+ import type { FileLockOptions, JsonFileRead, QuarantineNotice } from "@jini-ai/core/contracts/site/fs-durable-json";
5
+ /** Deprecated re-export: import these from `@jini-ai/core/contracts/site/fs-durable-json`; removed at the next major. */
6
+ export type { FileLockOptions, JsonFileRead, QuarantineNotice } from "@jini-ai/core/contracts/site/fs-durable-json";
20
7
  export interface DurableJsonPorts {
21
8
  filesystem: Pick<typeof nodeFs, "readFileSync" | "mkdirSync" | "openSync" | "writeFileSync" | "fsyncSync" | "closeSync" | "renameSync" | "rmSync" | "writeSync" | "statSync" | "fstatSync" | "lstatSync" | "chmodSync">;
22
9
  clock: Clock;
@@ -11,6 +11,7 @@ import nodeFs from "node:fs";
11
11
  import path from "node:path";
12
12
  import { randomBytes } from "node:crypto";
13
13
  import { createConsoleLogger } from "@jini-ai/core/primitives";
14
+ import { describeErrorForLog } from "@jini-ai/core/model-facing-tool-errors";
14
15
  import { createNodeAtomicFilesystem, writeJsonFileAtomic } from "./atomic-write.js";
15
16
  import { withFileLockSync } from "./file-lock.js";
16
17
  /** Native synchronous adapters. Liveness probes treat permission errors as alive. */
@@ -61,8 +62,9 @@ function quarantineUnreadableFile({ filePath, notice, fs, clock, report, notices
61
62
  catch (error) {
62
63
  if (error.code === "ENOENT")
63
64
  return true;
64
- const logger = report;
65
- logger.error({ message: `${notices.prefix}: ${notice.label} ${filePath} is unreadable and could not be moved aside. Left untouched; nothing was written over it.` }, { error });
65
+ // The safe class(code) label names why the move failed (EACCES vs EXDEV) without quoting the error's
66
+ // own text; the full error still goes to the injected reporter's diagnostics.
67
+ report.error({ message: `${notices.prefix}: ${notice.label} ${filePath} is unreadable and could not be moved aside (${describeErrorForLog({ err: error })}). Left untouched; nothing was written over it.` }, { error });
66
68
  return false;
67
69
  }
68
70
  report.error({ message: `${notices.prefix}: ${notice.label} ${filePath} was unreadable (torn or corrupt). Moved it aside to ${asidePath}; ${notice.consequence}` });
@@ -34,6 +34,16 @@ export interface GuardedListingResult {
34
34
  /** Adds optional paging without changing existing guarded-reader implementations. */
35
35
  export interface PagedGuardedFileReader extends GuardedFileReader {
36
36
  list(required: Record<string, never>, optional?: GuardedListingOptions): GuardedListingResult;
37
+ withGuardedBinaryStream<T>(required: {
38
+ relativePath: string;
39
+ maxBytes: number;
40
+ consume: (input: {
41
+ length: number;
42
+ chunks: AsyncIterable<Uint8Array>;
43
+ }) => Promise<T>;
44
+ }, optional?: {
45
+ signal?: AbortSignal;
46
+ }): Promise<T>;
37
47
  }
38
48
  /** Native filesystem adapter; callers can replace individual operations for a virtual filesystem. */
39
49
  export declare function createNodeGuardedReaderFilesystem(_required: Record<string, never>): GuardedReaderFilesystem;
@@ -30,6 +30,39 @@ export function createGuardedFileReader({ rootPath, denyRules, limits, filesyste
30
30
  resolve: ({ relativePath }) => resolveFsFilePath({ rootPath, relativePath }, context),
31
31
  read: ({ relativePath }) => readFsFile({ rootPath, relativePath }, context),
32
32
  readBytes: ({ relativePath, maxBytes }) => openFsFileForRead({ rootPath, relativePath, maxBytes }, context),
33
+ async withGuardedBinaryStream({ relativePath, maxBytes, consume }, { signal } = {}) {
34
+ if (descriptorFlags === undefined)
35
+ throw new TypeError("withGuardedBinaryStream requires descriptorRead");
36
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
37
+ throw new FsFilePathError({ message: "maxBytes must be a positive safe integer" });
38
+ signal?.throwIfAborted();
39
+ const target = resolveFsFilePath({ rootPath, relativePath }, context);
40
+ const { fd, length } = openValidatedDescriptor({ target, relativePath, maxBytes }, context);
41
+ const chunks = (async function* () {
42
+ let count = 0;
43
+ while (true) {
44
+ signal?.throwIfAborted();
45
+ const buffer = Buffer.alloc(Math.min(64 * 1024, length - count + 1));
46
+ const read = fs.readSync(fd, buffer, 0, buffer.length, null);
47
+ count += read;
48
+ if (count > length || count > maxBytes)
49
+ throw new FsFilePathError({ message: `file '${relativePath}' grew beyond its ${length}-byte descriptor length` });
50
+ if (read === 0) {
51
+ if (count !== length)
52
+ throw new FsFilePathError({ message: `file '${relativePath}' ended before its ${length}-byte descriptor length` });
53
+ return;
54
+ }
55
+ yield buffer.subarray(0, read);
56
+ }
57
+ })();
58
+ try {
59
+ return await consume({ length, chunks });
60
+ }
61
+ finally {
62
+ await chunks.return(undefined);
63
+ fs.closeSync(fd);
64
+ }
65
+ },
33
66
  list: (_required, optional = {}) => listFsFiles({ rootPath, ...optional }, context),
34
67
  isDeniedFileName: ({ fileName }) => isDeniedFsFileName(fileName, context),
35
68
  isDeniedPathSegment: ({ segmentName }) => isDeniedFsPathSegment(segmentName, context),
@@ -321,7 +354,7 @@ function openValidatedDescriptor({ target, relativePath, maxBytes }, context) {
321
354
  try {
322
355
  const stat = fs.fstatSync(fd);
323
356
  assertDescriptorStat({ stat, relativePath, maxBytes }, descriptorRead);
324
- return { fd, maxBytes: descriptorRead?.rejectGrowth ? Math.min(maxBytes, stat.size) : maxBytes };
357
+ return { fd, maxBytes: descriptorRead?.rejectGrowth ? Math.min(maxBytes, stat.size) : maxBytes, length: stat.size };
325
358
  }
326
359
  catch (error) {
327
360
  try {
@@ -19,4 +19,8 @@ export * from "./directory-delete-guard.js";
19
19
  export * from "./remove-directory-tree.js";
20
20
  export * from "./directory-relocation.js";
21
21
  export * from "./recent-directories.js";
22
+ export * from "./resolve-directory-target.js";
23
+ export * from "./leased-directory-move.js";
24
+ export * from "./owned-temp-root.js";
25
+ export * from "./staged-file.js";
22
26
  //# sourceMappingURL=index.d.ts.map
package/dist/fs/index.js CHANGED
@@ -20,4 +20,8 @@ export * from "./directory-delete-guard.js";
20
20
  export * from "./remove-directory-tree.js";
21
21
  export * from "./directory-relocation.js";
22
22
  export * from "./recent-directories.js";
23
+ export * from "./resolve-directory-target.js";
24
+ export * from "./leased-directory-move.js";
25
+ export * from "./owned-temp-root.js";
26
+ export * from "./staged-file.js";
23
27
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,49 @@
1
+ /** A held claim on one directory identity; `token` is what {@link LeasedDirectoryMovePorts.release} needs back. */
2
+ export type DirectoryMoveClaim = {
3
+ acquired: true;
4
+ token: string;
5
+ } | {
6
+ acquired: false;
7
+ };
8
+ /** What the host supplies to {@link moveDirectoryUnderLeases}: it decides what "idle" means, how identities are
9
+ * claimed and released, how the bytes move, and the operator copy of each refusal. */
10
+ export interface LeasedDirectoryMovePorts {
11
+ /** Throws when the source is running or any of its resources is still open. */
12
+ assertIdle(required: {
13
+ from: string;
14
+ }): void;
15
+ /** Reserves one directory identity against other apps booting it. */
16
+ claim(required: {
17
+ path: string;
18
+ }): DirectoryMoveClaim;
19
+ release(required: {
20
+ path: string;
21
+ token: string;
22
+ }): void;
23
+ /** Creates whatever the destination needs (for example its parent folder) before the move. */
24
+ prepareDestination(required: {
25
+ to: string;
26
+ }): void;
27
+ /** The verified relocation itself (a throw leaves the verified destination or the original, never an overwrite). */
28
+ relocate(required: {
29
+ from: string;
30
+ to: string;
31
+ }): void;
32
+ sourceClaimRefused(required: {
33
+ path: string;
34
+ }): Error;
35
+ targetClaimRefused(required: {
36
+ path: string;
37
+ }): Error;
38
+ }
39
+ /**
40
+ * Move one idle directory under its destination's creation lock while both identities are reserved.
41
+ * @throws A refusal from `ports`, an idleness error, or whatever `relocate` throws; both claims are released either way.
42
+ * @complexity The relocation's own cost plus O(1) lock and claim work.
43
+ */
44
+ export declare function moveDirectoryUnderLeases({ from, to, ports }: {
45
+ from: string;
46
+ to: string;
47
+ ports: LeasedDirectoryMovePorts;
48
+ }, _optional?: {}): Promise<void>;
49
+ //# sourceMappingURL=leased-directory-move.d.ts.map
@@ -0,0 +1,31 @@
1
+ import { withFileLock } from "./file-lock.js";
2
+ /**
3
+ * Move one idle directory under its destination's creation lock while both identities are reserved.
4
+ * @throws A refusal from `ports`, an idleness error, or whatever `relocate` throws; both claims are released either way.
5
+ * @complexity The relocation's own cost plus O(1) lock and claim work.
6
+ */
7
+ export async function moveDirectoryUnderLeases({ from, to, ports }, _optional = {}) {
8
+ await withFileLock({ lockPath: `${to}.creation.lock`, run: async () => {
9
+ ports.assertIdle({ from });
10
+ const reservation = ports.claim({ path: from });
11
+ if (!reservation.acquired)
12
+ throw ports.sourceClaimRefused({ path: from });
13
+ let targetToken;
14
+ try {
15
+ const targetReservation = ports.claim({ path: to });
16
+ if (!targetReservation.acquired)
17
+ throw ports.targetClaimRefused({ path: to });
18
+ targetToken = targetReservation.token;
19
+ ports.prepareDestination({ to });
20
+ ports.relocate({ from, to });
21
+ }
22
+ finally {
23
+ // Release at the new path only after the move, so cleanup never recreates the source.
24
+ // Leases can live outside either folder, so release both identities even after the source moves.
25
+ ports.release({ path: from, token: reservation.token });
26
+ if (targetToken)
27
+ ports.release({ path: to, token: targetToken });
28
+ }
29
+ } }, { createParent: true, staleMs: Infinity });
30
+ }
31
+ //# sourceMappingURL=leased-directory-move.js.map
@@ -0,0 +1,74 @@
1
+ import type { Stats } from "node:fs";
2
+ import type * as nodeFs from "node:fs/promises";
3
+ import type { Clock } from "@jini-ai/core/primitives";
4
+ export declare const OWNED_TEMP_ROOT_LOCK_SUFFIX = ".lock";
5
+ export declare const OWNED_TEMP_ROOT_MARKER_SUFFIX = ".owner";
6
+ export type OwnedTempRootFilesystem = Pick<typeof nodeFs, "mkdir" | "rm" | "writeFile" | "readdir" | "realpath"> & {
7
+ lstat(path: string): Promise<Stats>;
8
+ };
9
+ /** A lock adapter shaped like `withFileLock`; the host binds its process/liveness port into it. */
10
+ export type OwnedTempRootLock = <T>(required: {
11
+ lockPath: string;
12
+ run: () => Promise<T>;
13
+ }, options: {
14
+ timeoutMs?: number;
15
+ staleMs: number;
16
+ }) => Promise<T>;
17
+ export interface OwnedTempRootRemovalError {
18
+ root: string;
19
+ error: unknown;
20
+ }
21
+ /**
22
+ * Runs `work` inside a fresh owned root, holding the root's lock for the whole call.
23
+ * @param required.parent existing folder that holds the roots; @param required.prefix host prefix.
24
+ * @param required.id UUID source; @param required.lock lock adapter; @param required.work the job.
25
+ * @param optional.onRemovalError observer for a failed cleanup (the root and marker then stay).
26
+ * @returns what `work` returns. @throws RangeError for a non-plain prefix or a non-UUID id.
27
+ * @complexity O(work) plus one lock, two creates and two removals.
28
+ */
29
+ export declare function withOwnedTempRoot<T>(required: {
30
+ parent: string;
31
+ prefix: string;
32
+ id: () => string;
33
+ fs: OwnedTempRootFilesystem;
34
+ lock: OwnedTempRootLock;
35
+ work: (owned: {
36
+ root: string;
37
+ }) => Promise<T>;
38
+ }, optional?: {
39
+ onRemovalError?: (failure: OwnedTempRootRemovalError) => void;
40
+ }): Promise<T>;
41
+ export type OwnedTempRootOutcome = "removed" | "kept" | "report-only";
42
+ export type OwnedTempRootReason = "dead-owner" | "orphan-lock" | "young" | "owner-alive" | "not-a-directory" | "outside-root" | "changed" | "busy" | "legacy" | "unconfirmed";
43
+ export interface OwnedTempRootEntry {
44
+ path: string;
45
+ outcome: OwnedTempRootOutcome;
46
+ reason: OwnedTempRootReason;
47
+ }
48
+ export interface OwnedTempRootSweepReport {
49
+ entries: OwnedTempRootEntry[];
50
+ truncated: boolean;
51
+ aborted: boolean;
52
+ }
53
+ /**
54
+ * Tidies owned roots left by dead writers in the named parents, reporting everything else.
55
+ * @param required.roots `{ parent, prefix }` pairs; nothing outside them is read or touched.
56
+ * @param required.lock lock adapter whose liveness probe proves owner death; @param required.signal stops between roots.
57
+ * @param optional.olderThanMs minimum root age (default one day); @param optional.limit roots per pass (default 20).
58
+ * @returns one entry per examined root; `truncated` when the limit stopped the pass.
59
+ * @complexity O(n) directory entries plus O(limit) lock attempts and removals.
60
+ */
61
+ export declare function sweepOwnedTempRoots(required: {
62
+ roots: ReadonlyArray<{
63
+ parent: string;
64
+ prefix: string;
65
+ }>;
66
+ fs: OwnedTempRootFilesystem;
67
+ lock: OwnedTempRootLock;
68
+ clock: Pick<Clock, "nowMs">;
69
+ signal: AbortSignal;
70
+ }, optional?: {
71
+ olderThanMs?: number;
72
+ limit?: number;
73
+ }): Promise<OwnedTempRootSweepReport>;
74
+ //# sourceMappingURL=owned-temp-root.d.ts.map
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Writer-owned temporary roots: a short-lived folder whose owner is provable, so a sweeper can tidy
3
+ * what a crashed writer left behind without ever touching a root that is still in use.
4
+ *
5
+ * Protocol (every writer): take `<root>.lock` first, then write the provenance marker
6
+ * `<root>.owner`, then create `<root>` (mode 0700, name = host prefix + exact UUID). The writer
7
+ * stays inside the lock until its work (child processes, reads, publication) settles, removes the
8
+ * root in `finally`, and removes the marker only once the root is gone. A root therefore never
9
+ * exists without an owner, and a failed removal keeps the writer's provenance on disk.
10
+ *
11
+ * Sweep: only exact `<prefix><uuid>` names in the named parent; links and roots outside the parent
12
+ * are skipped; roots without a marker (written before this protocol, or unconfirmed) are only
13
+ * reported; a marked root is removed only after acquiring its lock (which succeeds only when the
14
+ * recorded owner is proven dead, or released) and re-checking its dev/ino under that exclusion.
15
+ *
16
+ * Accepted deviation from ALGO-P11 §9.7: the design placed this helper in the host
17
+ * (`platform/temp/owned-root.ts`). The protocol is generic, so it lives here; hosts supply the
18
+ * product-specific prefixes, parents, the lock adapter (and through it the liveness probe).
19
+ */
20
+ import { basename, dirname, join } from "node:path";
21
+ import { FileLockTimeoutError } from "@jini-ai/core/contracts/runtime";
22
+ import { errorCodeOf } from "./errno.js";
23
+ export const OWNED_TEMP_ROOT_LOCK_SUFFIX = ".lock";
24
+ export const OWNED_TEMP_ROOT_MARKER_SUFFIX = ".owner";
25
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
26
+ const EXACT_UUID = new RegExp(`^${UUID}$`);
27
+ const PLAIN_PREFIX = /^[A-Za-z0-9._-]+$/;
28
+ const DAY_MS = 86_400_000;
29
+ function ownedRootName(prefix, id) {
30
+ if (!PLAIN_PREFIX.test(prefix) || !EXACT_UUID.test(id))
31
+ throw new RangeError("A temporary folder needs a plain name prefix and an exact lowercase UUID.");
32
+ return prefix + id;
33
+ }
34
+ async function removeOwnedRoot(root, fs, onRemovalError) {
35
+ try {
36
+ await fs.rm(root, { recursive: true, force: true });
37
+ }
38
+ catch (error) {
39
+ // The marker is the writer's durable provenance: kept, the sweeper can finish this removal later.
40
+ onRemovalError?.({ root, error });
41
+ return;
42
+ }
43
+ await fs.rm(root + OWNED_TEMP_ROOT_MARKER_SUFFIX, { force: true });
44
+ }
45
+ /**
46
+ * Runs `work` inside a fresh owned root, holding the root's lock for the whole call.
47
+ * @param required.parent existing folder that holds the roots; @param required.prefix host prefix.
48
+ * @param required.id UUID source; @param required.lock lock adapter; @param required.work the job.
49
+ * @param optional.onRemovalError observer for a failed cleanup (the root and marker then stay).
50
+ * @returns what `work` returns. @throws RangeError for a non-plain prefix or a non-UUID id.
51
+ * @complexity O(work) plus one lock, two creates and two removals.
52
+ */
53
+ export async function withOwnedTempRoot(required, optional = {}) {
54
+ const { parent, prefix, fs, work } = required;
55
+ const root = join(parent, ownedRootName(prefix, required.id()));
56
+ const run = async () => {
57
+ await fs.writeFile(root + OWNED_TEMP_ROOT_MARKER_SUFFIX, JSON.stringify({ version: 1, prefix }), { flag: "wx", mode: 0o600 });
58
+ try {
59
+ await fs.mkdir(root, { mode: 0o700 });
60
+ return await work({ root });
61
+ }
62
+ finally {
63
+ await removeOwnedRoot(root, fs, optional.onRemovalError);
64
+ }
65
+ };
66
+ // staleMs Infinity: a slow writer is never age-evicted; only a proven-dead owner loses its lock.
67
+ return required.lock({ lockPath: root + OWNED_TEMP_ROOT_LOCK_SUFFIX, run }, { staleMs: Infinity });
68
+ }
69
+ const entry = (path, outcome, reason) => ({ path, outcome, reason });
70
+ async function lstatOrUndefined(fs, path) {
71
+ try {
72
+ return await fs.lstat(path);
73
+ }
74
+ catch (error) {
75
+ if (errorCodeOf({ error }) === "ENOENT")
76
+ return undefined;
77
+ throw error;
78
+ }
79
+ }
80
+ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
81
+ /** Distinct exact root names in `names` (from the root itself, its lock or its marker). O(n). */
82
+ function exactRootNames(names, prefix) {
83
+ const exact = new RegExp(`^(${escapeRegExp(prefix)}${UUID})(\\.lock|\\.owner)?$`);
84
+ const bases = new Set();
85
+ for (const name of names) {
86
+ const match = exact.exec(name);
87
+ if (match)
88
+ bases.add(match[1]);
89
+ }
90
+ return [...bases].sort();
91
+ }
92
+ /** Acquire without waiting; `undefined` means another owner is alive or its liveness is unknown. */
93
+ async function tryExclusive(ctx, lockPath, run) {
94
+ for (let attempt = 0; attempt < 2; attempt += 1) {
95
+ try {
96
+ return await ctx.lock({ lockPath, run }, { timeoutMs: 0, staleMs: Infinity });
97
+ }
98
+ catch (error) {
99
+ // withFileLock checks its deadline right after breaking a dead owner's lock, before creating
100
+ // its own; with a zero wait that first attempt reports a timeout. One retry then acquires,
101
+ // while a live (or foreign, unprovable) owner times out again.
102
+ if (!(error instanceof FileLockTimeoutError) && error?.name !== "FileLockTimeoutError")
103
+ throw error;
104
+ }
105
+ }
106
+ return undefined;
107
+ }
108
+ async function contained(ctx, parent, root) {
109
+ const [realParent, realRoot] = await Promise.all([ctx.fs.realpath(parent), ctx.fs.realpath(root)]);
110
+ return dirname(realRoot) === realParent && basename(realRoot) === basename(root);
111
+ }
112
+ async function removeUnderLock(ctx, root, seen) {
113
+ const result = await tryExclusive(ctx, root + OWNED_TEMP_ROOT_LOCK_SUFFIX, async () => {
114
+ const again = await lstatOrUndefined(ctx.fs, root);
115
+ if (!again?.isDirectory() || again.dev !== seen.dev || again.ino !== seen.ino)
116
+ return entry(root, "kept", "changed");
117
+ await ctx.fs.rm(root, { recursive: true, force: true });
118
+ await ctx.fs.rm(root + OWNED_TEMP_ROOT_MARKER_SUFFIX, { force: true });
119
+ return entry(root, "removed", "dead-owner");
120
+ });
121
+ return result ?? entry(root, "kept", "owner-alive");
122
+ }
123
+ /** A lock/marker whose root is absent: a writer died between taking its lock and creating the root. */
124
+ async function sweepOrphan(ctx, root) {
125
+ const files = await Promise.all([OWNED_TEMP_ROOT_LOCK_SUFFIX, OWNED_TEMP_ROOT_MARKER_SUFFIX].map((suffix) => lstatOrUndefined(ctx.fs, root + suffix)));
126
+ const present = files.filter((info) => info !== undefined);
127
+ if (present.length === 0)
128
+ return undefined;
129
+ if (present.some((info) => !info.isFile()))
130
+ return entry(root, "kept", "not-a-directory");
131
+ if (present.some((info) => ctx.nowMs - info.mtimeMs < ctx.olderThanMs))
132
+ return entry(root, "kept", "young");
133
+ // Same stale-break path as a root: acquiring breaks a dead owner's lock; ours is released on exit.
134
+ const result = await tryExclusive(ctx, root + OWNED_TEMP_ROOT_LOCK_SUFFIX, async () => {
135
+ if (await lstatOrUndefined(ctx.fs, root))
136
+ return entry(root, "kept", "changed");
137
+ await ctx.fs.rm(root + OWNED_TEMP_ROOT_MARKER_SUFFIX, { force: true });
138
+ return entry(root, "removed", "orphan-lock");
139
+ });
140
+ return result ?? entry(root, "kept", "owner-alive");
141
+ }
142
+ async function sweepOne(ctx, parent, root) {
143
+ const info = await lstatOrUndefined(ctx.fs, root);
144
+ if (!info)
145
+ return sweepOrphan(ctx, root);
146
+ // lstat never follows links: a symlink named like a root is not a directory here.
147
+ if (!info.isDirectory())
148
+ return entry(root, "kept", "not-a-directory");
149
+ if (!await contained(ctx, parent, root))
150
+ return entry(root, "kept", "outside-root");
151
+ const marker = await lstatOrUndefined(ctx.fs, root + OWNED_TEMP_ROOT_MARKER_SUFFIX);
152
+ if (!marker?.isFile())
153
+ return entry(root, "report-only", await lstatOrUndefined(ctx.fs, root + OWNED_TEMP_ROOT_LOCK_SUFFIX) ? "unconfirmed" : "legacy");
154
+ // Age is only a cheap prefilter. It cannot establish that the owner died: a live writer may hold
155
+ // a root for days (a long import, a paused laptop), so removal still requires the lock below,
156
+ // which only a proven-dead or released owner yields.
157
+ if (ctx.nowMs - info.mtimeMs < ctx.olderThanMs)
158
+ return entry(root, "kept", "young");
159
+ return removeUnderLock(ctx, root, info);
160
+ }
161
+ async function sweepOneSafely(ctx, parent, root) {
162
+ try {
163
+ return await sweepOne(ctx, parent, root);
164
+ }
165
+ catch (error) {
166
+ // Windows reports an open handle as EBUSY/EPERM/EACCES; the next pass retries.
167
+ if (["EBUSY", "EPERM", "EACCES"].includes(errorCodeOf({ error }) ?? ""))
168
+ return entry(root, "kept", "busy");
169
+ throw error;
170
+ }
171
+ }
172
+ /** Why a pass must stop before the next root; abort wins over the limit. */
173
+ function sweepStop({ signal, count, limit }) {
174
+ if (signal.aborted)
175
+ return { truncated: false, aborted: true };
176
+ if (count >= limit)
177
+ return { truncated: true, aborted: false };
178
+ return undefined;
179
+ }
180
+ /**
181
+ * Tidies owned roots left by dead writers in the named parents, reporting everything else.
182
+ * @param required.roots `{ parent, prefix }` pairs; nothing outside them is read or touched.
183
+ * @param required.lock lock adapter whose liveness probe proves owner death; @param required.signal stops between roots.
184
+ * @param optional.olderThanMs minimum root age (default one day); @param optional.limit roots per pass (default 20).
185
+ * @returns one entry per examined root; `truncated` when the limit stopped the pass.
186
+ * @complexity O(n) directory entries plus O(limit) lock attempts and removals.
187
+ */
188
+ export async function sweepOwnedTempRoots(required, optional = {}) {
189
+ const ctx = { fs: required.fs, lock: required.lock, nowMs: required.clock.nowMs(), olderThanMs: optional.olderThanMs ?? DAY_MS };
190
+ const limit = optional.limit ?? 20, entries = [];
191
+ for (const { parent, prefix } of required.roots) {
192
+ for (const name of exactRootNames(await required.fs.readdir(parent), prefix)) {
193
+ const stop = sweepStop({ signal: required.signal, count: entries.length, limit });
194
+ if (stop)
195
+ return { entries, ...stop };
196
+ const result = await sweepOneSafely(ctx, parent, join(parent, name));
197
+ if (result)
198
+ entries.push(result);
199
+ }
200
+ }
201
+ return { entries, truncated: false, aborted: false };
202
+ }
203
+ //# sourceMappingURL=owned-temp-root.js.map
@@ -1,4 +1,5 @@
1
- import type { DurableJsonFile, QuarantineNotice } from "./durable-json.js";
1
+ import type { DurableJsonFile } from "./durable-json.js";
2
+ import type { QuarantineNotice } from "@jini-ai/core/contracts/site/fs-durable-json";
2
3
  /**
3
4
  * Read the persisted state, treating any unreadable or malformed file as "no state yet".
4
5
  *