@oceanprotocol/lib 9.3.0-next.5 → 10.0.0-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.
@@ -34,6 +34,7 @@ export interface ComputeResource {
34
34
  [key: string]: any;
35
35
  };
36
36
  inUse?: number;
37
+ memoryTotal?: string;
37
38
  }
38
39
  export interface ComputeEnvironmentAccessOptions {
39
40
  addresses?: string[];
@@ -81,6 +81,7 @@ export interface NodeStatus {
81
81
  uptime: number;
82
82
  persistentStorage?: {
83
83
  accessLists?: AccessList[];
84
+ allowBucketSharing?: boolean;
84
85
  };
85
86
  }
86
87
  /**
@@ -244,6 +245,7 @@ export declare const PROTOCOL_COMMANDS: {
244
245
  SERVICE_EXTEND: string;
245
246
  SERVICE_GET_STREAMABLE_LOGS: string;
246
247
  GET_ESCROW_EVENTS: string;
248
+ SERVICE_GET_RESULT: string;
247
249
  };
248
250
  export interface NodeLogsParams {
249
251
  logId?: string;
@@ -1,12 +1,48 @@
1
1
  import { ComputeJobMetadata, ComputeResourceRequest, ContainerMetricsSnapshot } from './Compute.js';
2
- export interface TemplateResourceRequirement {
3
- id?: string;
4
- kind?: 'discrete' | 'fungible';
5
- type?: string;
6
- min: number;
7
- recommended?: number;
8
- unit?: string;
2
+ /** One way to book the recommended VRAM: `gpuCount` identical GPUs of one group, one host. */
3
+ export interface GpuLayout {
4
+ gpuCount: number;
5
+ vramPerGpu?: number;
6
+ }
7
+ export type TemplateResourceRequirement = {
8
+ id: 'cpu';
9
+ recommended: number;
10
+ unit: 'cores';
11
+ description?: string;
12
+ } | {
13
+ id: 'ram' | 'disk';
14
+ recommended: number;
15
+ unit: 'GB';
16
+ description?: string;
17
+ } | {
18
+ kind: 'discrete';
19
+ type: 'gpu';
20
+ recommended: number;
21
+ unit: 'GB';
22
+ gpuCountEnv?: string;
23
+ layouts: GpuLayout[];
9
24
  description?: string;
25
+ };
26
+ /**
27
+ * Authoring-time GPU sizing rule (`<flow>/sizing.json` in the templates repo), never sent to
28
+ * the node. deriveGpuLayouts() turns it into a template's `recommended` + `layouts`; the
29
+ * formula is at gpuFloorGb(). The templates repo shares the formula's test vectors
30
+ * (test/unit/fixtures/gpu-sizing-vectors.json).
31
+ */
32
+ export interface GpuSizingProfile {
33
+ version: 1;
34
+ engine: string;
35
+ widths: number[];
36
+ shardableGiB: number;
37
+ replicatedGiB: number;
38
+ memUtil: number | Record<string, number>;
39
+ outsideGiB?: number;
40
+ driverReserveGiB?: number;
41
+ overrides?: Record<string, {
42
+ vramPerGpu: number;
43
+ source: 'measured' | 'policy' | 'estimate';
44
+ note: string;
45
+ }>;
10
46
  }
11
47
  export interface UserConfigurableEnvVar {
12
48
  key: string;
@@ -33,7 +69,6 @@ export interface ServiceTemplatePublic {
33
69
  userConfigurableEnvVars?: UserConfigurableEnvVar[];
34
70
  command?: string[];
35
71
  entrypoint?: string[];
36
- requiredResources?: TemplateResourceRequirement[];
37
72
  recommendedResources?: TemplateResourceRequirement[];
38
73
  workflows?: ServiceTemplateWorkflow[];
39
74
  }
@@ -66,6 +101,13 @@ export interface ServiceJobPayment {
66
101
  cost?: string | number;
67
102
  [key: string]: any;
68
103
  }
104
+ export interface ServiceOutputArchive {
105
+ index: number;
106
+ filename: string;
107
+ filesize: number;
108
+ createdAt: number;
109
+ containerId: string;
110
+ }
69
111
  export interface ServiceJob {
70
112
  serviceId: string;
71
113
  clusterHash: string;
@@ -94,8 +136,10 @@ export interface ServiceJob {
94
136
  extendPayments?: ServiceJobPayment[];
95
137
  runtimeMetrics?: ContainerMetricsSnapshot;
96
138
  metadata?: ComputeJobMetadata;
139
+ outputBucketId?: string;
140
+ outputArchives?: ServiceOutputArchive[];
97
141
  }
98
- export type ServiceJobListed = Omit<ServiceJob, 'dockerCmd' | 'dockerEntrypoint' | 'dockerfile' | 'additionalDockerFiles' | 'runtimeMetrics'>;
142
+ export type ServiceJobListed = Omit<ServiceJob, 'dockerCmd' | 'dockerEntrypoint' | 'dockerfile' | 'additionalDockerFiles' | 'runtimeMetrics' | 'outputArchives'>;
99
143
  export interface ServiceListFilters {
100
144
  status?: ServiceStatusNumber;
101
145
  includeAllStatuses?: boolean;
@@ -20,7 +20,7 @@ export declare class Datatoken extends SmartContract {
20
20
  * Approves a spender to spend a certain amount of datatokens.
21
21
  * @param {String} dtAddress Datatoken address
22
22
  * @param {String} spender Spender address
23
- * @param {string} amount Number of datatokens, as number. Will be converted to wei
23
+ * @param {string} amount Number of datatokens, as number. Will be converted to units using the token's on-chain decimals
24
24
  * @param {Boolean} estimateGas if True, return gas estimate
25
25
  * @return {Promise<ReceiptOrEstimate>}
26
26
  */
@@ -124,7 +124,7 @@ export declare class Datatoken extends SmartContract {
124
124
  * Transfer tokens(as number) from address to toAddress
125
125
  * @param {String} dtAddress Datatoken address
126
126
  * @param {String} toAddress Receiver address
127
- * @param {String} amount Number of datatokens, as number. Will be converted to wei.
127
+ * @param {String} amount Number of datatokens, as number. Will be converted to units using the token's on-chain decimals.
128
128
  * @param {Boolean} estimateGas if True, return gas estimate
129
129
  * @return {Promise<ReceiptOrEstimate>} transactionId
130
130
  */
@@ -270,7 +270,7 @@ export declare class Datatoken extends SmartContract {
270
270
  * Get Address Balance for datatoken
271
271
  * @param {String} dtAddress Datatoken adress
272
272
  * @param {String} address user adress
273
- * @return {Promise<String>} balance Number of datatokens. Will be converted from wei
273
+ * @return {Promise<String>} balance Number of datatokens. Will be converted from units using the token's on-chain decimals
274
274
  */
275
275
  balance(datatokenAddress: string, address: string): Promise<string>;
276
276
  /**
@@ -278,8 +278,8 @@ export declare class Datatoken extends SmartContract {
278
278
  * @param {String} dtAddress Datatoken adress
279
279
  * @param {String} owner owner adress
280
280
  * @param {String} spender spender adress
281
- * @param {Number} decimals numer of token decimals, default 18
282
- * @return {Promise<String>} allowance Number of datatokens. Will be converted from wei
281
+ * @param {Number} [decimals] number of token decimals; when omitted they are read on-chain from the token
282
+ * @return {Promise<String>} allowance Number of datatokens. Will be converted from units
283
283
  */
284
284
  allowance(datatokenAddress: string, owner: string, spender: string, decimals?: number): Promise<string>;
285
285
  /**
@@ -2,6 +2,12 @@ import { Signer, TransactionRequest } from 'ethers';
2
2
  import { AbiItem, ReceiptOrEstimate, ValidationResponse, DepositData, PermitData, AuthData, LockData, EscrowKind, Sponsorship } from '../@types/index.js';
3
3
  import { Config } from '../config/index.js';
4
4
  import { SmartContractWithAddress } from './SmartContractWithAddress.js';
5
+ interface ReauthParams {
6
+ ceiling: string;
7
+ newSeconds: string;
8
+ newCounts: string;
9
+ newExpiry?: string;
10
+ }
5
11
  export declare class EscrowContract extends SmartContractWithAddress {
6
12
  abiEnterprise: AbiItem[];
7
13
  getDefaultAbi(): AbiItem[];
@@ -51,24 +57,58 @@ export declare class EscrowContract extends SmartContractWithAddress {
51
57
  */
52
58
  getAuthorizations(token: string, payer: string, payee: string): Promise<any[]>;
53
59
  /**
54
- * Checks funds for escrow payment.
55
- * Does authorization when needed.
56
- * Does deposit when needed.
60
+ * Checks (and tops up) escrow funds and authorization for a compute payment.
61
+ *
62
+ * Rejects (isValid=false) when this escrow address differs from config.escrow (fail-closed).
63
+ * All amounts are HUMAN-READABLE token units (not wei), converted once with the token's real
64
+ * decimals. The funding target is the larger of amountToDeposit and maxLockedAmount; only the
65
+ * shortfall versus current escrow funds is deposited, and the payment-token balance is read only
66
+ * to check that the shortfall is affordable. The payee is (re-)authorized up to the funding
67
+ * target.
57
68
  * @param {String} token as payment token for escrow
58
69
  * @param {String} consumerAddress as consumerAddress for that environment
59
- * @param {String} amountToDeposit wanted amount for escrow lock deposit. If this is
60
- * not provided and funds for escrow are 0 -> fallback to maxLockedAmount, else
61
- * use balance of payment token.
70
+ * @param {String} amountToDeposit wanted deposit (human units). When omitted, the funding target
71
+ * defaults to maxLockedAmount; only the shortfall from current escrow funds is deposited.
62
72
  * @param {String} maxLockedAmount amount necessary to be paid for starting compute job,
63
- * returned from initialize compute payment and used for authorize if needed.
73
+ * returned from initialize compute payment; used for the funding target and authorize if needed.
64
74
  * @param {String} maxLockSeconds max seconds to lock the payment,
65
75
  * returned from initialize compute payment and used for authorize if needed.
66
76
  * @param {String} maxLockCounts max lock counts,
67
77
  * returned from initialize compute payment and used for authorize if needed.
68
78
  * @param {number} [tokenDecimals] optional number of decimals of the token
79
+ * @param {String} [expiryTimestamp] optional unix timestamp (seconds) at which a newly
80
+ * created/updated authorization expires (Escrow v2); '0' = no expiry. When omitted and a prior
81
+ * authorization has a nonzero expiry that still covers now + maxLockSeconds (+120s buffer), it is
82
+ * preserved. If that prior expiry is too early (or in the past), or an explicit nonzero value is
83
+ * too early, no transaction is sent and { isValid: false } is returned: pass a later
84
+ * expiryTimestamp (or '0') to renew. It only applies when a (re-)authorization is actually made;
85
+ * if an existing authorization already satisfies the pending lock, no authorize tx is sent and an
86
+ * explicit expiryTimestamp has no effect (the existing record is left untouched).
87
+ * An existing authorization is reused only if it can satisfy createLock: its expiry covers
88
+ * now + maxLockSeconds (or is 0), its remaining ceiling (maxLocked - currentLocked) covers
89
+ * maxLockedAmount, its maxLockSeconds cap covers the requested duration, and it has a free
90
+ * lock slot. Otherwise it is re-authorized with a ceiling of max(currentLocked + maxLockedAmount,
91
+ * existing ceiling) and caps never lower than the existing record's (counts also leave a free slot).
69
92
  * @return {Promise<ValidationResponse>} validation response
70
93
  */
71
- verifyFundsForEscrowPayment(token: string, consumerAddress: string, amountToDeposit?: string, maxLockedAmount?: string, maxLockSeconds?: string, maxLockCounts?: string, tokenDecimals?: number): Promise<ValidationResponse>;
94
+ verifyFundsForEscrowPayment(token: string, consumerAddress: string, amountToDeposit?: string, maxLockedAmount?: string, maxLockSeconds?: string, maxLockCounts?: string, tokenDecimals?: number, expiryTimestamp?: string): Promise<ValidationResponse>;
95
+ /**
96
+ * Pure helper: merges a required authorization with the prior record (authorize() overwrites in
97
+ * place, keeping currentLocked/currentLocks). Never shrinks the prior ceiling/caps, leaves room
98
+ * for the already-locked funds and one more lock slot, and refuses (fail fast) to silently
99
+ * renew or set an expiry that cannot cover the lock horizon.
100
+ * @param {any} prior prior authorization tuple/struct for this payee (or undefined)
101
+ * @param {String} requiredAmountHuman required amount, human units
102
+ * @param {String} priorCurrentHuman prior currentLockedAmount, human units
103
+ * @param {String} priorMaxHuman prior maxLockedAmount, human units
104
+ * @param {String} maxLockSeconds required lock duration
105
+ * @param {String} maxLockCounts required lock count
106
+ * @param {number} requiredExpiry now + maxLockSeconds + buffer (unix seconds)
107
+ * @param {String} callerExpiry expiryTimestamp explicitly passed by the caller, if any
108
+ */
109
+ protected computeReauthParams(prior: any, requiredAmountHuman: string, priorCurrentHuman: string, priorMaxHuman: string, maxLockSeconds: string, maxLockCounts: string, requiredExpiry: number, callerExpiry?: string): ReauthParams | {
110
+ message: string;
111
+ };
72
112
  /**
73
113
  * Deposit funds
74
114
  * @param {String} token Token address
@@ -288,3 +328,4 @@ export declare class EscrowContract extends SmartContractWithAddress {
288
328
  */
289
329
  previewFee(token: string, amount: string, tokenDecimals?: number): Promise<string>;
290
330
  }
331
+ export {};
@@ -251,6 +251,26 @@ export declare class BaseProvider {
251
251
  getServiceStatus(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId?: string, signal?: AbortSignal, includeMetrics?: boolean): Promise<ServiceJob[]>;
252
252
  getServices(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, filters?: ServiceListFilters, signal?: AbortSignal): Promise<ServiceJobListed[]>;
253
253
  serviceGetStreamableLogs(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, since?: string, signal?: AbortSignal): Promise<any>;
254
+ /**
255
+ * Downloads a service's /data/outputs as a zip, dispatching to the HTTP or P2P transport based
256
+ * on `nodeUri`. Only for a service started without an output bucket (its results are in the
257
+ * bucket otherwise); owner-only.
258
+ *
259
+ * - `index`: one of the zips the node took whenever a container of the service was removed
260
+ * (stop, expiry, restart, recovery), listed as `outputArchives` by getServiceStatus. Works in
261
+ * any status until the node's storage expiry deletes it; resumable with `offset`.
262
+ * - `'live'`: a zip of the running container's /data/outputs, built as it is read — while the
263
+ * service is Running (or Error before teardown). Not resumable; files being written at that
264
+ * moment may come out partial.
265
+ * @param {OceanNode} nodeUri The provider target (HTTP URL, or peerId / multiaddr for P2P).
266
+ * @param {SignerOrAuthTokenOrSignature} signerOrAuthToken Signer, JWT auth token, or precomputed signature used to authenticate the request.
267
+ * @param {string} serviceId The service.
268
+ * @param {number | 'live'} index An archive index, or `'live'`.
269
+ * @param {number} [offset=0] Byte offset to resume an archive download from.
270
+ * @param {AbortSignal} [signal] Abort signal that cancels the download.
271
+ * @return {Promise<ComputeResultStream>} An async-iterable stream of the zip, starting at `offset`.
272
+ */
273
+ serviceGetResult(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, index: number | 'live', offset?: number, signal?: AbortSignal): Promise<ComputeResultStream>;
254
274
  fetchConfig(nodeUri: OceanNode, payload: Record<string, any>): Promise<any>;
255
275
  pushConfig(nodeUri: OceanNode, payload: Record<string, any>): Promise<any>;
256
276
  }
@@ -381,4 +381,16 @@ export declare class HttpProvider {
381
381
  */
382
382
  getServices(nodeUri: string, signerOrAuthToken: SignerOrAuthTokenOrSignature, filters?: ServiceListFilters, signal?: AbortSignal): Promise<ServiceJobListed[]>;
383
383
  serviceGetStreamableLogs(nodeUri: string, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, since?: string, signal?: AbortSignal): Promise<any>;
384
+ /**
385
+ * Downloads a service's /data/outputs as a zip over HTTP — for a service started without an
386
+ * output bucket. Owner-only.
387
+ * @param {string} nodeUri The provider URI.
388
+ * @param {SignerOrAuthTokenOrSignature} signerOrAuthToken Signer, JWT auth token, or precomputed signature used to authenticate the request.
389
+ * @param {string} serviceId The service.
390
+ * @param {number | 'live'} index An `index` from the service's `outputArchives` (see getServiceStatus), or `'live'` for a zip of the running container's /data/outputs, built as it is read.
391
+ * @param {number} [offset=0] Byte offset to resume an archive download from, sent as the `offset` query parameter (the node answers 200 with the bytes from there on). Must be a non-negative safe integer; not supported with `'live'`.
392
+ * @param {AbortSignal} [signal] Abort signal that cancels the in-flight request.
393
+ * @return {Promise<ComputeResultStream>} An async-iterable stream of the zip, starting at `offset`.
394
+ */
395
+ serviceGetResult(nodeUri: string, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, index: number | 'live', offset?: number, signal?: AbortSignal): Promise<ComputeResultStream>;
384
396
  }
@@ -754,4 +754,21 @@ export declare class P2pProvider {
754
754
  * (Unix seconds, or a relative duration like '30s'/'2h'); omit for the full history then live.
755
755
  */
756
756
  serviceGetStreamableLogs(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, since?: string, signal?: AbortSignal): Promise<any>;
757
+ /**
758
+ * Downloads a service's /data/outputs as a zip over libp2p — for a service started without an
759
+ * output bucket. Owner-only.
760
+ *
761
+ * The transfer mirrors `downloadPersistentStorageFile`: `dialAndStream` takes a concurrency
762
+ * slot, the first frame is a status JSON (an `httpStatus >= 400` throws and releases the
763
+ * slot), and the returned generator streams the zip with flow control, resetting the stream
764
+ * and releasing the slot however iteration ends.
765
+ * @param {OceanNode} nodeUri The provider node (peerId / multiaddr).
766
+ * @param {SignerOrAuthTokenOrSignature} signerOrAuthToken Signer, JWT auth token, or precomputed signature used to authenticate the request.
767
+ * @param {string} serviceId The service.
768
+ * @param {number | 'live'} index An `index` from the service's `outputArchives` (see getServiceStatus), or `'live'` for a zip of the running container's /data/outputs, built as it is read.
769
+ * @param {number} [offset=0] Byte offset to resume an archive download from. Must be a non-negative safe integer; not supported with `'live'`.
770
+ * @param {AbortSignal} [signal] Abort signal that cancels the download mid-flight and tears down the stream.
771
+ * @return {Promise<ComputeResultStream>} An async-iterable stream of the zip, starting at `offset`.
772
+ */
773
+ serviceGetResult(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, index: number | 'live', offset?: number, signal?: AbortSignal): Promise<ComputeResultStream>;
757
774
  }
@@ -158,6 +158,8 @@ export declare class LpFrameReader {
158
158
  private discarded;
159
159
  /** Set when the stream ends in an error, whether raised locally or by the peer. */
160
160
  private closeError;
161
+ /** Set when the peer closed its writable end, i.e. finished sending the response. */
162
+ private remoteEnded;
161
163
  constructor(lp: ReturnType<typeof lpStream>, stream: Stream, maxBufferSize?: number);
162
164
  /** Bytes delivered by the transport that are not yet part of a complete frame. */
163
165
  get pendingBytes(): number;
@@ -165,9 +167,11 @@ export declare class LpFrameReader {
165
167
  signal: AbortSignal;
166
168
  }): Promise<Uint8Array>;
167
169
  /**
168
- * True when `err` is the graceful end of the stream: an end-of-file thrown with
169
- * every delivered byte already accounted for by a complete frame. A truncated
170
- * frame throws the same error type but leaves bytes pending, and returns false.
170
+ * True when `err` is the graceful end of the stream: an end-of-file thrown after the
171
+ * peer closed its writable end, with every delivered byte already accounted for by a
172
+ * complete frame. A truncated frame throws the same error type but leaves bytes
173
+ * pending, and a stream ended by its connection closing never saw the peer's close;
174
+ * both return false.
171
175
  */
172
176
  isCleanEnd(err: unknown): boolean;
173
177
  }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Validates the target of a `serviceGetResult` call before anything is signed or dialled: an
3
+ * archive `index` (with an optional resume `offset`), or `'live'` (which cannot be resumed —
4
+ * each live zip is built afresh, so a byte offset into one means nothing in the next).
5
+ */
6
+ export declare function assertServiceResultTarget(index: number | 'live', offset: number): void;
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Matches a service template's `recommendedResources` against a compute environment (from
3
+ * getComputeEnvironments()): GPU layout planning, plan re-validation and best-effort
4
+ * CPU/RAM/disk sizing. Also the authoring-side sizing rule (GpuSizingProfile -> layouts) and
5
+ * advisory helpers for custom Hugging Face models.
6
+ *
7
+ * Pure: no network, no node config. Callers own access, payment and duration checks, and
8
+ * re-validate a plan (validateGpuPlan) before payment and start.
9
+ *
10
+ * Rules shared with ocean-node and every client:
11
+ * - Memory is compared in integer bytes against ceil(GB * 1e9); unknown memory never fits.
12
+ * - A layout books exactly `gpuCount` whole GPUs of ONE group (same description) on one host.
13
+ * - A GPU resource with (total ?? max) > 1 is a pool. The node hands the container all of its
14
+ * devices whatever amount was requested, so a pool is booked whole or not at all.
15
+ * - The node adds any GPU resource with min > 0 that a request leaves out, so every booking
16
+ * must include it.
17
+ */
18
+ import type { ComputeResource, ComputeResourceRequest } from '../@types/Compute.js';
19
+ import type { GpuLayout, GpuSizingProfile, TemplateResourceRequirement } from '../@types/Services.js';
20
+ /** The GPU member of the TemplateResourceRequirement union. */
21
+ export type GpuResourceRequirement = Extract<TemplateResourceRequirement, {
22
+ type: 'gpu';
23
+ }>;
24
+ /** The CPU / RAM / disk members of the TemplateResourceRequirement union. */
25
+ export type SharedResourceRequirement = Exclude<TemplateResourceRequirement, {
26
+ type: 'gpu';
27
+ }>;
28
+ /** The shared (non-GPU) resource ids a template can declare. */
29
+ export type SharedResourceId = SharedResourceRequirement['id'];
30
+ /** One feasible way to book a GPU layout on an environment. */
31
+ export interface GpuLayoutCandidate {
32
+ /** The declared layout booked; null when the target declares no GPU. */
33
+ layout: GpuLayout | null;
34
+ /** The GPU group (description, or `id:<id>` without one); null without a layout. */
35
+ groupKey: string | null;
36
+ /** Exact whole-unit requests, summing to layout.gpuCount. */
37
+ gpuRequests: ComputeResourceRequest[];
38
+ /** GPU price per minute: sum of fees[id] * amount. */
39
+ gpuPrice: number;
40
+ /** Per-card bytes checked (the group's smallest card); null without a layout. */
41
+ perCardBytes: number | null;
42
+ }
43
+ /** Inputs of planGpuLayouts(). */
44
+ export interface PlanGpuLayoutsParams {
45
+ /** The environment's GPU resources only; `memoryTotal` is per card, also for a pool. */
46
+ gpuResources: ComputeResource[];
47
+ /** The template's GPU requirement; undefined means no GPU demand. */
48
+ requirement?: GpuResourceRequirement;
49
+ /** Fee per unit per minute by resource id, for the chosen chain/token; missing = 0. */
50
+ fees?: Record<string, number>;
51
+ /** Exact width the runtime will use (package TP size or `gpuCountEnv` value). */
52
+ forcedGpuCount?: number;
53
+ }
54
+ /** Result of sizeSharedResources(). */
55
+ export interface SharedResourceSizing {
56
+ /** Allocated amount per declared id, in grant units (cores, GiB). */
57
+ amounts: Partial<Record<SharedResourceId, number>>;
58
+ /** The amounts as requests; zero amounts omitted (the node rejects them). */
59
+ requests: ComputeResourceRequest[];
60
+ /** Declared ids allocated less than recommended, in the recommendation's units. */
61
+ shortfalls: Array<{
62
+ id: SharedResourceId;
63
+ recommended: number;
64
+ allocated: number;
65
+ }>;
66
+ }
67
+ /**
68
+ * Parses a `memoryTotal` string ("143771 MiB", "16 GiB", "8GB", "1024") into bytes, with
69
+ * ocean-node's grammar: b/kb/mb/gb/tb decimal, kib/mib/gib/tib binary, any case, no unit =
70
+ * bytes.
71
+ * @param {string} memoryTotal the advertised memory of one unit
72
+ * @returns {number | undefined} bytes, or undefined when absent, unparseable or <= 0
73
+ */
74
+ export declare function parseMemoryTotalBytes(memoryTotal?: string): number | undefined;
75
+ /**
76
+ * Whole units a new booking can still get: max(0, min(max, total - inUse)), with `max`
77
+ * standing in for a missing `total` (legacy node).
78
+ * @param {ComputeResource} resource the environment resource
79
+ * @returns {number} grantable amount
80
+ */
81
+ export declare function grantableAmount(resource: ComputeResource): number;
82
+ /**
83
+ * Whether a GPU resource is a pool ((total ?? max) > 1), bookable only whole and only when
84
+ * every unit is free.
85
+ * @param {ComputeResource} resource a GPU resource of the environment
86
+ * @returns {boolean} true when the resource may only be booked whole
87
+ */
88
+ export declare function isPooledGpuResource(resource: ComputeResource): boolean;
89
+ /**
90
+ * Every feasible way to book the GPU requirement on one environment, cheapest first.
91
+ *
92
+ * A group qualifies for a declared layout (only `forcedGpuCount` when set) when all its cards
93
+ * report memory, its smallest card holds the per-card VRAM (`recommended` for one GPU,
94
+ * `vramPerGpu` otherwise), `gpuCount` cards hold `recommended`, and enough whole units are
95
+ * free. Ids are the cheapest exact combination (ties: lower fee, then id).
96
+ * @param {PlanGpuLayoutsParams} params GPU resources, requirement, fees and optional forced width
97
+ * @returns {GpuLayoutCandidate[]} sorted by gpuPrice, gpuCount, group key; empty when nothing
98
+ * fits; one empty candidate (layout null) when there is no requirement
99
+ */
100
+ export declare function planGpuLayouts(params: PlanGpuLayoutsParams): GpuLayoutCandidate[];
101
+ /** Result of assertSingleGpuGroup(). */
102
+ export type GpuGroupCheck = {
103
+ ok: true;
104
+ /** The one group every GPU request belongs to; null when no GPU is requested. */
105
+ groupKey: string | null;
106
+ } | {
107
+ ok: false;
108
+ reason: string;
109
+ };
110
+ /**
111
+ * Checks that every requested GPU (amount > 0) is in one group. Non-GPU ids (cpu, ram, disk)
112
+ * are ignored, so the full request list may be passed.
113
+ * @param {ComputeResource[]} gpuResources the environment's GPU resources
114
+ * @param {ComputeResourceRequest[]} requests the selection to check
115
+ * @returns {GpuGroupCheck} ok with the group key, or the reason the selection mixes groups
116
+ */
117
+ export declare function assertSingleGpuGroup(gpuResources: ComputeResource[], requests: ComputeResourceRequest[]): GpuGroupCheck;
118
+ /** Inputs of validateGpuPlan(). */
119
+ export interface ValidateGpuPlanParams {
120
+ /** A FRESH snapshot of the environment's GPU resources. */
121
+ gpuResources: ComputeResource[];
122
+ /** The template's GPU requirement; undefined means no GPU demand. */
123
+ requirement?: GpuResourceRequirement;
124
+ /** The plan's GPU requests only (e.g. a candidate's gpuRequests). */
125
+ requests: ComputeResourceRequest[];
126
+ /** Exact width the runtime will use (package TP size or `gpuCountEnv` value). */
127
+ forcedGpuCount?: number;
128
+ }
129
+ /** Result of validateGpuPlan(). */
130
+ export type GpuPlanCheck = {
131
+ ok: true;
132
+ /** The declared layout the plan books; null without a requirement. */
133
+ layout: GpuLayout | null;
134
+ /** The one group the plan books from; null when it books no GPU. */
135
+ groupKey: string | null;
136
+ } | {
137
+ ok: false;
138
+ reason: string;
139
+ };
140
+ /**
141
+ * Re-checks a chosen plan against a fresh environment snapshot with planGpuLayouts' rules; call
142
+ * it at payment and again at start. Checks whole unique amounts, ids still GPUs of the
143
+ * snapshot, one group, and each amount still grantable (pools whole, mins met). With a
144
+ * requirement also: no min > 0 GPU left out, the count is a declared layout (and
145
+ * forcedGpuCount), and the cards still hold it. Prices are not checked: re-quote from the plan.
146
+ * @param {ValidateGpuPlanParams} params fresh GPU resources, requirement, plan requests, forced width
147
+ * @returns {GpuPlanCheck} ok with the matched layout and group, or the first reason it fails
148
+ */
149
+ export declare function validateGpuPlan(params: ValidateGpuPlanParams): GpuPlanCheck;
150
+ /**
151
+ * Best-effort CPU/RAM/disk sizing for the template's declared recommendations
152
+ * @param {ComputeResource[]} resources the environment's resources (cpu/ram/disk looked up by id)
153
+ * @param {TemplateResourceRequirement[]} requirements the template's recommendedResources
154
+ * @returns {SharedResourceSizing | null} null when a declared id with recommended > 0 is absent
155
+ * or exhausted on the environment, or when any declared id's env min exceeds what is grantable
156
+ */
157
+ export declare function sizeSharedResources(resources: ComputeResource[], requirements?: TemplateResourceRequirement[]): SharedResourceSizing | null;
158
+ /**
159
+ * Validates a GpuSizingProfile against the constraints on its fields; throws an Error naming
160
+ * the first violation.
161
+ * @param {GpuSizingProfile} profile the profile to check
162
+ */
163
+ export declare function validateGpuSizingProfile(profile: GpuSizingProfile): void;
164
+ /**
165
+ * Per-card floor of a declared width: the smallest card memoryTotal (whole decimal GB) the
166
+ * profile fits on at that width. With u = memUtil at width n:
167
+ * needGiB = shardableGiB / n + replicatedGiB
168
+ * cardGiB = max(needGiB / u, outsideGiB > 0 ? outsideGiB / (1 - u) : 0) + driverReserveGiB
169
+ * floorGb(n) = overrides[n]?.vramPerGpu ?? ceil(cardGiB * 1.073741824)
170
+ * @param {GpuSizingProfile} profile the sizing profile (throws when invalid)
171
+ * @param {number} n a width declared in profile.widths (throws otherwise)
172
+ * @returns {number} decimal GB per card
173
+ */
174
+ export declare function gpuFloorGb(profile: GpuSizingProfile, n: number): number;
175
+ /**
176
+ * Turns a profile into the GPU requirement a template carries: width 1 -> { gpuCount: 1 },
177
+ * width n -> { gpuCount: n, vramPerGpu: floorGb(n) } (see gpuFloorGb). `recommended` is
178
+ * floorGb(1) when width 1 is declared (throws when some n * floorGb(n) is below it: the node
179
+ * rejects such layouts), else the smallest n * floorGb(n).
180
+ * @param {GpuSizingProfile} profile the sizing profile (throws when invalid)
181
+ * @returns {GpuResourceRequirement} the requirement; the caller adds gpuCountEnv and description
182
+ */
183
+ export declare function deriveGpuLayouts(profile: GpuSizingProfile): GpuResourceRequirement;
184
+ /** The attention fields of a Hugging Face config.json that decide tensor-parallel widths. */
185
+ export interface HfAttentionConfig {
186
+ num_attention_heads?: number;
187
+ num_key_value_heads?: number;
188
+ }
189
+ /** A minimal Hugging Face config.json; multimodal models nest the LLM under text_config. */
190
+ export interface HfTpConfig extends HfAttentionConfig {
191
+ text_config?: HfAttentionConfig;
192
+ }
193
+ /** Options of legalTpWidths(). */
194
+ export interface LegalTpWidthsOptions {
195
+ /** Widths to test, integers 1..64; default [1, 2, 4, 8]. */
196
+ candidates?: number[];
197
+ }
198
+ /**
199
+ * Tensor-parallel widths the attention heads allow: n is kept when heads % n === 0 and
200
+ * (kv % n === 0 || n % kv === 0), kv = num_key_value_heads (default: heads). Reads text_config
201
+ * when it has num_attention_heads, else the top level.
202
+ *
203
+ * Necessary, not sufficient (quantization blocks, MLA, MoE sharding can rule out more widths).
204
+ * @param {HfTpConfig} cfg the model's config.json
205
+ * @param {LegalTpWidthsOptions} opts candidate widths (throws when not integers 1..64)
206
+ * @returns {number[] | null} legal widths ascending; null when the head count is unknown
207
+ */
208
+ export declare function legalTpWidths(cfg: HfTpConfig | null | undefined, opts?: LegalTpWidthsOptions): number[] | null;
209
+ /** Inputs of estimateHfSizingProfile(); model-shape fields come from config.json / safetensors. */
210
+ export interface HfSizingInput {
211
+ /** Safetensors parameter (element) counts per dtype, e.g. { BF16: 7.2e9, F32: 1e6 }. */
212
+ paramsByDtype?: Record<string, number>;
213
+ /** Total parameter count, used when paramsByDtype is absent. */
214
+ totalParams?: number;
215
+ /** Bytes per parameter with totalParams (default 2), or for a dtype not in the table. */
216
+ bytesPerParam?: number;
217
+ numLayers?: number;
218
+ numKvHeads?: number;
219
+ headDim?: number;
220
+ /** MLA latent rank (DeepSeek kv_lora_rank); its presence means MLA. */
221
+ kvLoraRank?: number;
222
+ /** MLA decoupled RoPE dims cached next to the latent (DeepSeek qk_rope_head_dim). */
223
+ qkRopeHeadDim?: number;
224
+ /** Bytes per cached KV element; default 2. */
225
+ kvBytes?: number;
226
+ /** Context the default configuration must hold, in tokens. */
227
+ contextTokens: number;
228
+ /** Sequences of contextTokens held at once; default 1. */
229
+ concurrentSeqs?: number;
230
+ /** Replicated per-GPU runtime (CUDA context, activations, graphs); default 5.5. */
231
+ runtimeGiB?: number;
232
+ /** Engine memory budget fraction in (0,1); default 0.9. */
233
+ memUtil?: number;
234
+ /** Widths to size, normally legalTpWidths() of the model. */
235
+ widths: number[];
236
+ /** Profile engine label; default 'vllm'. */
237
+ engine?: string;
238
+ }
239
+ /** Result of estimateHfSizingProfile(). */
240
+ export interface HfSizingEstimate {
241
+ profile: GpuSizingProfile;
242
+ /** Inputs missing and counted as 0 or defaulted. */
243
+ unknown: string[];
244
+ }
245
+ /**
246
+ * Advisory GpuSizingProfile for a custom Hugging Face model: a soft filter, never a guarantee.
247
+ *
248
+ * - Weights (sharded): paramsByDtype × dtype size (unknown dtype: bytesPerParam), else
249
+ * totalParams × bytesPerParam (default 2).
250
+ * - KV cache for contextTokens × concurrentSeqs, per token and layer: MLA caches
251
+ * (kvLoraRank + qkRopeHeadDim) × kvBytes, replicated on every rank; otherwise
252
+ * 2 × numKvHeads × headDim × kvBytes, sharded while numKvHeads >= the widest width, else
253
+ * replicated. Missing shape fields count as 0.
254
+ * - runtimeGiB is replicated.
255
+ * Missing or defaulted inputs are listed in `unknown`.
256
+ * @param {HfSizingInput} input model shape, context and knobs
257
+ * @returns {HfSizingEstimate | null} null when the weights are unknown; throws on invalid knobs
258
+ */
259
+ export declare function estimateHfSizingProfile(input: HfSizingInput): HfSizingEstimate | null;
@@ -14,3 +14,4 @@ export * from './Assets.js';
14
14
  export * from './Addresses.js';
15
15
  export * from './bytes.js';
16
16
  export * from './C2dCapability.js';
17
+ export * from './ServiceResources.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oceanprotocol/lib",
3
3
  "source": "./src/index.ts",
4
- "version": "9.3.0-next.5",
4
+ "version": "10.0.0-next.1",
5
5
  "description": "JavaScript client library for Ocean Protocol",
6
6
  "module": "./dist/lib.module.mjs",
7
7
  "type": "module",
@@ -35,7 +35,7 @@
35
35
  "doc:json": "node ./scripts/typedoc.js",
36
36
  "docs": "typedoc --options typedoc.json --plugin typedoc-plugin-markdown",
37
37
  "release": "release-it",
38
- "changelog": "auto-changelog -p",
38
+ "changelog": "bash scripts/changelog.sh",
39
39
  "prepublishOnly": "npm run build",
40
40
  "test": "npm run lint && npm run test:unit:cover && npm run test:integration:cover",
41
41
  "test:unit": "npx tsx ./node_modules/mocha/bin/mocha.js --config ./test/.mocharc.json 'test/unit/**/*.test.ts' --verbose",
@@ -66,6 +66,14 @@
66
66
  "overrides": {
67
67
  "tsup": {
68
68
  "esbuild": "^0.28.2"
69
+ },
70
+ "minimatch": "^11.0.5",
71
+ "glob": "^14.0.4",
72
+ "typedoc": {
73
+ "minimatch": "^10.2.5"
74
+ },
75
+ "get-uri": {
76
+ "basic-ftp": "^6.2.6"
69
77
  }
70
78
  },
71
79
  "dependencies": {