@jini-ai/platform 0.7.1 → 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 (165) hide show
  1. package/CHANGELOG.md +2 -2
  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/vault.types.d.ts +0 -27
  164. package/dist/secrets/credential-sets/vault.types.js +0 -49
  165. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
package/CHANGELOG.md CHANGED
@@ -18,7 +18,7 @@
18
18
  `parseMailAdaptersFile({ raw }, optional)` call remains supported through a local
19
19
  validation boundary, preserving declared setup validation and v1/v2 descriptors.
20
20
  Provider-status and credential-save factories also require host wording and catalog
21
- provenance so a second host supplies its own navigation without changing Tovu bytes.
21
+ provenance so a second host supplies its own navigation without changing the first host's bytes.
22
22
 
23
23
  ### Patch Changes
24
24
 
@@ -180,7 +180,7 @@
180
180
 
181
181
  ### Patch Changes
182
182
 
183
- - Tovu clean-up release (2026-10-08): code Tovu moved into Jini, plus the Jini clean-up (see the commit log since 0.5.1).
183
+ - Host clean-up release (2026-10-08): code the first host moved into Jini, plus the Jini clean-up (see the commit log since 0.5.1).
184
184
 
185
185
  ## 0.5.1 — 2026-10-04
186
186
 
package/README.md CHANGED
@@ -61,9 +61,9 @@ need a `PtySpawn` implementation supplied by the caller — this package defines
61
61
  ```ts
62
62
  import { waitForHttpOk, pathContains, spawnBackgroundProcess, LocalBlobStorage } from '@jini-ai/platform';
63
63
 
64
- await waitForHttpOk('http://127.0.0.1:4317/api/daemon/status', { timeoutMs: 15000 });
64
+ await waitForHttpOk({ url: 'http://127.0.0.1:4317/api/daemon/status' }, { timeoutMs: 15000 });
65
65
 
66
- if (!pathContains('/workspace/project', requestedPath)) {
66
+ if (!pathContains({ root: '/workspace/project', target: requestedPath })) {
67
67
  throw new Error('path escapes project root');
68
68
  }
69
69
 
@@ -97,6 +97,13 @@ The package also exposes `./http/guarded`, `./mail`, `./mail/smtp`,
97
97
  `./fs/guarded-reader`, `./fs/durable-json`, and `./secrets`. New APIs take a required
98
98
  object followed by an optional object. Application identity and policy values belong to the caller.
99
99
 
100
+ `@jini-ai/platform/secrets/root-key` (Node) exports the pure provisioning table
101
+ `planSiteKeyEnsure`, the payload-preserving `decideLocalSiteKeyEnsure`, and the
102
+ `verdictOfCheck`, `verdictOf`, and `matchesFingerprint` helpers. Callers supply the runtime
103
+ mode and resolved material checks; source selection, reads and writes belong to the host.
104
+
105
+ `@jini-ai/platform/system` (universal) exports `createSystemClock()` (wall `Clock`) and `createRandomUuidGenerator()` (cryptographic `IdGenerator`); Jini packages take these ports as required arguments and hosts pass these adapters.
106
+
100
107
  Email event senders use the universal `@jini-ai/platform/mail/senders` entry (also exported by `/mail`).
101
108
  `EmailSender` exposes `listSources`, `describeSource`, `resolveEvent`, and `configureEmail`.
102
109
  Each operation authorizes its workspace and principal; the sender owns values, recipients and binding.
@@ -112,6 +119,10 @@ Its result can be frozen in the feature's existing job; missing optional values
112
119
  when using that subpath; the other entries do not load them. Existing web consumers that
113
120
  relied on transitive installation must add them before upgrading.
114
121
 
122
+ `@jini-ai/platform/mail/email-template` (pure email-template renders: `{{field}}` fill-ins, preview and send) loads only `parse5@7.3.0`.
123
+
124
+ `@jini-ai/platform/mail/email-template-operations` (create/edit/rename/list/get/preview/send-render over a host `EmailTemplateStore` port) loads `parse5@7.3.0` through `./mail/email-template`.
125
+
115
126
  ```sh
116
127
  npm install parse5@7.3.0 hast-util-from-parse5@8.0.3 hast-util-to-mdast@10.1.2 mdast-util-to-markdown@2.1.2 mdast-util-gfm-table@2.0.0
117
128
  ```
@@ -168,8 +179,8 @@ malformed/truncated input. Streamed bytes are counted before decoding, independe
168
179
  failed guarded consumption cancels and releases the reader without masking the original error.
169
180
  Incoming chunk allocation is controlled by the upstream stream. The text-fetch helper maps timeout
170
181
  errors during both headers and body consumption to `FetchTimeoutError`, returns `{ response, text }`,
171
- and leaves the response metadata available with its body consumed. The existing positional
172
- `fetchWithTimeout(url, init, { timeoutMs, fetch? })` now accepts transport injection and still returns
182
+ and leaves the response metadata available with its body consumed. The
183
+ `fetchWithTimeout({ url, timeoutMs, fetch? }, { init })` now accepts transport injection and still returns
173
184
  the original unconsumed response. Neither function retries.
174
185
 
175
186
  For retained-byte metadata and optional truncation, use the single-object overload:
@@ -221,6 +232,7 @@ vendor-shaped `NativeSmtpTransport` so the factory adapts the payload once. Poli
221
232
 
222
233
  | Subpath | API and required host ports/policy |
223
234
  | --- | --- |
235
+ | `./secrets/legacy-owner` | `readLegacyOwnerBackup({ envelope, passphrase })` decodes a legacy `jini-owner-store` v1/v2 passphrase backup read-only; `openLegacyOwnerVault({ repo, keyFilePath }, { metaParsers })` is the legacy keyring + authorize policy (owner workspace, no principal, copyable kind; never generates a key) over a host-supplied `VaultRepoPort`; `readLegacyOwnerEntry({ vault, row })` is one decrypt whose every failure is the fixed `OwnerStoreRecoveryError`. Entries are `VaultArchiveEntry`. The SQL reads are `@jini-ai/db/owner-store`; the file wiring is `@jini-ai/server/owner-store`. |
224
236
  | `./mail` | `createMailAdapterContext({ credential, kit }, { now, settings })` supplies a live clock and fresh empty settings by default; modules validate opaque per-install settings. |
225
237
  | `@jini-ai/analytics` (separate package) | `ingestHit({ input, deps }, { hooks, hash })`, `normalizeIngestContext({ input, dailySalt }, { hash })`, `deriveDailySalt({ rootKeySeed, workspaceId, utcDate, saltContext })`. The host supplies sink/config, host resolution, HKDF context, and privacy bounds. `LocalBufferSink({}, { initialHits })` is process-local. |
226
238
  | `@jini-ai/cms/trash` (separate package) | `createTrashService({ repo, adapters, transaction, idGen, entityPolicy }, { retentionDays, ...optional })`, `createTrashSweep({ repo, adapters, transaction, entityPolicy })`, and `startTrashSweeper({ sweep, clock, scheduler, leaseOwner }, optional)`. The host owns authorization, transactions, retention, scheduling, and adapters; follow-up hooks are in argument two. |
@@ -7,11 +7,19 @@ export declare const CACHEABLE_MEDIA_EXT: RegExp;
7
7
  /** True when `raw` is an absolute http(s) URL pointing at a media file we are
8
8
  * willing to route through the cache. Pure + side-effect free so the URL
9
9
  * rewriter and tests can share the exact predicate. */
10
- export declare function isCacheableExternalUrl(raw: unknown): raw is string;
10
+ export declare function isCacheableExternalUrl(required: {
11
+ raw: unknown;
12
+ }, _optional?: Record<string, never>): required is {
13
+ raw: string;
14
+ };
11
15
  /** Map a cacheable external URL to its same-origin proxy URL. `routePath`
12
16
  * defaults to `/api/asset-cache` but is caller-configurable since the route
13
17
  * is mounted by the host application, not this package. */
14
- export declare function assetCacheRewriteUrl(raw: string, routePath?: string): string;
18
+ export declare function assetCacheRewriteUrl({ raw }: {
19
+ raw: string;
20
+ }, { routePath }?: {
21
+ routePath?: string | undefined;
22
+ }): string;
15
23
  /** Error carrying the HTTP status the route should surface. */
16
24
  export declare class AssetCacheError extends Error {
17
25
  readonly status: number;
@@ -64,6 +72,8 @@ export declare function createAssetCache(opts: AssetCacheOptions, options?: {
64
72
  dispatcher?: Dispatcher;
65
73
  }): AssetCache;
66
74
  /** Exposed for tests that need to assert the on-disk key layout. */
67
- export declare function assetCacheKey(rawUrl: string): string;
75
+ export declare function assetCacheKey({ rawUrl }: {
76
+ rawUrl: string;
77
+ }, _optional?: Record<string, never>): string;
68
78
  export {};
69
79
  //# sourceMappingURL=asset-cache.d.ts.map
@@ -49,7 +49,8 @@ const CACHEABLE_MEDIA_MIME = new Set(Object.values(EXT_TO_MIME));
49
49
  /** True when `raw` is an absolute http(s) URL pointing at a media file we are
50
50
  * willing to route through the cache. Pure + side-effect free so the URL
51
51
  * rewriter and tests can share the exact predicate. */
52
- export function isCacheableExternalUrl(raw) {
52
+ export function isCacheableExternalUrl(required, _optional = {}) {
53
+ const { raw } = required;
53
54
  if (typeof raw !== 'string')
54
55
  return false;
55
56
  const value = raw.trim();
@@ -67,7 +68,7 @@ export function isCacheableExternalUrl(raw) {
67
68
  /** Map a cacheable external URL to its same-origin proxy URL. `routePath`
68
69
  * defaults to `/api/asset-cache` but is caller-configurable since the route
69
70
  * is mounted by the host application, not this package. */
70
- export function assetCacheRewriteUrl(raw, routePath = '/api/asset-cache') {
71
+ export function assetCacheRewriteUrl({ raw }, { routePath = '/api/asset-cache' } = {}) {
71
72
  return `${routePath}?url=${encodeURIComponent(raw.trim())}`;
72
73
  }
73
74
  /** Error carrying the HTTP status the route should surface. */
@@ -135,174 +136,182 @@ export function createValidatingLookup(lookupImpl = dnsLookupCb) {
135
136
  export function createAssetCacheDispatcher(_required, { lookupImpl } = {}) {
136
137
  return createUndiciAssetCacheDispatcher({ lookup: createValidatingLookup(lookupImpl) });
137
138
  }
138
- /** Build a disk-backed cache for external sandboxed-content media. Concurrent
139
- * requests for the same URL share one in-flight fetch; completed fetches
140
- * persist to `<cacheDir>/<sha256>` (+ `.json` sidecar) and are replayed from
141
- * disk. */
142
- export function createAssetCache(opts, options = {}) {
143
- const cacheDir = opts.cacheDir;
144
- const maxBytes = opts.maxBytes ?? 64 * 1024 * 1024;
145
- const timeoutMs = opts.fetchTimeoutMs ?? 15_000;
146
- const fetchImpl = opts.fetchImpl ?? fetch;
147
- // Pin SSRF validation to the actual outbound connection: the Agent resolves
148
- // the host once, and `validatingLookup` rejects the connection if that exact
149
- // address is private. No separate pre-validation lookup to rebind around.
150
- const suppliedDispatcher = options.dispatcher ?? opts.dispatcher;
151
- const dispatcher = suppliedDispatcher ?? createAssetCacheDispatcher({}, opts.lookupImpl ? { lookupImpl: opts.lookupImpl } : {});
152
- const inflight = new Map();
153
- async function readFromDisk({ key }, _options = {}) {
154
- const blobPath = path.join(cacheDir, key);
155
- const metaPath = `${blobPath}.json`;
156
- try {
157
- const [buf, metaRaw] = await Promise.all([readFile(blobPath), readFile(metaPath, 'utf8')]);
158
- const meta = JSON.parse(metaRaw);
159
- const contentType = meta.contentType;
160
- // Old cache entries must satisfy the same passive-media policy as new fetches.
161
- if (typeof contentType !== 'string' || !CACHEABLE_MEDIA_MIME.has(contentType))
162
- return null;
163
- return { buf, contentType };
164
- }
165
- catch {
139
+ async function readFromDisk({ s, key }) {
140
+ const { cacheDir } = s;
141
+ const blobPath = path.join(cacheDir, key);
142
+ const metaPath = `${blobPath}.json`;
143
+ try {
144
+ const [buf, metaRaw] = await Promise.all([readFile(blobPath), readFile(metaPath, 'utf8')]);
145
+ const meta = JSON.parse(metaRaw);
146
+ const contentType = meta.contentType;
147
+ // Old cache entries must satisfy the same passive-media policy as new fetches.
148
+ if (typeof contentType !== 'string' || !CACHEABLE_MEDIA_MIME.has(contentType))
166
149
  return null;
167
- }
150
+ return { buf, contentType };
168
151
  }
169
- async function writeToDisk(key, result) {
170
- await mkdir(cacheDir, { recursive: true });
171
- const blobPath = path.join(cacheDir, key);
172
- const tmpPath = `${blobPath}.${process.pid}.tmp`;
173
- await writeFile(tmpPath, result.buf);
174
- await rename(tmpPath, blobPath);
175
- await writeFile(`${blobPath}.json`, JSON.stringify({ contentType: result.contentType }));
152
+ catch {
153
+ return null;
176
154
  }
177
- function resolveContentType({ headerValue, url }, _options = {}) {
178
- // Moved from URL eligibility, which now uses URL.pathname instead of split:
179
- // `String#split` always returns a non-empty array (even `''.split(x)` is
180
- // `['']`), so index 0 is never `undefined` — the `!` narrows a
181
- // `noUncheckedIndexedAccess` false positive, not a real fallback path.
182
- // `(headerValue ?? '')` is reachable (no content-type header at all). The
183
- // trailing `?? ''` after the optional-chained `.split(';')[0]?.trim()` is
184
- // not: `String#split` always returns a non-empty array, so `[0]` is never
185
- // `undefined` and `?.` never short-circuits — kept for
186
- // `noUncheckedIndexedAccess`, not a real fallback path.
187
- const header = (headerValue ?? '').split(';')[0].trim().toLowerCase();
188
- if (CACHEABLE_MEDIA_MIME.has(header))
189
- return header;
190
- // An explicit active/unsupported type must never be relabelled by its URL.
191
- if (header && header !== 'application/octet-stream') {
192
- throw new AssetCacheError(415, `unsupported content-type: ${header}`);
193
- }
194
- const ext = path.posix.extname(url.pathname).toLowerCase();
195
- const guessed = EXT_TO_MIME[ext];
196
- if (guessed)
197
- return guessed;
198
- throw new AssetCacheError(415, `unsupported content-type: ${header || 'unknown'}`);
155
+ }
156
+ async function writeToDisk({ s, key, result }) {
157
+ const { cacheDir } = s;
158
+ await mkdir(cacheDir, { recursive: true });
159
+ const blobPath = path.join(cacheDir, key);
160
+ const tmpPath = `${blobPath}.${process.pid}.tmp`;
161
+ await writeFile(tmpPath, result.buf);
162
+ await rename(tmpPath, blobPath);
163
+ await writeFile(`${blobPath}.json`, JSON.stringify({ contentType: result.contentType }));
164
+ }
165
+ function resolveContentType({ headerValue, url }, _options = {}) {
166
+ // Moved from URL eligibility, which now uses URL.pathname instead of split:
167
+ // `String#split` always returns a non-empty array (even `''.split(x)` is
168
+ // `['']`), so index 0 is never `undefined` — the `!` narrows a
169
+ // `noUncheckedIndexedAccess` false positive, not a real fallback path.
170
+ // `(headerValue ?? '')` is reachable (no content-type header at all). The
171
+ // trailing `?? ''` after the optional-chained `.split(';')[0]?.trim()` is
172
+ // not: `String#split` always returns a non-empty array, so `[0]` is never
173
+ // `undefined` and `?.` never short-circuits — kept for
174
+ // `noUncheckedIndexedAccess`, not a real fallback path.
175
+ const header = (headerValue ?? '').split(';')[0].trim().toLowerCase();
176
+ if (CACHEABLE_MEDIA_MIME.has(header))
177
+ return header;
178
+ // An explicit active/unsupported type must never be relabelled by its URL.
179
+ if (header && header !== 'application/octet-stream') {
180
+ throw new AssetCacheError(415, `unsupported content-type: ${header}`);
199
181
  }
200
- function assertWithinLimit(total) {
201
- if (total > maxBytes)
202
- throw new AssetCacheError(413, 'asset exceeds size limit');
182
+ const ext = path.posix.extname(url.pathname).toLowerCase();
183
+ const guessed = EXT_TO_MIME[ext];
184
+ if (guessed)
185
+ return guessed;
186
+ throw new AssetCacheError(415, `unsupported content-type: ${header || 'unknown'}`);
187
+ }
188
+ function assertWithinLimit({ s, total }) {
189
+ const { maxBytes } = s;
190
+ if (total > maxBytes)
191
+ throw new AssetCacheError(413, 'asset exceeds size limit');
192
+ }
193
+ /** Pull chunks until done, failing as soon as the running total passes
194
+ * `maxBytes`. Always releases the reader, even on the size-limit throw. */
195
+ async function drainCapped({ s, reader, controller }) {
196
+ const { maxBytes } = s;
197
+ const chunks = [];
198
+ let total = 0;
199
+ try {
200
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
201
+ const value = next.value;
202
+ if (!value)
203
+ continue;
204
+ total += value.byteLength;
205
+ if (total > maxBytes) {
206
+ controller.abort(); // stop pulling more bytes from upstream
207
+ throw new AssetCacheError(413, 'asset exceeds size limit');
208
+ }
209
+ chunks.push(value);
210
+ }
203
211
  }
204
- /** Pull chunks until done, failing as soon as the running total passes
205
- * `maxBytes`. Always releases the reader, even on the size-limit throw. */
206
- async function drainCapped(reader, controller) {
207
- const chunks = [];
208
- let total = 0;
212
+ finally {
209
213
  try {
210
- for (let next = await reader.read(); !next.done; next = await reader.read()) {
211
- const value = next.value;
212
- if (!value)
213
- continue;
214
- total += value.byteLength;
215
- if (total > maxBytes) {
216
- controller.abort(); // stop pulling more bytes from upstream
217
- throw new AssetCacheError(413, 'asset exceeds size limit');
218
- }
219
- chunks.push(value);
220
- }
214
+ await reader.cancel();
221
215
  }
222
- finally {
223
- try {
224
- await reader.cancel();
225
- }
226
- catch {
227
- // reader already closed / errored — nothing to release
228
- }
216
+ catch {
217
+ // reader already closed / errored — nothing to release
229
218
  }
230
- return Buffer.concat(chunks);
231
- }
232
- /** Drain the body, aborting the moment the accumulated size exceeds
233
- * `maxBytes`. A response without a trustworthy Content-Length must never be
234
- * fully buffered first — that would turn this caller-supplied proxy into a
235
- * memory-exhaustion path. */
236
- async function readBodyCapped(response, controller) {
237
- const body = response.body;
238
- if (body)
239
- return drainCapped(body.getReader(), controller);
240
- const ab = await response.arrayBuffer();
241
- assertWithinLimit(ab.byteLength);
242
- return Buffer.from(ab);
243
219
  }
244
- async function fetchAndStore(rawUrl, key) {
245
- const url = assertSafePublicUrl(rawUrl);
246
- const controller = new AbortController();
247
- const timer = setTimeout(() => controller.abort(), timeoutMs);
220
+ return Buffer.concat(chunks);
221
+ }
222
+ /** Drain the body, aborting the moment the accumulated size exceeds
223
+ * `maxBytes`. A response without a trustworthy Content-Length must never be
224
+ * fully buffered first — that would turn this caller-supplied proxy into a
225
+ * memory-exhaustion path. */
226
+ async function readBodyCapped({ s, response, controller }) {
227
+ const body = response.body;
228
+ if (body)
229
+ return drainCapped({ s, reader: body.getReader(), controller });
230
+ const ab = await response.arrayBuffer();
231
+ assertWithinLimit({ s, total: ab.byteLength });
232
+ return Buffer.from(ab);
233
+ }
234
+ async function fetchAndStore({ s, rawUrl, key }) {
235
+ const { timeoutMs, fetchImpl, dispatcher } = s;
236
+ const url = assertSafePublicUrl(rawUrl);
237
+ const controller = new AbortController();
238
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
239
+ try {
240
+ let response;
248
241
  try {
249
- let response;
250
- try {
251
- // `dispatcher` carries the connection-time SSRF guard. It is an undici
252
- // extension of RequestInit; attach it at runtime to avoid the
253
- // undici-types (bundled with @types/node) vs undici@7 Dispatcher version
254
- // skew that a typed field would trip over.
255
- const init = { redirect: 'error', signal: controller.signal };
256
- init.dispatcher = dispatcher;
257
- response = await fetchImpl(url, init);
258
- }
259
- catch (err) {
260
- throw new AssetCacheError(502, `fetch failed: ${err instanceof Error ? err.message : String(err)}`);
261
- }
262
- if (!response.ok) {
263
- throw new AssetCacheError(502, `upstream responded ${response.status}`);
264
- }
265
- const declaredLength = Number(response.headers.get('content-length') ?? '');
266
- if (Number.isFinite(declaredLength))
267
- assertWithinLimit(declaredLength);
268
- const contentType = resolveContentType({ headerValue: response.headers.get('content-type'), url });
269
- const buf = await readBodyCapped(response, controller);
270
- const result = { buf, contentType };
271
- try {
272
- await writeToDisk(key, result);
273
- }
274
- catch {
275
- // A cache-write failure must not fail the request; serve from memory.
276
- }
277
- return result;
242
+ // `dispatcher` carries the connection-time SSRF guard. It is an undici
243
+ // extension of RequestInit; attach it at runtime to avoid the
244
+ // undici-types (bundled with @types/node) vs undici@7 Dispatcher version
245
+ // skew that a typed field would trip over.
246
+ const init = { redirect: 'error', signal: controller.signal };
247
+ init.dispatcher = dispatcher;
248
+ response = await fetchImpl(url, init);
278
249
  }
279
- finally {
280
- clearTimeout(timer);
250
+ catch (err) {
251
+ throw new AssetCacheError(502, `fetch failed: ${err instanceof Error ? err.message : String(err)}`);
281
252
  }
282
- }
283
- async function get(rawUrl) {
284
- if (!isCacheableExternalUrl(rawUrl)) {
285
- throw new AssetCacheError(400, 'url is not a cacheable external media url');
253
+ if (!response.ok) {
254
+ throw new AssetCacheError(502, `upstream responded ${response.status}`);
286
255
  }
287
- const url = rawUrl.trim();
288
- const key = assetCacheKey(url);
289
- const cached = await readFromDisk({ key });
290
- if (cached)
291
- return cached;
292
- const existing = inflight.get(key);
293
- if (existing)
294
- return existing;
295
- const pending = fetchAndStore(url, key).finally(() => {
296
- inflight.delete(key);
297
- });
298
- inflight.set(key, pending);
299
- return pending;
256
+ const declaredLength = Number(response.headers.get('content-length') ?? '');
257
+ if (Number.isFinite(declaredLength))
258
+ assertWithinLimit({ s, total: declaredLength });
259
+ const contentType = resolveContentType({ headerValue: response.headers.get('content-type'), url });
260
+ const buf = await readBodyCapped({ s, response, controller });
261
+ const result = { buf, contentType };
262
+ try {
263
+ await writeToDisk({ s, key, result });
264
+ }
265
+ catch {
266
+ // A cache-write failure must not fail the request; serve from memory.
267
+ }
268
+ return result;
300
269
  }
301
- return { get, close: async () => { if (!suppliedDispatcher)
302
- await dispatcher.close(); } };
270
+ finally {
271
+ clearTimeout(timer);
272
+ }
273
+ }
274
+ async function get({ s, rawUrl }) {
275
+ const { inflight } = s;
276
+ if (!isCacheableExternalUrl({ raw: rawUrl })) {
277
+ throw new AssetCacheError(400, 'url is not a cacheable external media url');
278
+ }
279
+ const url = rawUrl.trim();
280
+ const key = assetCacheKey({ rawUrl: url });
281
+ const cached = await readFromDisk({ s, key });
282
+ if (cached)
283
+ return cached;
284
+ const existing = inflight.get(key);
285
+ if (existing)
286
+ return existing;
287
+ const pending = fetchAndStore({ s, rawUrl: url, key }).finally(() => {
288
+ inflight.delete(key);
289
+ });
290
+ inflight.set(key, pending);
291
+ return pending;
292
+ }
293
+ /** Build a disk-backed cache for external sandboxed-content media. Concurrent
294
+ * requests for the same URL share one in-flight fetch; completed fetches
295
+ * persist to `<cacheDir>/<sha256>` (+ `.json` sidecar) and are replayed from
296
+ * disk. */
297
+ export function createAssetCache(opts, options = {}) {
298
+ // Pin SSRF validation to the actual outbound connection: the Agent resolves
299
+ // the host once, and `validatingLookup` rejects the connection if that exact
300
+ // address is private. No separate pre-validation lookup to rebind around.
301
+ const suppliedDispatcher = options.dispatcher ?? opts.dispatcher;
302
+ const s = {
303
+ cacheDir: opts.cacheDir,
304
+ maxBytes: opts.maxBytes ?? 64 * 1024 * 1024,
305
+ timeoutMs: opts.fetchTimeoutMs ?? 15_000,
306
+ fetchImpl: opts.fetchImpl ?? fetch,
307
+ dispatcher: suppliedDispatcher ?? createAssetCacheDispatcher({}, opts.lookupImpl ? { lookupImpl: opts.lookupImpl } : {}),
308
+ inflight: new Map(),
309
+ };
310
+ return { get: (rawUrl) => get({ s, rawUrl }), close: async () => { if (!suppliedDispatcher)
311
+ await s.dispatcher.close(); } };
303
312
  }
304
313
  /** Exposed for tests that need to assert the on-disk key layout. */
305
- export function assetCacheKey(rawUrl) {
314
+ export function assetCacheKey({ rawUrl }, _optional = {}) {
306
315
  return createHash('sha256').update(rawUrl.trim()).digest('hex');
307
316
  }
308
317
  //# sourceMappingURL=asset-cache.js.map
@@ -1,39 +1,10 @@
1
+ import { type BlobFileMeta, type BlobStorage } from "@jini-ai/core/contracts/blob";
1
2
  import { type SigV4Credentials } from './aws-sigv4.js';
2
- /** Metadata for a single stored blob. */
3
- export interface BlobFileMeta {
4
- /** Path relative to the namespace root. Always uses forward slashes. */
5
- path: string;
6
- /** Total size in bytes. */
7
- size: number;
8
- /** Unix epoch milliseconds of last modification. */
9
- mtimeMs: number;
10
- }
11
- /** The narrow contract every blob storage backend implements. */
12
- export interface BlobStorage {
13
- /** Reads `<namespace>/<relpath>` into a Buffer. Throws a `StorageError('NOT_FOUND', ...)` when missing. */
14
- readFile(namespace: string, relpath: string): Promise<Buffer>;
15
- /** Writes `<namespace>/<relpath>`, creating parent directories/prefixes as needed. */
16
- writeFile(namespace: string, relpath: string, body: Buffer): Promise<BlobFileMeta>;
17
- /**
18
- * Lists every file under `<namespace>/` recursively. The order is implementation-defined;
19
- * callers that need deterministic order sort by `path`.
20
- */
21
- listFiles(namespace: string): Promise<BlobFileMeta[]>;
22
- /** Deletes a single file under `<namespace>/`. Idempotent — missing files do not throw. */
23
- deleteFile(namespace: string, relpath: string): Promise<void>;
24
- /** Reports metadata for a single file without reading its bytes. Returns `null` when missing. */
25
- statFile(namespace: string, relpath: string): Promise<BlobFileMeta | null>;
26
- }
27
- /** Error thrown by {@link BlobStorage} implementations, distinguishing not-found/traversal/IO failures. */
28
- export declare class StorageError extends Error {
29
- readonly code: 'NOT_FOUND' | 'TRAVERSAL' | 'IO';
30
- constructor(code: 'NOT_FOUND' | 'TRAVERSAL' | 'IO', message: string);
31
- }
32
3
  /**
33
4
  * The local-disk default backend — a thin `fs/promises` wrapper rooted at a caller-supplied
34
5
  * directory, with a traversal guard so a hostile `namespace`/`relpath` can never escape it.
35
6
  */
36
- export declare class LocalBlobStorage implements BlobStorage {
7
+ export declare class LocalBlobStorage implements BlobStorage<Buffer> {
37
8
  private readonly root;
38
9
  constructor(root: string);
39
10
  readFile(namespace: string, relpath: string): Promise<Buffer>;
@@ -72,7 +43,7 @@ export interface S3BlobStorageOptions {
72
43
  /** Override for clock — tests pin signatures with this. Production leaves it undefined (`signSigV4` falls back to `new Date()`). */
73
44
  now?: () => Date;
74
45
  }
75
- export declare class S3BlobStorage implements BlobStorage {
46
+ export declare class S3BlobStorage implements BlobStorage<Buffer> {
76
47
  readonly options: S3BlobStorageOptions;
77
48
  private readonly fetchFn;
78
49
  constructor(options: S3BlobStorageOptions);
@@ -20,16 +20,8 @@
20
20
  import path from 'node:path';
21
21
  import { promises as fsp } from 'node:fs';
22
22
  import { trimChars, trimCharsEnd, trimCharsStart } from '@jini-ai/core/primitives';
23
+ import { StorageError } from "@jini-ai/core/contracts/blob";
23
24
  import { encodeS3PathSegment, signSigV4 } from './aws-sigv4.js';
24
- /** Error thrown by {@link BlobStorage} implementations, distinguishing not-found/traversal/IO failures. */
25
- export class StorageError extends Error {
26
- code;
27
- constructor(code, message) {
28
- super(message);
29
- this.code = code;
30
- this.name = 'StorageError';
31
- }
32
- }
33
25
  /**
34
26
  * The local-disk default backend — a thin `fs/promises` wrapper rooted at a caller-supplied
35
27
  * directory, with a traversal guard so a hostile `namespace`/`relpath` can never escape it.
@@ -1,20 +1,4 @@
1
1
  /** Environment isolation for child processes; hosts name the settings that belong to one run. */
2
- /**
3
- * Copy an environment without host-selected keys. Reports names only, never values; no I/O.
4
- * Windows callers opt into case-insensitive matching so duplicate spellings cannot survive.
5
- * @returns A fresh environment and the configured names whose defined values were omitted.
6
- * @complexity O(e + k) time/space for e environment entries and k configured names.
7
- * @example omitEnvironmentKeys({ env: parent, keys: ['WORKSPACE_STORAGE'] });
8
- */
9
- export declare function omitEnvironmentKeys({ env, keys }: {
10
- env: Readonly<Record<string, string | undefined>>;
11
- keys: readonly string[];
12
- }, { caseInsensitive }?: {
13
- caseInsensitive?: boolean;
14
- }): {
15
- env: Record<string, string | undefined>;
16
- omitted: string[];
17
- };
18
2
  /** Runs one bounded command and resolves its stdout; `execFile` semantics. */
19
3
  export type LoginShellCommandRunner = (required: {
20
4
  file: string;
@@ -1,31 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { userInfo } from 'node:os';
3
3
  import { promisify } from 'node:util';
4
- /** Environment isolation for child processes; hosts name the settings that belong to one run. */
5
- /**
6
- * Copy an environment without host-selected keys. Reports names only, never values; no I/O.
7
- * Windows callers opt into case-insensitive matching so duplicate spellings cannot survive.
8
- * @returns A fresh environment and the configured names whose defined values were omitted.
9
- * @complexity O(e + k) time/space for e environment entries and k configured names.
10
- * @example omitEnvironmentKeys({ env: parent, keys: ['WORKSPACE_STORAGE'] });
11
- */
12
- export function omitEnvironmentKeys({ env, keys }, { caseInsensitive = false } = {}) {
13
- const normalize = (key) => caseInsensitive ? key.toUpperCase() : key;
14
- const names = new Map(keys.map((key) => [normalize(key), key]));
15
- const child = {};
16
- const omitted = new Set();
17
- for (const [key, value] of Object.entries(env)) {
18
- const name = names.get(normalize(key));
19
- if (name !== undefined) {
20
- if (value !== undefined)
21
- omitted.add(name);
22
- }
23
- else {
24
- child[key] = value;
25
- }
26
- }
27
- return { env: child, omitted: [...omitted] };
28
- }
29
4
  const LOGIN_SHELL_BOOTSTRAP_KEYS = ['PATH', 'HOME', 'USERPROFILE', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'TEMP', 'TMP',
30
5
  'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'SSH_AUTH_SOCK', 'SystemRoot', 'windir', 'ComSpec', 'PATHEXT'];
31
6
  // Registry-backed machine/user environment, without inheriting the service's private values.
package/dist/command.d.ts CHANGED
@@ -1,13 +1,4 @@
1
- export type CommandInvocation = {
2
- args: string[];
3
- command: string;
4
- windowsVerbatimArguments?: boolean;
5
- };
6
- export type CommandInvocationRequest = {
7
- args?: string[];
8
- command: string;
9
- env?: NodeJS.ProcessEnv;
10
- };
1
+ import { type CommandInvocation, type CommandInvocationRequest } from "@jini-ai/core/contracts/runtime";
11
2
  /**
12
3
  * Resolve a command request into the concrete invocation to spawn. On Windows,
13
4
  * `.bat` / `.cmd` targets are rewrapped as a `cmd.exe /d /s /c "..."` shim with
@@ -28,5 +19,9 @@ export declare function createCommandInvocation({ args, command, env }: CommandI
28
19
  * @param env - Environment to read `npm_execpath` / `ComSpec` from (defaults to `process.env`).
29
20
  * @returns The `{ command, args }` invocation that runs the package manager.
30
21
  */
31
- export declare function createPackageManagerInvocation(args: string[], env?: NodeJS.ProcessEnv): CommandInvocation;
22
+ export declare function createPackageManagerInvocation({ args }: {
23
+ args: string[];
24
+ }, { env }?: {
25
+ env?: NodeJS.ProcessEnv | undefined;
26
+ }): CommandInvocation;
32
27
  //# sourceMappingURL=command.d.ts.map