@jini-ai/platform 0.7.2 → 0.7.3-next.1

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 (169) hide show
  1. package/CHANGELOG.md +2 -8
  2. package/README.md +16 -4
  3. package/dist/asset-cache.d.ts +13 -3
  4. package/dist/asset-cache.js +163 -154
  5. package/dist/blob-storage.d.ts +3 -32
  6. package/dist/blob-storage.js +1 -9
  7. package/dist/child-environment.d.ts +0 -16
  8. package/dist/child-environment.js +0 -25
  9. package/dist/command.d.ts +6 -11
  10. package/dist/command.js +8 -54
  11. package/dist/download-lock.d.ts +4 -0
  12. package/dist/download-lock.js +82 -0
  13. package/dist/download-maintenance.d.ts +5 -0
  14. package/dist/download-maintenance.js +82 -0
  15. package/dist/download-state.d.ts +8 -0
  16. package/dist/download-state.js +126 -0
  17. package/dist/download-store.d.ts +22 -0
  18. package/dist/download-store.js +174 -0
  19. package/dist/download-target.d.ts +10 -0
  20. package/dist/download-target.js +102 -0
  21. package/dist/download-transfer.d.ts +12 -0
  22. package/dist/download-transfer.js +174 -0
  23. package/dist/download-types.d.ts +162 -0
  24. package/dist/download-types.js +31 -0
  25. package/dist/download.d.ts +1 -89
  26. package/dist/download.js +8 -738
  27. package/dist/fetch-with-timeout.d.ts +7 -32
  28. package/dist/fetch-with-timeout.js +1 -77
  29. package/dist/fs/app-data-root.d.ts +28 -0
  30. package/dist/fs/app-data-root.js +35 -0
  31. package/dist/fs/atomic-write.js +1 -1
  32. package/dist/fs/boot-identity.d.ts +1 -4
  33. package/dist/fs/directory-delete-guard.d.ts +93 -0
  34. package/dist/fs/directory-delete-guard.js +148 -0
  35. package/dist/fs/directory-registry.js +45 -35
  36. package/dist/fs/directory-relocation.d.ts +82 -0
  37. package/dist/fs/directory-relocation.js +99 -0
  38. package/dist/fs/directory-running-lock.d.ts +1 -1
  39. package/dist/fs/directory-running-lock.js +24 -21
  40. package/dist/fs/directory-sync.js +1 -1
  41. package/dist/fs/directory-user-config.js +30 -3
  42. package/dist/fs/directory-workspace.d.ts +34 -30
  43. package/dist/fs/directory-workspace.js +70 -29
  44. package/dist/fs/durable-json.d.ts +6 -15
  45. package/dist/fs/durable-json.js +38 -35
  46. package/dist/fs/errno.d.ts +12 -3
  47. package/dist/fs/errno.js +5 -3
  48. package/dist/fs/file-lock.d.ts +3 -87
  49. package/dist/fs/file-lock.js +16 -30
  50. package/dist/fs/guarded-reader.js +335 -315
  51. package/dist/fs/index.d.ts +5 -0
  52. package/dist/fs/index.js +5 -0
  53. package/dist/fs/recent-directories.d.ts +46 -0
  54. package/dist/fs/recent-directories.js +68 -0
  55. package/dist/fs/remove-directory-tree.d.ts +20 -0
  56. package/dist/fs/remove-directory-tree.js +28 -0
  57. package/dist/fs/user-data-directories.js +2 -2
  58. package/dist/fs/workspace-directory.js +2 -1
  59. package/dist/fs.d.ts +16 -4
  60. package/dist/fs.js +4 -4
  61. package/dist/home-expansion.d.ts +7 -2
  62. package/dist/home-expansion.js +3 -3
  63. package/dist/http/guarded/client.d.ts +1 -2
  64. package/dist/http/guarded/client.js +2 -1
  65. package/dist/http/guarded/index.d.ts +0 -3
  66. package/dist/http/guarded/node-ports.d.ts +1 -1
  67. package/dist/http/guarded/transport.fetch.d.ts +2 -3
  68. package/dist/http/guarded/transport.fetch.js +64 -58
  69. package/dist/http.d.ts +3 -1
  70. package/dist/http.js +2 -2
  71. package/dist/index.d.ts +10 -11
  72. package/dist/index.js +7 -6
  73. package/dist/mail/activity/activity.d.ts +136 -0
  74. package/dist/mail/activity/activity.js +172 -0
  75. package/dist/mail/activity/ports.d.ts +113 -0
  76. package/dist/mail/activity/suppressions.d.ts +82 -0
  77. package/dist/mail/activity/suppressions.js +119 -0
  78. package/dist/mail/activity/vocabulary.d.ts +10 -0
  79. package/dist/mail/activity/vocabulary.js +8 -0
  80. package/dist/mail/builtin-providers.d.ts +12 -6
  81. package/dist/mail/builtin-providers.js +14 -11
  82. package/dist/mail/delivery-wrapper.js +2 -1
  83. package/dist/mail/email-sender-registry.d.ts +1 -1
  84. package/dist/mail/email-sender-registry.js +1 -1
  85. package/dist/mail/email-template-operations.d.ts +186 -0
  86. package/dist/mail/email-template-operations.js +226 -0
  87. package/dist/mail/email-template.d.ts +120 -0
  88. package/dist/mail/email-template.js +243 -0
  89. package/dist/mail/index.d.ts +4 -0
  90. package/dist/mail/index.js +3 -0
  91. package/dist/mail/prepare-sender-email.d.ts +1 -10
  92. package/dist/mail/prepare-sender-email.js +1 -11
  93. package/dist/mail/resolve-mailer.d.ts +2 -1
  94. package/dist/mail/resolve-mailer.js +5 -2
  95. package/dist/mail/senders.d.ts +0 -1
  96. package/dist/mail/senders.js +0 -1
  97. package/dist/mail/smtp.d.ts +1 -31
  98. package/dist/net/address.d.ts +1 -8
  99. package/dist/net/address.js +1 -18
  100. package/dist/net/index.d.ts +1 -1
  101. package/dist/net/index.js +1 -1
  102. package/dist/net/local-http-probe.js +1 -1
  103. package/dist/net/local-http-request.js +1 -1
  104. package/dist/process-probes.d.ts +36 -0
  105. package/dist/process-probes.js +151 -0
  106. package/dist/process-top-footprint.d.ts +7 -0
  107. package/dist/process-top-footprint.js +30 -0
  108. package/dist/process.d.ts +29 -31
  109. package/dist/process.js +18 -196
  110. package/dist/proxy-env.d.ts +12 -3
  111. package/dist/proxy-env.js +9 -8
  112. package/dist/resource-paths.d.ts +15 -3
  113. package/dist/resource-paths.js +7 -5
  114. package/dist/sandbox-env.d.ts +26 -5
  115. package/dist/sandbox-env.js +7 -7
  116. package/dist/secrets/credential-sets/contracts.d.ts +0 -1
  117. package/dist/secrets/credential-sets/contracts.js +0 -1
  118. package/dist/secrets/credential-sets/index.d.ts +2 -3
  119. package/dist/secrets/credential-sets/index.js +1 -1
  120. package/dist/secrets/credential-sets/provider-matches.d.ts +1 -1
  121. package/dist/secrets/credential-sets/provider-matches.js +1 -1
  122. package/dist/secrets/credential-sets/vault-archive.d.ts +1 -1
  123. package/dist/secrets/credential-sets/vault-archive.js +14 -8
  124. package/dist/secrets/credential-sets/vault.aad.d.ts +1 -1
  125. package/dist/secrets/credential-sets/vault.meta.d.ts +1 -1
  126. package/dist/secrets/credential-sets/vault.meta.js +1 -1
  127. package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -1
  128. package/dist/secrets/credential-sets/vault.repo.memory.js +1 -1
  129. package/dist/secrets/credential-sets/vault.reseal-refused.d.ts +23 -0
  130. package/dist/secrets/credential-sets/vault.reseal-refused.js +36 -0
  131. package/dist/secrets/credential-sets/vault.service.d.ts +25 -5
  132. package/dist/secrets/credential-sets/vault.service.js +42 -8
  133. package/dist/secrets/index.d.ts +0 -3
  134. package/dist/secrets/index.js +5 -0
  135. package/dist/secrets/keyring.env.d.ts +1 -1
  136. package/dist/secrets/legacy-owner.d.ts +61 -0
  137. package/dist/secrets/legacy-owner.js +196 -0
  138. package/dist/secrets/root-key/decide.d.ts +89 -0
  139. package/dist/secrets/root-key/decide.js +60 -0
  140. package/dist/secrets/sealer-contract.d.ts +19 -0
  141. package/dist/secrets/sealer-contract.js +37 -0
  142. package/dist/secrets/secret-sealer.aesgcm.d.ts +1 -1
  143. package/dist/secrets/testing.d.ts +1 -0
  144. package/dist/secrets/testing.js +1 -0
  145. package/dist/shell.d.ts +4 -1
  146. package/dist/shell.js +1 -1
  147. package/dist/system.d.ts +6 -0
  148. package/dist/system.js +9 -0
  149. package/dist/terminal.d.ts +11 -96
  150. package/dist/terminal.js +80 -56
  151. package/dist/web/agent-tools.d.ts +107 -0
  152. package/dist/web/agent-tools.js +49 -0
  153. package/dist/web/index.d.ts +1 -0
  154. package/dist/web/index.js +1 -0
  155. package/package.json +38 -12
  156. package/dist/http/guarded/ports.d.ts +0 -56
  157. package/dist/http/guarded/types.d.ts +0 -8
  158. package/dist/http/guarded/types.js +0 -2
  159. package/dist/mail/email-sender.d.ts +0 -109
  160. package/dist/mail/email-sender.js +0 -10
  161. package/dist/net/endpoint-policy.d.ts +0 -39
  162. package/dist/net/endpoint-policy.js +0 -218
  163. package/dist/secrets/credential-sets/aad.d.ts +0 -7
  164. package/dist/secrets/credential-sets/aad.js +0 -7
  165. package/dist/secrets/credential-sets/repo.memory.d.ts +0 -44
  166. package/dist/secrets/credential-sets/repo.memory.js +0 -80
  167. package/dist/secrets/credential-sets/vault.types.d.ts +0 -27
  168. package/dist/secrets/credential-sets/vault.types.js +0 -49
  169. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
@@ -51,6 +51,7 @@
51
51
  * serving `index.js`: throws at import time) — see the 2026-08-17 Jini hardening report. Browser
52
52
  * call sites should import from this subpath, never the root barrel.
53
53
  */
54
+ import type { TextReadOptions } from "@jini-ai/core/net";
54
55
  /** Thrown in place of the platform's generic abort error specifically when the timeout — not a
55
56
  * caller-supplied `init.signal` — is what ended the call, so a caller can tell "this took too long"
56
57
  * apart from "I cancelled it myself" without string-matching an error message. */
@@ -67,31 +68,8 @@ export declare class ResponseLimitExceededError extends RangeError {
67
68
  limitBytes: number;
68
69
  }, _options?: Record<string, never>);
69
70
  }
70
- /**
71
- * Shared, documented timeout classes for outbound `fetch()` calls. Every call site names one
72
- * explicitly (or its own justified number) rather than relying on an unstated default.
73
- */
74
- export declare const FETCH_TIMEOUT_MS: {
75
- /** A single metadata/status/API-read call expected to return quickly: a model catalog listing, a
76
- * connection test, a GitHub API read, an LLM provider's non-streaming completion call. */
77
- readonly QUICK: 15000;
78
- /** A deploy-provider API call that may involve real backend work on the provider's side — site
79
- * creation, DNS record lookups, deployment status polling. */
80
- readonly DEPLOY: 30000;
81
- /** A large-payload transfer: an asset/blob upload, a generated-media byte fetch. */
82
- readonly UPLOAD: 120000;
83
- /** A media-generation API call whose response only arrives once the vendor has actually finished
84
- * generating the image/video/audio server-side — routinely minutes, not seconds. Matches the
85
- * value OpenAI's and OpenRouter's own image providers already hardcode locally
86
- * (`OPENAI_IMAGE_*_TIMEOUT_MS`/`OPENROUTER_IMAGE_TIMEOUT_MS`); used as the shared dispatch-level
87
- * backstop in `@jini-ai/integrations`' `dispatchVendorRequest` for every OTHER vendor that (as of
88
- * 2026-08-16) sets no timeout of its own at all. Deliberately NOT the same as `UPLOAD`: a backstop
89
- * shorter than a vendor's own already-correct 10-minute generation timeout would abort a
90
- * legitimately still-generating request early. */
91
- readonly GENERATE: number;
92
- };
93
71
  export interface FetchWithTimeoutOptions {
94
- /** Milliseconds before the call is aborted. Pick one of {@link FETCH_TIMEOUT_MS}, or a specific
72
+ /** Milliseconds before the call is aborted. Pick one of `FETCH_TIMEOUT_MS` from `@jini-ai/core/net`, or a specific
95
73
  * justified number for a call site that doesn't fit those classes. */
96
74
  timeoutMs: number;
97
75
  /** Host-supplied transport; defaults to the global fetch. */
@@ -130,13 +108,6 @@ export declare function createDeadlineSignal({ waitMs }: {
130
108
  signal: AbortSignal;
131
109
  dispose: () => void;
132
110
  };
133
- /** Opt-in byte and decoding guards; defaults remain unlimited and replacement-decoded. */
134
- export type TextReadOptions = {
135
- /** Nonnegative safe integer. Actual streamed bytes, independent of Content-Length. */
136
- maxResponseBytes?: number;
137
- /** Reject malformed UTF-8, including an incomplete trailing character. */
138
- strictUtf8?: boolean;
139
- };
140
111
  /**
141
112
  * Consumes a response as UTF-8, checking bytes before decoding/retaining each chunk.
142
113
  * Details mode reports retained source bytes and truncates only on observed overflow;
@@ -181,7 +152,11 @@ export declare function readFetchResponseText({ response }: {
181
152
  * `init.signal` (if any) did not itself already abort. Any other rejection (a caller's own abort, a
182
153
  * genuine network error) propagates unchanged.
183
154
  */
184
- export declare function fetchWithTimeout(url: string | URL, init: RequestInit | undefined, options: FetchWithTimeoutOptions): Promise<Response>;
155
+ export declare function fetchWithTimeout({ url, ...options }: {
156
+ url: string | URL;
157
+ } & FetchWithTimeoutOptions, { init }?: {
158
+ init?: RequestInit | undefined;
159
+ }): Promise<Response>;
185
160
  /**
186
161
  * Fetches and consumes text inside one timeout scope. The returned response keeps its metadata
187
162
  * and has a consumed body. No retries; other fetch/read errors propagate unchanged.
@@ -1,56 +1,3 @@
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
1
  /** Thrown in place of the platform's generic abort error specifically when the timeout — not a
55
2
  * caller-supplied `init.signal` — is what ended the call, so a caller can tell "this took too long"
56
3
  * apart from "I cancelled it myself" without string-matching an error message. */
@@ -74,29 +21,6 @@ export class ResponseLimitExceededError extends RangeError {
74
21
  this.limitBytes = limitBytes;
75
22
  }
76
23
  }
77
- /**
78
- * Shared, documented timeout classes for outbound `fetch()` calls. Every call site names one
79
- * explicitly (or its own justified number) rather than relying on an unstated default.
80
- */
81
- export const FETCH_TIMEOUT_MS = {
82
- /** A single metadata/status/API-read call expected to return quickly: a model catalog listing, a
83
- * connection test, a GitHub API read, an LLM provider's non-streaming completion call. */
84
- QUICK: 15_000,
85
- /** A deploy-provider API call that may involve real backend work on the provider's side — site
86
- * creation, DNS record lookups, deployment status polling. */
87
- DEPLOY: 30_000,
88
- /** A large-payload transfer: an asset/blob upload, a generated-media byte fetch. */
89
- UPLOAD: 120_000,
90
- /** A media-generation API call whose response only arrives once the vendor has actually finished
91
- * generating the image/video/audio server-side — routinely minutes, not seconds. Matches the
92
- * value OpenAI's and OpenRouter's own image providers already hardcode locally
93
- * (`OPENAI_IMAGE_*_TIMEOUT_MS`/`OPENROUTER_IMAGE_TIMEOUT_MS`); used as the shared dispatch-level
94
- * backstop in `@jini-ai/integrations`' `dispatchVendorRequest` for every OTHER vendor that (as of
95
- * 2026-08-16) sets no timeout of its own at all. Deliberately NOT the same as `UPLOAD`: a backstop
96
- * shorter than a vendor's own already-correct 10-minute generation timeout would abort a
97
- * legitimately still-generating request early. */
98
- GENERATE: 10 * 60_000,
99
- };
100
24
  /** Browser-safe timer adapter; completion and cancellation both release its listener. */
101
25
  function waitForDeadline({ ms, signal }, _options = {}) {
102
26
  return new Promise((resolve, reject) => {
@@ -261,7 +185,7 @@ async function readResponseChunk({ reader, signal }) {
261
185
  * `init.signal` (if any) did not itself already abort. Any other rejection (a caller's own abort, a
262
186
  * genuine network error) propagates unchanged.
263
187
  */
264
- export async function fetchWithTimeout(url, init = {}, options) {
188
+ export async function fetchWithTimeout({ url, ...options }, { init = {} } = {}) {
265
189
  return executeFetchWithTimeout({ url, init, timeoutMs: options.timeoutMs, consume: async ({ response }) => response }, options);
266
190
  }
267
191
  /**
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Electron's per-user application-data root (`app.getPath('appData')`), without Electron.
3
+ * The table keeps each platform's rule independently correctable. Linux honors XDG_CONFIG_HOME
4
+ * and Windows uses APPDATA because Electron does, with conventional fallbacks for stripped envs.
5
+ * Returns undefined when the platform has no known convention; reads no host state or files.
6
+ * @complexity O(1) — a fixed platform table.
7
+ */
8
+ export declare function resolveElectronAppDataRoot(required: {
9
+ platform: NodeJS.Platform;
10
+ env: NodeJS.ProcessEnv;
11
+ homeDir: string;
12
+ }, _optional?: Record<string, never>): string | undefined;
13
+ /**
14
+ * `<appDataRoot>/<appName>`: Electron's default userData for a packaged-name-less dev app.
15
+ * This mirrors Electron rather than deriving the answer from it, a risk: if its convention or
16
+ * the app name changes, callers can silently target a directory the application does not use.
17
+ * Windows paths use win32 syntax even on another host; all other paths use POSIX syntax.
18
+ * Returns undefined for an unknown platform; creates and checks no directories.
19
+ * @throws {Error} If appName is empty.
20
+ * @complexity O(1) — a fixed platform lookup and path join.
21
+ */
22
+ export declare function resolveElectronUserDataDir(required: {
23
+ platform: NodeJS.Platform;
24
+ env: NodeJS.ProcessEnv;
25
+ homeDir: string;
26
+ appName: string;
27
+ }, _optional?: Record<string, never>): string | undefined;
28
+ //# sourceMappingURL=app-data-root.d.ts.map
@@ -0,0 +1,35 @@
1
+ import path from "node:path";
2
+ const APP_DATA_ROOTS = Object.freeze({
3
+ darwin: ({ homeDir }) => path.posix.join(homeDir, "Library", "Application Support"),
4
+ win32: ({ env, homeDir }) => env.APPDATA?.trim() || path.win32.join(homeDir, "AppData", "Roaming"),
5
+ linux: ({ env, homeDir }) => env.XDG_CONFIG_HOME?.trim() || path.posix.join(homeDir, ".config"),
6
+ });
7
+ /**
8
+ * Electron's per-user application-data root (`app.getPath('appData')`), without Electron.
9
+ * The table keeps each platform's rule independently correctable. Linux honors XDG_CONFIG_HOME
10
+ * and Windows uses APPDATA because Electron does, with conventional fallbacks for stripped envs.
11
+ * Returns undefined when the platform has no known convention; reads no host state or files.
12
+ * @complexity O(1) — a fixed platform table.
13
+ */
14
+ export function resolveElectronAppDataRoot(required, _optional = {}) {
15
+ return APP_DATA_ROOTS[required.platform]?.(required);
16
+ }
17
+ /**
18
+ * `<appDataRoot>/<appName>`: Electron's default userData for a packaged-name-less dev app.
19
+ * This mirrors Electron rather than deriving the answer from it, a risk: if its convention or
20
+ * the app name changes, callers can silently target a directory the application does not use.
21
+ * Windows paths use win32 syntax even on another host; all other paths use POSIX syntax.
22
+ * Returns undefined for an unknown platform; creates and checks no directories.
23
+ * @throws {Error} If appName is empty.
24
+ * @complexity O(1) — a fixed platform lookup and path join.
25
+ */
26
+ export function resolveElectronUserDataDir(required, _optional = {}) {
27
+ if (required.appName.length === 0)
28
+ throw new Error("appName must be a non-empty string.");
29
+ const root = resolveElectronAppDataRoot(required);
30
+ if (root === undefined)
31
+ return undefined;
32
+ const paths = required.platform === "win32" ? path.win32 : path.posix;
33
+ return paths.join(root, required.appName);
34
+ }
35
+ //# sourceMappingURL=app-data-root.js.map
@@ -20,7 +20,7 @@ export function createNodeAtomicFilesystem(_required, { filesystem = fs } = {})
20
20
  }
21
21
  const DIRECTORY_SYNC_UNSUPPORTED = ["EPERM", "EISDIR", "EINVAL", "EACCES", "ENOTSUP"];
22
22
  function hasErrorCode(error, codes) {
23
- const code = errorCodeOf(error);
23
+ const code = errorCodeOf({ error });
24
24
  return code !== undefined && codes.includes(code);
25
25
  }
26
26
  function isMissing(error) {
@@ -1,7 +1,4 @@
1
- export interface BootIdentity {
2
- id: string;
3
- startedAtMs: number;
4
- }
1
+ import type { BootIdentity } from "@jini-ai/core/contracts/runtime";
5
2
  /** Kernel boot identity distinguishes a recycled PID across reboots. Unknown identity fails safe
6
3
  * to the existing liveness probe; no age timeout is used to evict a potentially live owner.
7
4
  * Native calls are bounded and cached once per process. @complexity O(1) bounded OS reads.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The identity a site carries in its own directory — the configured marker file's identity field, the UUID
3
+ * the host stamps once at creation and nothing afterwards rewrites.
4
+ *
5
+ * Chosen over an inode/device pair on purpose. Both distinguish "the site I created" from "whatever
6
+ * is at that path now", but `st_dev` is a property of the MOUNT, not of the directory: it is free to
7
+ * change across a reboot or a re-mounted external volume, which would silently downgrade every
8
+ * later delete of a perfectly ordinary project to a card-removal. The recorded identity is content the site
9
+ * carries with it — it survives a move, a reboot, a copy, and a restore from backup, and a
10
+ * DIFFERENT site has a different one, which is exactly the discrimination this guard needs.
11
+ *
12
+ * @returns the site's id, or `null` when the directory is absent, unreadable, holds no
13
+ * marker metadata, holds one that is not JSON, or holds one with no usable identity — every one
14
+ * of which is "cannot prove identity", and all of which the caller must treat identically.
15
+ * @complexity O(1) — one file read.
16
+ */
17
+ export declare function readDirectoryIdentity({ directory, markerFile, identityField }: {
18
+ directory: string;
19
+ markerFile: string;
20
+ identityField: string;
21
+ }, { readText }?: {
22
+ readText?: ((file: string) => string) | undefined;
23
+ }): string | null;
24
+ /**
25
+ * `target` with every symlink resolved and the path normalized, so a containment test cannot be
26
+ * defeated by `..`, a trailing slash, a relative segment, or a site dir that is itself a symlink
27
+ * pointing into the repo.
28
+ *
29
+ * `realpathSync.native` rather than the JS implementation on purpose: on macOS the native call also
30
+ * returns the directory's canonical on-disk CASE, so a case-insensitive filesystem cannot be used to
31
+ * smuggle `/repo/Sites/example-project` past a comparison against `/repo/sites`.
32
+ *
33
+ * A path whose LEAF does not exist still resolves correctly: the deepest existing ancestor is
34
+ * resolved and the remaining segments are re-appended to it. Resolving only whole paths would leave
35
+ * a moved-or-deleted site dir under a symlinked checkout comparing as OUTSIDE the repo it is plainly
36
+ * in — the wrong answer in the dangerous direction — because one side of the comparison would have
37
+ * followed the symlink and the other would not.
38
+ *
39
+ * The canonicalizer returns the resolved absolute path. It falls back to `path.resolve`'s plain normalization (which
40
+ * still collapses `..` and trailing slashes) only when not even the filesystem root resolves.
41
+ * It takes O(depth) stat calls, worst case one per path segment.
42
+ *
43
+ * Whether `target` is `container` itself or lives somewhere beneath it, compared on resolved real
44
+ * paths.
45
+ *
46
+ * `path.relative` rather than a `startsWith` prefix test: `startsWith` would report `/repo-backup`
47
+ * as being inside `/repo` (a false positive that refuses a legitimate delete) and would be defeated
48
+ * by any `..` the caller had not normalized away. A relative path that is empty means "the same
49
+ * directory"; one that neither starts with `..` nor is itself absolute means "below".
50
+ *
51
+ * @complexity O(depth) — two {@link canonicalNodeDirectory} calls plus a string compare.
52
+ */
53
+ export declare function isInsideDirectory({ target, container }: {
54
+ target: string;
55
+ container: string;
56
+ }, _optional?: Record<string, never>): boolean;
57
+ /**
58
+ * Whether deleting `row`'s project may erase its directory from disk, or must only drop its card.
59
+ *
60
+ * The single authority for that decision. `handleDelete` calls it, and `buildSiteRecord` calls it
61
+ * too so the renderer can label the button with what will actually happen — the UI must never be
62
+ * left to re-derive this rule for itself and drift from it.
63
+ *
64
+ * @param required.row a row from `readTrackedSites`, whose `origin` is already normalized fail-closed by that
65
+ * function. `identity` is present only on rows `trackSite` wrote as `created` once identity
66
+ * recording existed. Typed loosely (every field `unknown`) because a hand-edited registry file, or
67
+ * a row written before a field existed, must be refused rather than crash this check.
68
+ * @param required.protectedRoot the host-protected checkout root. A missing or non-string value refuses everything:
69
+ * containment cannot be PROVEN without it, and this module never permits what it cannot prove.
70
+ * `main.ts` always supplies it, so that arm is a guard against a future miswiring, not a
71
+ * reachable operator state.
72
+ * @returns `true` only when the app created the directory, it lives outside the repo, AND the site
73
+ * at that path is still the one the app created.
74
+ * @complexity O(depth) — {@link isInsideDirectory}'s cost plus one file read, and only for a
75
+ * `created` row.
76
+ */
77
+ export declare function mayEraseDirectory({ row, createdOrigin, protectedRoot, markerFile, identityField }: {
78
+ /** A recorded row may be garbage, missing, or of the wrong type (a hand-edited registry
79
+ * or a fail-closed fixture); refuse rather than throw or admit it. */
80
+ row: {
81
+ directory?: unknown;
82
+ origin?: unknown;
83
+ identity?: unknown;
84
+ } | undefined;
85
+ createdOrigin: string;
86
+ /** The protected-root input is as loosely typed as the recorded row fields. */
87
+ protectedRoot: unknown;
88
+ markerFile: string;
89
+ identityField: string;
90
+ }, { readText }?: {
91
+ readText?: ((file: string) => string) | undefined;
92
+ }): boolean;
93
+ //# sourceMappingURL=directory-delete-guard.d.ts.map
@@ -0,0 +1,148 @@
1
+ /**
2
+ * @file The one rule that stands between a two-click card overlay and `fs.rm(dir, {recursive: true,
3
+ * force: true})`.
4
+ *
5
+ * `project-ipc.ts`'s `handleDelete` erases a project's whole install directory — `content.db`,
6
+ * `uploads/`, `themes/`, `agent-plugins/` — with no backup and no OS trash, because that is the
7
+ * honest meaning of "delete this project" for a project the app itself provisioned. It is NOT the
8
+ * honest meaning for a directory the app merely ADOPTED. `main.ts` seeds the Projects screen with
9
+ * `<repo>/sites/example-project` (`seedDevFallbackSite`), a git-tracked folder holding a real production
10
+ * database that this app did not create a single byte of; the moment that folder classifies as a
11
+ * site, a card for it appears and two clicks would destroy it.
12
+ *
13
+ * **Three independent tests, all of which must pass before anything is erased:**
14
+ *
15
+ * 1. *Provenance* (`createdOrigin`) — only a row this app recorded as `created` is erasable.
16
+ * This is the general rule: it protects every adopted folder anywhere on the disk, not just the
17
+ * ones that happen to live in a checkout.
18
+ * 2. *Containment* — nothing under `protectedRoot` is erasable, whatever its row claims. This is the
19
+ * backstop for the specific asset at risk, and it survives a row whose provenance is wrong:
20
+ * a hand-edited `desktop-projects.json`, a future seeding path that forgets to say `adopted`, or
21
+ * an operator who points "+ Create website" at a folder inside the checkout.
22
+ * 3. *Identity* ({@link isStillTheRecordedDirectory}) — the site actually living at that path right now
23
+ * must be the same site whose creation produced the row. Tests 1 and 2 are both properties of the
24
+ * ROW, and a row is a path string in a JSON file; a path is not an identity. An operator who moves
25
+ * their site elsewhere and lets something else take its old path leaves a row whose provenance and
26
+ * containment are both still perfectly true about a directory this app never made — and the card
27
+ * even renders under the NEW site's name, since `readSiteName` reads whatever `config.json` is
28
+ * there now. No amount of reasoning about the row can catch
29
+ * it: only asking the live directory who it is can.
30
+ *
31
+ * No test subsumes another, which is why all three are here rather than one. All fail CLOSED:
32
+ * anything this module cannot positively prove safe is refused, and a refusal costs the operator a
33
+ * leftover folder they can delete in Finder, while a wrong permission costs them their content.
34
+ *
35
+ * **Consequence of test 3, stated rather than hidden:** a `created` row written before identity was
36
+ * recorded carries no `identity`, so it is refused and its delete removes the card only. That is the
37
+ * fail-closed direction — the alternative would be to trust exactly the rows this test exists to
38
+ * distrust — and it self-corrects for every project created from here on.
39
+ *
40
+ * No `electron` import, so all of it is testable under plain `node --test` — same convention as
41
+ * `tracked-sites.ts` and `site-dir-store.ts`.
42
+ */
43
+ import fs from "node:fs";
44
+ import path from "node:path";
45
+ import { orFallbackSync } from "@jini-ai/core/errors/idioms";
46
+ import { canonicalNodeDirectory } from "./directory-workspace.js";
47
+ /**
48
+ * The identity a site carries in its own directory — the configured marker file's identity field, the UUID
49
+ * the host stamps once at creation and nothing afterwards rewrites.
50
+ *
51
+ * Chosen over an inode/device pair on purpose. Both distinguish "the site I created" from "whatever
52
+ * is at that path now", but `st_dev` is a property of the MOUNT, not of the directory: it is free to
53
+ * change across a reboot or a re-mounted external volume, which would silently downgrade every
54
+ * later delete of a perfectly ordinary project to a card-removal. The recorded identity is content the site
55
+ * carries with it — it survives a move, a reboot, a copy, and a restore from backup, and a
56
+ * DIFFERENT site has a different one, which is exactly the discrimination this guard needs.
57
+ *
58
+ * @returns the site's id, or `null` when the directory is absent, unreadable, holds no
59
+ * marker metadata, holds one that is not JSON, or holds one with no usable identity — every one
60
+ * of which is "cannot prove identity", and all of which the caller must treat identically.
61
+ * @complexity O(1) — one file read.
62
+ */
63
+ export function readDirectoryIdentity({ directory, markerFile, identityField }, { readText = (file) => fs.readFileSync(file, "utf8") } = {}) {
64
+ return orFallbackSync({ work: () => {
65
+ const meta = JSON.parse(readText(path.join(directory, markerFile)));
66
+ const identity = meta?.[identityField];
67
+ return typeof identity === "string" && identity !== "" ? identity : null;
68
+ }, fallback: null, step: "directory identity marker" });
69
+ }
70
+ /**
71
+ * Whether the site living at `row.directory` right now is the one whose creation wrote `row`.
72
+ *
73
+ * A row with no recorded `identity` (written before this test existed, or hand-edited) can never
74
+ * satisfy this — it has nothing to compare — so it is refused rather than grandfathered.
75
+ *
76
+ * @complexity O(1) beyond {@link readDirectoryIdentity}'s own file read.
77
+ */
78
+ function isStillTheRecordedDirectory({ row, markerFile, identityField }, { readText } = {}) {
79
+ if (typeof row?.identity !== "string" || row.identity === "")
80
+ return false;
81
+ return readDirectoryIdentity({ directory: row.directory, markerFile, identityField }, { readText }) === row.identity;
82
+ }
83
+ /**
84
+ * `target` with every symlink resolved and the path normalized, so a containment test cannot be
85
+ * defeated by `..`, a trailing slash, a relative segment, or a site dir that is itself a symlink
86
+ * pointing into the repo.
87
+ *
88
+ * `realpathSync.native` rather than the JS implementation on purpose: on macOS the native call also
89
+ * returns the directory's canonical on-disk CASE, so a case-insensitive filesystem cannot be used to
90
+ * smuggle `/repo/Sites/example-project` past a comparison against `/repo/sites`.
91
+ *
92
+ * A path whose LEAF does not exist still resolves correctly: the deepest existing ancestor is
93
+ * resolved and the remaining segments are re-appended to it. Resolving only whole paths would leave
94
+ * a moved-or-deleted site dir under a symlinked checkout comparing as OUTSIDE the repo it is plainly
95
+ * in — the wrong answer in the dangerous direction — because one side of the comparison would have
96
+ * followed the symlink and the other would not.
97
+ *
98
+ * The canonicalizer returns the resolved absolute path. It falls back to `path.resolve`'s plain normalization (which
99
+ * still collapses `..` and trailing slashes) only when not even the filesystem root resolves.
100
+ * It takes O(depth) stat calls, worst case one per path segment.
101
+ *
102
+ * Whether `target` is `container` itself or lives somewhere beneath it, compared on resolved real
103
+ * paths.
104
+ *
105
+ * `path.relative` rather than a `startsWith` prefix test: `startsWith` would report `/repo-backup`
106
+ * as being inside `/repo` (a false positive that refuses a legitimate delete) and would be defeated
107
+ * by any `..` the caller had not normalized away. A relative path that is empty means "the same
108
+ * directory"; one that neither starts with `..` nor is itself absolute means "below".
109
+ *
110
+ * @complexity O(depth) — two {@link canonicalNodeDirectory} calls plus a string compare.
111
+ */
112
+ export function isInsideDirectory({ target, container }, _optional = {}) {
113
+ const relative = path.relative(canonicalNodeDirectory({ path: path.resolve(container) }, { realpath: fs.realpathSync.native, fallbackOnAnyError: true }), canonicalNodeDirectory({ path: path.resolve(target) }, { realpath: fs.realpathSync.native, fallbackOnAnyError: true }));
114
+ if (relative === "")
115
+ return true;
116
+ return !relative.startsWith("..") && !path.isAbsolute(relative);
117
+ }
118
+ /**
119
+ * Whether deleting `row`'s project may erase its directory from disk, or must only drop its card.
120
+ *
121
+ * The single authority for that decision. `handleDelete` calls it, and `buildSiteRecord` calls it
122
+ * too so the renderer can label the button with what will actually happen — the UI must never be
123
+ * left to re-derive this rule for itself and drift from it.
124
+ *
125
+ * @param required.row a row from `readTrackedSites`, whose `origin` is already normalized fail-closed by that
126
+ * function. `identity` is present only on rows `trackSite` wrote as `created` once identity
127
+ * recording existed. Typed loosely (every field `unknown`) because a hand-edited registry file, or
128
+ * a row written before a field existed, must be refused rather than crash this check.
129
+ * @param required.protectedRoot the host-protected checkout root. A missing or non-string value refuses everything:
130
+ * containment cannot be PROVEN without it, and this module never permits what it cannot prove.
131
+ * `main.ts` always supplies it, so that arm is a guard against a future miswiring, not a
132
+ * reachable operator state.
133
+ * @returns `true` only when the app created the directory, it lives outside the repo, AND the site
134
+ * at that path is still the one the app created.
135
+ * @complexity O(depth) — {@link isInsideDirectory}'s cost plus one file read, and only for a
136
+ * `created` row.
137
+ */
138
+ export function mayEraseDirectory({ row, createdOrigin, protectedRoot, markerFile, identityField }, { readText } = {}) {
139
+ if (row?.origin !== createdOrigin)
140
+ return false;
141
+ if (typeof protectedRoot !== "string" || protectedRoot === "")
142
+ return false;
143
+ if (!isStillTheRecordedDirectory({ row, markerFile, identityField }, { readText }))
144
+ return false;
145
+ // The identity check above refuses an undefined row, but does not narrow it for TypeScript.
146
+ return !isInsideDirectory({ target: row.directory, container: protectedRoot });
147
+ }
148
+ //# sourceMappingURL=directory-delete-guard.js.map
@@ -1,3 +1,43 @@
1
+ /** Load and shape-check the catalog; anything unreadable or malformed fails closed without overwriting. */
2
+ function readRegistryState({ file }) {
3
+ const result = file.read({});
4
+ if (result.state === "missing")
5
+ return { version: 1, entries: [], migrations: [] };
6
+ if (result.state !== "ok")
7
+ throw new Error("The shared directory registry is unreadable; nothing was overwritten.");
8
+ const state = result.value;
9
+ const shapeOk = state?.version === 1 && Array.isArray(state.entries) && Array.isArray(state.migrations);
10
+ if (!shapeOk || !state.migrations.every((item) => typeof item === "string") || !state.entries.every(validRecord)) {
11
+ throw new Error("The shared directory registry has an invalid format; nothing was overwritten.");
12
+ }
13
+ return state;
14
+ }
15
+ /** Fold incoming records and migration markers into the state; a migration already applied is a no-op. */
16
+ function mergeRegistryState({ state, entries, migration, migrations, canonical }) {
17
+ if (migration && state.migrations.includes(migration))
18
+ return { result: state.entries, next: state };
19
+ const byPath = new Map(state.entries.map((entry) => [canonical(entry.path), { ...entry, path: canonical(entry.path) }]));
20
+ const byId = new Map([...byPath.values()].map((entry) => [entry.id, entry.path]));
21
+ for (const entry of entries)
22
+ mergeEntry({ entry, byPath, byId }, { canonical });
23
+ const result = [...byPath.values()];
24
+ return { result, next: { ...state, entries: result, migrations: [...new Set([...state.migrations, ...migrations, ...(migration ? [migration] : [])])] } };
25
+ }
26
+ /** Remove rejected entries under the mutation lock and report them once; returns the surviving entries. */
27
+ function pruneDiscarded({ update, discard, reportDiscarded }) {
28
+ let entries = [];
29
+ let removed = [];
30
+ // Re-read under the same mutation lock; never overwrite a sibling process's new rows.
31
+ update((state) => {
32
+ removed = state.entries.filter((entry) => discard({ entry }));
33
+ const discarded = new Set(removed);
34
+ entries = state.entries.filter((entry) => !discarded.has(entry));
35
+ return { ...state, entries };
36
+ });
37
+ if (removed.length)
38
+ reportDiscarded({ entries: removed });
39
+ return entries;
40
+ }
1
41
  /** Shared catalog: corrupt state fails closed; every update holds one durable file lock.
2
42
  * Canonical paths deduplicate symlink aliases. Identity collisions require explicit relocation.
3
43
  * Optional host admission prunes rejected entries on list under that same lock, then reports once.
@@ -7,19 +47,7 @@ export function createDirectoryRegistry(
7
47
  // The catalog only reads, writes and locks; it never quarantines or stages temp files, so
8
48
  // transaction-local adapters need not stub those members.
9
49
  { file, canonicalPath }, { discard, reportDiscarded = () => { } } = {}) {
10
- function read() {
11
- const result = file.read({});
12
- if (result.state === "missing")
13
- return { version: 1, entries: [], migrations: [] };
14
- if (result.state !== "ok")
15
- throw new Error("The shared directory registry is unreadable; nothing was overwritten.");
16
- const state = result.value;
17
- const shapeOk = state?.version === 1 && Array.isArray(state.entries) && Array.isArray(state.migrations);
18
- if (!shapeOk || !state.migrations.every((item) => typeof item === "string") || !state.entries.every(validRecord)) {
19
- throw new Error("The shared directory registry has an invalid format; nothing was overwritten.");
20
- }
21
- return state;
22
- }
50
+ const read = () => readRegistryState({ file });
23
51
  const canonical = (value) => canonicalPath({ path: value });
24
52
  const update = (change) => file.withLock({ critical: () => {
25
53
  const previous = read(), next = change(previous);
@@ -33,32 +61,14 @@ export function createDirectoryRegistry(
33
61
  const current = read();
34
62
  if (!discard || !current.entries.some((entry) => discard({ entry })))
35
63
  return current.entries;
36
- let entries = current.entries;
37
- let removed = [];
38
- // Re-read under the same mutation lock; never overwrite a sibling process's new rows.
39
- update((state) => {
40
- removed = state.entries.filter((entry) => discard({ entry }));
41
- const discarded = new Set(removed);
42
- entries = state.entries.filter((entry) => !discarded.has(entry));
43
- return { ...state, entries };
44
- });
45
- if (removed.length)
46
- reportDiscarded({ entries: removed });
47
- return entries;
64
+ return pruneDiscarded({ update, discard, reportDiscarded });
48
65
  },
49
66
  merge({ entries, migration, migrations = [] }, _optional = {}) {
50
67
  let result = [];
51
68
  update((state) => {
52
- if (migration && state.migrations.includes(migration)) {
53
- result = state.entries;
54
- return state;
55
- }
56
- const byPath = new Map(state.entries.map((entry) => [canonical(entry.path), { ...entry, path: canonical(entry.path) }]));
57
- const byId = new Map([...byPath.values()].map((entry) => [entry.id, entry.path]));
58
- for (const entry of entries)
59
- mergeEntry({ entry, byPath, byId }, { canonical });
60
- result = [...byPath.values()];
61
- return { ...state, entries: result, migrations: [...new Set([...state.migrations, ...migrations, ...(migration ? [migration] : [])])] };
69
+ const merged = mergeRegistryState({ state, entries, migration, migrations, canonical });
70
+ result = merged.result;
71
+ return merged.next;
62
72
  });
63
73
  return result;
64
74
  },