@oceanprotocol/lib 9.3.0-next.6 → 10.0.0

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[];
@@ -50,6 +50,15 @@ export interface NodeStatusIndexer {
50
50
  network: string;
51
51
  block: string;
52
52
  }
53
+ export interface NodeStatusMaintenance {
54
+ enabled: boolean;
55
+ /** Detailed status only: compute jobs still running while draining. */
56
+ runningComputeJobs?: number;
57
+ /** Detailed status only: services still running while draining. */
58
+ runningServices?: number;
59
+ /** Detailed status only: unix seconds, drain ETA. */
60
+ latestExpectedEndTime?: number;
61
+ }
53
62
  export interface NodeStatus {
54
63
  id: string;
55
64
  publicKey: string;
@@ -61,6 +70,8 @@ export interface NodeStatus {
61
70
  provider: NodeStatusProvider[];
62
71
  indexer: NodeStatusIndexer[];
63
72
  escrowAddress: Record<string, string>;
73
+ /** Maintenance (drain) mode. Absent on nodes that predate the feature. */
74
+ maintenance?: NodeStatusMaintenance;
64
75
  supportedStorage: Record<string, boolean>;
65
76
  platform: {
66
77
  cpus: number;
@@ -227,6 +238,7 @@ export declare const PROTOCOL_COMMANDS: {
227
238
  FETCH_CONFIG: string;
228
239
  PUSH_CONFIG: string;
229
240
  GET_LOGS: string;
241
+ SET_MAINTENANCE: string;
230
242
  JOBS: string;
231
243
  PERSISTENT_STORAGE_CREATE_BUCKET: string;
232
244
  PERSISTENT_STORAGE_UPDATE_BUCKET: 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
  }
@@ -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 {};
@@ -124,6 +124,20 @@ export declare class BaseProvider {
124
124
  PolicyServerPassthrough(nodeUri: OceanNode, request: PolicyServerPassthroughCommand, signal?: AbortSignal): Promise<any>;
125
125
  initializePSVerification(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, request: PolicyServerInitializeCommand, signal?: AbortSignal): Promise<any>;
126
126
  downloadNodeLogs(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, startTime: string, endTime: string, maxLogs?: number, moduleName?: string, level?: string, page?: number, signal?: AbortSignal): Promise<NodeLogEntry[]>;
127
+ /**
128
+ * Enables or disables the node's maintenance (drain) mode. Admin only.
129
+ * While enabled the node rejects new compute/service requests with
130
+ * `code: 'MAINTENANCE_MODE'` (detect with `isMaintenanceError`); running jobs continue.
131
+ * Works over HTTP (`POST /api/admin/maintenance`) and P2P.
132
+ * @param {OceanNode} nodeUri - The node URI / peerId / multiaddr.
133
+ * @param {SignerOrAuthTokenOrSignature} signerOrAuthToken - Admin signer / auth token.
134
+ * @param {boolean} enabled - true to start draining, false to resume.
135
+ * @param {AbortSignal} [signal] - An optional abort signal.
136
+ * @returns {Promise<{ maintenance: boolean }>} The node's resulting maintenance state.
137
+ */
138
+ setMaintenance(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, enabled: boolean, signal?: AbortSignal): Promise<{
139
+ maintenance: boolean;
140
+ }>;
127
141
  getNodeStatus(nodeUri: OceanNode, signal?: AbortSignal): Promise<NodeStatus>;
128
142
  getNodeJobs(nodeUri: OceanNode, fromTimestamp?: number, signal?: AbortSignal): Promise<NodeComputeJob[]>;
129
143
  /**
@@ -285,6 +285,32 @@ export declare class HttpProvider {
285
285
  * @returns {Promise<any>} The logs response body stream.
286
286
  */
287
287
  downloadNodeLogs(nodeUri: string, signerOrAuthToken: SignerOrAuthTokenOrSignature, startTime: string, endTime: string, maxLogs?: number, moduleName?: string, level?: string, page?: number, signal?: AbortSignal): Promise<NodeLogEntry[]>;
288
+ /**
289
+ * Builds the typed error for a non-ok response whose body is read as text. The message
290
+ * stays the raw text (as before); `code`/`body` are populated when the text is JSON.
291
+ */
292
+ private toProviderError;
293
+ /**
294
+ * Enables or disables the node's maintenance (drain) mode. Admin only: the caller must
295
+ * be in the node's ALLOWED_ADMINS / admin access list.
296
+ *
297
+ * While enabled the node rejects new commitment (`computeStart`, `freeComputeStart`,
298
+ * `initializeCompute`, `serviceStart`, `serviceExtend`) with HTTP 503 and
299
+ * `code: 'MAINTENANCE_MODE'` (see `isMaintenanceError`); running jobs and services
300
+ * continue. Read progress via `getNodeStatus` (`maintenance`).
301
+ *
302
+ * Calls `POST /api/admin/maintenance`. The request is signed over
303
+ * `address + nonce + 'setMaintenance'`; `enabled` is sent as a real JSON boolean, which
304
+ * the node requires.
305
+ * @param {string} nodeUri - The node URI.
306
+ * @param {SignerOrAuthTokenOrSignature} signerOrAuthToken - Admin signer / auth token.
307
+ * @param {boolean} enabled - true to start draining, false to resume.
308
+ * @param {AbortSignal} [signal] - An optional abort signal.
309
+ * @returns {Promise<{ maintenance: boolean }>} The node's resulting maintenance state.
310
+ */
311
+ setMaintenance(nodeUri: string, signerOrAuthToken: SignerOrAuthTokenOrSignature, enabled: boolean, signal?: AbortSignal): Promise<{
312
+ maintenance: boolean;
313
+ }>;
288
314
  private noZeroX;
289
315
  private zeroXTransformer;
290
316
  private inputMatch;
@@ -68,14 +68,29 @@ export declare class P2pError extends Error {
68
68
  readonly peerResponse?: {
69
69
  value: unknown;
70
70
  };
71
+ /** HTTP status the peer reported in its status frame, when it reported one. */
72
+ readonly httpStatus?: number;
73
+ /** Machine-readable `code` from the peer's status frame (e.g. `MAINTENANCE_MODE`). */
74
+ readonly code?: string;
75
+ /** The peer's status frame / reply body, when it reported the failure itself. */
76
+ readonly body?: unknown;
71
77
  constructor(type: P2pErrorType, message: string, options?: {
72
78
  cause?: unknown;
73
79
  peerId?: string;
74
80
  peerResponse?: {
75
81
  value: unknown;
76
82
  };
83
+ httpStatus?: number;
84
+ code?: string;
85
+ body?: unknown;
77
86
  });
78
87
  }
88
+ /**
89
+ * Wraps a peer-reported failure (a status frame with `httpStatus >= 400`) so the
90
+ * node's `code`, status and body survive. The message is the same text the untyped
91
+ * code threw; `asP2pCommandError` adds the usual `P2P command error:` prefix later.
92
+ */
93
+ export declare function peerReportedError(frame: Record<string, any>, message: string): P2pError;
79
94
  /**
80
95
  * Classifies a thrown value.
81
96
  *
@@ -89,6 +104,11 @@ export declare class P2pError extends Error {
89
104
  */
90
105
  export declare function classifyP2pError(err: unknown): P2pErrorType;
91
106
  export declare function isRetryableP2pError(type: P2pErrorType): boolean;
107
+ /**
108
+ * Final error for a failed command. Preserves the `P2P command error: <message>`
109
+ * shaping the untyped code produced — consumers match on it — and adds the type.
110
+ */
111
+ export declare function asP2pCommandError(err: unknown, type: P2pErrorType): P2pError;
92
112
  /**
93
113
  * Optional request payload sent as LP frames after the command JSON; ends with an empty LP frame.
94
114
  * This mirrors ocean-node's `p2pStreamBody` mechanism introduced for true streaming uploads.
@@ -667,6 +687,23 @@ export declare class P2pProvider {
667
687
  * string: `consumerAddress + nonce + "PolicyServerInitialize"`.
668
688
  */
669
689
  initializePSVerification(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, request: PolicyServerInitializeCommand, signal?: AbortSignal): Promise<any>;
690
+ /**
691
+ * Enables or disables the node's maintenance (drain) mode via P2P. Admin only.
692
+ *
693
+ * While enabled the node rejects new `computeStart`, `freeComputeStart`,
694
+ * `initializeCompute`, `serviceStart` and `serviceExtend` with `code: 'MAINTENANCE_MODE'`
695
+ * (see `isMaintenanceError`); running jobs continue. The request is signed over
696
+ * `address + nonce + 'setMaintenance'` and `enabled` is sent as a real boolean, which the
697
+ * node requires.
698
+ * @param {OceanNode} nodeUri - The node peerId / multiaddr.
699
+ * @param {SignerOrAuthTokenOrSignature} signerOrAuthToken - Admin signer / auth token.
700
+ * @param {boolean} enabled - true to start draining, false to resume.
701
+ * @param {AbortSignal} [signal] - An optional abort signal.
702
+ * @returns {Promise<{ maintenance: boolean }>} The node's resulting maintenance state.
703
+ */
704
+ setMaintenance(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, enabled: boolean, signal?: AbortSignal): Promise<{
705
+ maintenance: boolean;
706
+ }>;
670
707
  /**
671
708
  * Download node logs via P2P.
672
709
  */
@@ -1 +1,42 @@
1
1
  export declare function getErrorMessage(err: string): string;
2
+ /** Machine-readable `code` the node attaches to maintenance (drain mode) rejections. */
3
+ export declare const MAINTENANCE_MODE_CODE = "MAINTENANCE_MODE";
4
+ /**
5
+ * Error thrown when an Ocean Node answers a request with a non-ok response.
6
+ *
7
+ * Extends `Error` and keeps `message` byte-identical to what the library threw before
8
+ * (the JSON-stringified response body, or the raw text when that is what was read), so
9
+ * `e.message`, `instanceof Error` and `JSON.parse(e.message)` keep working. The extra
10
+ * fields let callers branch on a machine-readable `code` instead of matching text.
11
+ */
12
+ export declare class OceanNodeProviderError extends Error {
13
+ /** HTTP status of the node's reply (also carried on the P2P status frame). */
14
+ readonly httpStatus?: number;
15
+ /** Machine-readable code from the node's body, e.g. `MAINTENANCE_MODE`. */
16
+ readonly code?: string;
17
+ /** The node's response body: parsed JSON when it was JSON, raw text otherwise. */
18
+ readonly body?: any;
19
+ /**
20
+ * @param resolved The node's response body (parsed JSON or raw text).
21
+ * @param httpStatus HTTP status of the response.
22
+ * @param message Optional message override; defaults to `JSON.stringify(resolved)`.
23
+ * Callers that read the body as text (e.g. `toProviderError`) pass that text here so
24
+ * the message stays byte-identical to the pre-existing `new Error(text)` throw.
25
+ */
26
+ constructor(resolved: any, httpStatus?: number, message?: string);
27
+ }
28
+ /**
29
+ * True when `e` is a node rejection caused by maintenance (drain) mode.
30
+ * Works for both transports: HTTP throws `OceanNodeProviderError`, P2P throws a
31
+ * `P2pError` that carries the same `code` field.
32
+ *
33
+ * A type guard: in the true branch `e` narrows to an `Error` whose `code` is
34
+ * `MAINTENANCE_MODE_CODE`. `httpStatus` and `body` are exposed as OPTIONAL because this
35
+ * check does not validate them — they are present on the errors the library throws, but
36
+ * the guard only asserts `code`.
37
+ */
38
+ export declare function isMaintenanceError(e: unknown): e is Error & {
39
+ code: typeof MAINTENANCE_MODE_CODE;
40
+ httpStatus?: number;
41
+ body?: unknown;
42
+ };
@@ -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';