@moss-dev/moss-web 1.0.0 → 1.2.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.
- package/README.md +85 -4
- package/dist/auth/authenticator.interface.d.ts +8 -0
- package/dist/auth/authenticator.interface.js +1 -0
- package/dist/auth/caching.authenticator.d.ts +11 -0
- package/dist/auth/caching.authenticator.js +35 -0
- package/dist/client.d.ts +42 -1
- package/dist/client.js +208 -25
- package/dist/embedder.d.ts +13 -11
- package/dist/embedder.js +86 -66
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/model-artifact-ownership.d.ts +18 -0
- package/dist/model-artifact-ownership.js +106 -0
- package/dist/model-config.d.ts +3 -0
- package/dist/model-config.js +8 -0
- package/dist/model-delivery.d.ts +61 -0
- package/dist/model-delivery.js +279 -0
- package/dist/sha256.d.ts +14 -0
- package/dist/sha256.js +152 -0
- package/dist/types.d.ts +19 -1
- package/dist/wasm-runtime-capability.d.ts +14 -0
- package/dist/wasm-runtime-capability.js +68 -0
- package/package.json +7 -7
package/dist/embedder.js
CHANGED
|
@@ -1,85 +1,105 @@
|
|
|
1
1
|
import * as ort from "onnxruntime-web";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
"moss-minilm": { hiddenDim: 384 },
|
|
5
|
-
"moss-mediumlm": { hiddenDim: 1024 },
|
|
6
|
-
};
|
|
2
|
+
import { modelHiddenDim } from "./model-config.js";
|
|
3
|
+
import { loadSealedModel } from "./model-delivery.js";
|
|
7
4
|
export class Embedder {
|
|
8
|
-
constructor(modelId,
|
|
9
|
-
this.
|
|
10
|
-
this.
|
|
11
|
-
this.initPromise = null;
|
|
5
|
+
constructor(modelId, poolAndNormalize, delivery) {
|
|
6
|
+
this.runtimes = new Map();
|
|
7
|
+
this.retainedKeys = new Set();
|
|
12
8
|
this.modelId = modelId;
|
|
13
|
-
this.hiddenDim = MODEL_CONFIGS[modelId].hiddenDim;
|
|
14
|
-
this.wasmTokenizerCtor = wasmTokenizerCtor;
|
|
15
9
|
this.poolAndNormalize = poolAndNormalize;
|
|
10
|
+
this.delivery = delivery;
|
|
16
11
|
}
|
|
17
12
|
async init(onnxWasmPath) {
|
|
18
|
-
if (this.initPromise)
|
|
19
|
-
return this.initPromise;
|
|
20
|
-
this.initPromise = this._init(onnxWasmPath);
|
|
21
|
-
return this.initPromise;
|
|
22
|
-
}
|
|
23
|
-
async _init(onnxWasmPath) {
|
|
24
13
|
if (onnxWasmPath) {
|
|
25
14
|
ort.env.wasm.wasmPaths = onnxWasmPath;
|
|
26
15
|
}
|
|
27
|
-
const modelUrl = `${CDN_BASE}${this.modelId}/`;
|
|
28
|
-
const [tokenizerBytes, onnxModel] = await Promise.all([
|
|
29
|
-
fetch(`${modelUrl}tokenizer.json`).then((r) => {
|
|
30
|
-
if (!r.ok)
|
|
31
|
-
throw new Error(`Failed to fetch tokenizer.json: ${r.status}`);
|
|
32
|
-
return r.arrayBuffer();
|
|
33
|
-
}),
|
|
34
|
-
fetch(`${modelUrl}onnx/model.onnx`).then((r) => {
|
|
35
|
-
if (!r.ok)
|
|
36
|
-
throw new Error(`Failed to fetch model.onnx: ${r.status}`);
|
|
37
|
-
return r.arrayBuffer();
|
|
38
|
-
}),
|
|
39
|
-
]);
|
|
40
|
-
this.tokenizer = new this.wasmTokenizerCtor(new Uint8Array(tokenizerBytes));
|
|
41
|
-
this.session = await ort.InferenceSession.create(onnxModel, {
|
|
42
|
-
executionProviders: ["wasm"],
|
|
43
|
-
graphOptimizationLevel: "all",
|
|
44
|
-
});
|
|
45
16
|
}
|
|
46
|
-
async embed(text) {
|
|
47
|
-
if (
|
|
48
|
-
throw new Error(
|
|
17
|
+
async embed(text, identity) {
|
|
18
|
+
if (identity.modelId !== this.modelId) {
|
|
19
|
+
throw new Error(`Loaded index requires model '${identity.modelId}', but this client is configured for '${this.modelId}'`);
|
|
49
20
|
}
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (!firstKey)
|
|
21
|
+
const [key, entry] = this.runtimeFor(identity);
|
|
22
|
+
entry.users += 1;
|
|
23
|
+
try {
|
|
24
|
+
const runtime = await entry.promise;
|
|
25
|
+
const tokens = runtime.tokenizer.tokenize(text);
|
|
26
|
+
const seqLen = tokens.inputIds.length;
|
|
27
|
+
const feeds = {
|
|
28
|
+
input_ids: new ort.Tensor("int64", BigInt64Array.from(tokens.inputIds.map(BigInt)), [1, seqLen]),
|
|
29
|
+
attention_mask: new ort.Tensor("int64", BigInt64Array.from(tokens.attentionMask.map(BigInt)), [1, seqLen]),
|
|
30
|
+
token_type_ids: new ort.Tensor("int64", BigInt64Array.from(tokens.tokenTypeIds.map(BigInt)), [1, seqLen]),
|
|
31
|
+
};
|
|
32
|
+
const output = await runtime.session.run(feeds);
|
|
33
|
+
const tensor = output.last_hidden_state ?? output[Object.keys(output)[0] ?? ""];
|
|
34
|
+
if (!tensor)
|
|
65
35
|
throw new Error("ONNX model returned no outputs");
|
|
66
|
-
|
|
67
|
-
|
|
36
|
+
return this.poolAndNormalize(tensor.data, new Int32Array(tokens.attentionMask), runtime.hiddenDim);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
entry.users -= 1;
|
|
40
|
+
if (!entry.retained && entry.users === 0)
|
|
41
|
+
this.retireRuntime(key, entry);
|
|
68
42
|
}
|
|
69
|
-
return this.poolResult(lastHiddenState.data, tokens.attentionMask);
|
|
70
43
|
}
|
|
71
|
-
|
|
72
|
-
|
|
44
|
+
retainModelArtifacts(identities) {
|
|
45
|
+
this.retainedKeys = new Set(identities.map((identity) => this.identityKey(identity)));
|
|
46
|
+
for (const [key, entry] of this.runtimes) {
|
|
47
|
+
entry.retained = this.retainedKeys.has(key);
|
|
48
|
+
if (!entry.retained && entry.users === 0)
|
|
49
|
+
this.retireRuntime(key, entry);
|
|
50
|
+
}
|
|
73
51
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
52
|
+
runtimeFor(identity) {
|
|
53
|
+
const key = this.identityKey(identity);
|
|
54
|
+
const existing = this.runtimes.get(key);
|
|
55
|
+
if (existing)
|
|
56
|
+
return [key, existing];
|
|
57
|
+
let entry;
|
|
58
|
+
const promise = this.loadRuntime(identity).catch((error) => {
|
|
59
|
+
if (this.runtimes.get(key) === entry)
|
|
60
|
+
this.runtimes.delete(key);
|
|
61
|
+
throw error;
|
|
62
|
+
});
|
|
63
|
+
entry = { promise, users: 0, retained: this.retainedKeys.has(key) };
|
|
64
|
+
this.runtimes.set(key, entry);
|
|
65
|
+
return [key, entry];
|
|
66
|
+
}
|
|
67
|
+
identityKey(identity) {
|
|
68
|
+
return `${identity.modelId}\0${identity.version}\0${identity.manifestSha256}`;
|
|
69
|
+
}
|
|
70
|
+
retireRuntime(key, entry) {
|
|
71
|
+
if (this.runtimes.get(key) !== entry)
|
|
72
|
+
return;
|
|
73
|
+
this.runtimes.delete(key);
|
|
74
|
+
void entry.promise.then(({ tokenizer, session }) => {
|
|
75
|
+
tokenizer.free();
|
|
76
|
+
session.release();
|
|
77
|
+
}).catch(() => undefined);
|
|
78
|
+
}
|
|
79
|
+
async loadRuntime(identity) {
|
|
80
|
+
const { graph, tokenizer } = await loadSealedModel(this.delivery, identity);
|
|
81
|
+
try {
|
|
82
|
+
const session = await ort.InferenceSession.create(graph, {
|
|
83
|
+
executionProviders: ["wasm"],
|
|
84
|
+
graphOptimizationLevel: "all",
|
|
85
|
+
});
|
|
86
|
+
return {
|
|
87
|
+
tokenizer,
|
|
88
|
+
session,
|
|
89
|
+
hiddenDim: modelHiddenDim(identity.modelId),
|
|
90
|
+
};
|
|
78
91
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
92
|
+
catch (error) {
|
|
93
|
+
tokenizer.free();
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
dispose() {
|
|
98
|
+
this.retainedKeys.clear();
|
|
99
|
+
for (const [key, entry] of this.runtimes) {
|
|
100
|
+
entry.retained = false;
|
|
101
|
+
if (entry.users === 0)
|
|
102
|
+
this.retireRuntime(key, entry);
|
|
82
103
|
}
|
|
83
|
-
this.initPromise = null;
|
|
84
104
|
}
|
|
85
105
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
export { MossClient } from "./client";
|
|
2
|
-
export type {
|
|
1
|
+
export { MossClient } from "./client.js";
|
|
2
|
+
export type { IAuthenticator, AuthToken } from "./auth/authenticator.interface.js";
|
|
3
|
+
export { ModelDeliveryError } from "./model-delivery.js";
|
|
4
|
+
export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, ModelArtifactIdentity, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult, ISODate, } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export { MossClient } from "./client";
|
|
1
|
+
export { MossClient } from "./client.js";
|
|
2
|
+
export { ModelDeliveryError } from "./model-delivery.js";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ModelArtifactIdentity } from "./types.js";
|
|
2
|
+
export declare class ModelArtifactOwnership {
|
|
3
|
+
private readonly identities;
|
|
4
|
+
private readonly retain;
|
|
5
|
+
constructor(retain: (identities: ModelArtifactIdentity[]) => void);
|
|
6
|
+
has(indexName: string): boolean;
|
|
7
|
+
get(indexName: string): ModelArtifactIdentity | null | undefined;
|
|
8
|
+
synchronize(indexName: string, identity: ModelArtifactIdentity | null): void;
|
|
9
|
+
clear(indexName: string): void;
|
|
10
|
+
clearAll(): void;
|
|
11
|
+
replaceAfter<T>(indexName: string, transition: () => Promise<T>, identityFromResult: (result: T) => ModelArtifactIdentity | null, rollbackSynchronizedTransition?: (result: T) => Promise<void>): Promise<T>;
|
|
12
|
+
removeAfter<T>(indexName: string, transition: () => Promise<T>): Promise<T>;
|
|
13
|
+
/** Clear an index's identity while an error is already propagating: the
|
|
14
|
+
* map entry is always removed, but a failure releasing runtimes is
|
|
15
|
+
* swallowed so it cannot mask the primary error. */
|
|
16
|
+
private clearWithoutMasking;
|
|
17
|
+
private retainCurrentArtifacts;
|
|
18
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
export class ModelArtifactOwnership {
|
|
2
|
+
constructor(retain) {
|
|
3
|
+
this.identities = new Map();
|
|
4
|
+
this.retain = retain;
|
|
5
|
+
}
|
|
6
|
+
has(indexName) {
|
|
7
|
+
return this.identities.has(indexName);
|
|
8
|
+
}
|
|
9
|
+
get(indexName) {
|
|
10
|
+
return this.identities.get(indexName);
|
|
11
|
+
}
|
|
12
|
+
synchronize(indexName, identity) {
|
|
13
|
+
const hadPrevious = this.identities.has(indexName);
|
|
14
|
+
const previous = this.identities.get(indexName);
|
|
15
|
+
this.identities.set(indexName, identity);
|
|
16
|
+
try {
|
|
17
|
+
this.retainCurrentArtifacts();
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (hadPrevious) {
|
|
21
|
+
this.identities.set(indexName, previous ?? null);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
this.identities.delete(indexName);
|
|
25
|
+
}
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
clear(indexName) {
|
|
30
|
+
if (!this.identities.delete(indexName))
|
|
31
|
+
return;
|
|
32
|
+
this.retainCurrentArtifacts();
|
|
33
|
+
}
|
|
34
|
+
clearAll() {
|
|
35
|
+
if (this.identities.size === 0)
|
|
36
|
+
return;
|
|
37
|
+
this.identities.clear();
|
|
38
|
+
this.retainCurrentArtifacts();
|
|
39
|
+
}
|
|
40
|
+
async replaceAfter(indexName, transition, identityFromResult, rollbackSynchronizedTransition) {
|
|
41
|
+
let result;
|
|
42
|
+
let transitioned = false;
|
|
43
|
+
let synchronizationStarted = false;
|
|
44
|
+
try {
|
|
45
|
+
result = await transition();
|
|
46
|
+
transitioned = true;
|
|
47
|
+
const identity = identityFromResult(result);
|
|
48
|
+
synchronizationStarted = true;
|
|
49
|
+
this.synchronize(indexName, identity);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (!transitioned) {
|
|
54
|
+
// The transition itself failed: the index did not advance, but its
|
|
55
|
+
// identity may now be stale, so drop it. A retain failure while
|
|
56
|
+
// clearing must never mask the transition error.
|
|
57
|
+
this.clearWithoutMasking(indexName);
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
if (rollbackSynchronizedTransition) {
|
|
61
|
+
// The index transitioned but its identity could not be derived or
|
|
62
|
+
// synchronized. Undo the transition; the index ends unloaded, so its
|
|
63
|
+
// identity entry goes with it.
|
|
64
|
+
try {
|
|
65
|
+
await rollbackSynchronizedTransition(result);
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
68
|
+
this.clearWithoutMasking(indexName);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
if (!synchronizationStarted) {
|
|
72
|
+
this.clearWithoutMasking(indexName);
|
|
73
|
+
}
|
|
74
|
+
// No rollback: the index remains loaded. When `synchronize` failed it
|
|
75
|
+
// already restored the previous identity, so leave the map alone.
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async removeAfter(indexName, transition) {
|
|
80
|
+
let result;
|
|
81
|
+
try {
|
|
82
|
+
result = await transition();
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
// The identity must still be dropped, but a retain failure during the
|
|
86
|
+
// unwind must not replace the transition error.
|
|
87
|
+
this.clearWithoutMasking(indexName);
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
this.clear(indexName);
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
/** Clear an index's identity while an error is already propagating: the
|
|
94
|
+
* map entry is always removed, but a failure releasing runtimes is
|
|
95
|
+
* swallowed so it cannot mask the primary error. */
|
|
96
|
+
clearWithoutMasking(indexName) {
|
|
97
|
+
try {
|
|
98
|
+
this.clear(indexName);
|
|
99
|
+
}
|
|
100
|
+
catch { }
|
|
101
|
+
}
|
|
102
|
+
retainCurrentArtifacts() {
|
|
103
|
+
const artifacts = Array.from(this.identities.values()).filter((identity) => identity !== null);
|
|
104
|
+
this.retain(artifacts);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
const MODEL_CONFIGS = {
|
|
2
|
+
"moss-minilm": { hiddenDim: 384 },
|
|
3
|
+
"moss-mediumlm": { hiddenDim: 512 },
|
|
4
|
+
};
|
|
5
|
+
/** Width of the model's last hidden state, as expected by `poolAndNormalize`. */
|
|
6
|
+
export function modelHiddenDim(modelId) {
|
|
7
|
+
return MODEL_CONFIGS[modelId].hiddenDim;
|
|
8
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ModelContentKeys, ModelKeyExchange, SealedModel, Tokenizer } from "@moss-dev/moss-wasm";
|
|
2
|
+
import type { ModelArtifactIdentity } from "./types.js";
|
|
3
|
+
export declare const DEFAULT_INDEX_BASE_URL = "https://service.usemoss.dev/index";
|
|
4
|
+
export declare const DEFAULT_MODEL_ARTIFACT_ORIGIN = "https://models.moss.link";
|
|
5
|
+
export interface SealedModelRuntime {
|
|
6
|
+
newKeyExchange(): ModelKeyExchange;
|
|
7
|
+
openSealedModel(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModel;
|
|
8
|
+
}
|
|
9
|
+
export interface ModelDeliveryAuth {
|
|
10
|
+
getAuthHeader(): Promise<string>;
|
|
11
|
+
invalidate(): Promise<void> | void;
|
|
12
|
+
}
|
|
13
|
+
export interface ModelDeliveryOptions {
|
|
14
|
+
projectId: string;
|
|
15
|
+
auth: ModelDeliveryAuth;
|
|
16
|
+
runtime: SealedModelRuntime;
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
artifactOrigin?: string;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
}
|
|
21
|
+
export interface GrantedObject {
|
|
22
|
+
url: string;
|
|
23
|
+
capability: string;
|
|
24
|
+
expiresAtMs: number;
|
|
25
|
+
}
|
|
26
|
+
export interface ModelDeliveryGrant {
|
|
27
|
+
modelId: string;
|
|
28
|
+
identity: ModelArtifactIdentity;
|
|
29
|
+
release: GrantedObject;
|
|
30
|
+
model: GrantedObject;
|
|
31
|
+
acceptedArtifactVersions: string[];
|
|
32
|
+
json: string;
|
|
33
|
+
}
|
|
34
|
+
export interface SealedModelBundle {
|
|
35
|
+
grant: ModelDeliveryGrant;
|
|
36
|
+
graph: Uint8Array;
|
|
37
|
+
tokenizer: Tokenizer;
|
|
38
|
+
}
|
|
39
|
+
export declare class ModelDeliveryError extends Error {
|
|
40
|
+
readonly status: number | undefined;
|
|
41
|
+
readonly code: string | undefined;
|
|
42
|
+
constructor(message: string, status?: number, code?: string);
|
|
43
|
+
}
|
|
44
|
+
interface ArtifactOrigin {
|
|
45
|
+
protocol: string;
|
|
46
|
+
host: string;
|
|
47
|
+
}
|
|
48
|
+
interface ReleaseFile {
|
|
49
|
+
relativePath: string;
|
|
50
|
+
sha256: string;
|
|
51
|
+
sizeBytes: number;
|
|
52
|
+
}
|
|
53
|
+
export declare function parseArtifactOrigin(value: string): ArtifactOrigin;
|
|
54
|
+
export declare function parseModelDeliveryGrant(json: string, sku: string, artifactOrigin?: string): ModelDeliveryGrant;
|
|
55
|
+
export declare function grantAcceptsStamp(grant: ModelDeliveryGrant, stamped: ModelArtifactIdentity): boolean;
|
|
56
|
+
export declare function requestModelDeliveryGrant(options: ModelDeliveryOptions, sku: string, capabilityQuery: string): Promise<ModelDeliveryGrant>;
|
|
57
|
+
export declare function fetchGrantedBytes(fetchFn: typeof fetch, object: GrantedObject, maxBytes?: number): Promise<Uint8Array>;
|
|
58
|
+
export declare function verifyReleaseManifest(releaseBytes: Uint8Array, grant: ModelDeliveryGrant): Promise<ReleaseFile>;
|
|
59
|
+
export declare function verifyModelBytes(bytes: Uint8Array, record: ReleaseFile): Promise<void>;
|
|
60
|
+
export declare function loadSealedModel(options: ModelDeliveryOptions, stamped: ModelArtifactIdentity): Promise<SealedModelBundle>;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { sha256Hex } from "./sha256.js";
|
|
2
|
+
import { exactModelArtifactIdentity } from "./wasm-runtime-capability.js";
|
|
3
|
+
export const DEFAULT_INDEX_BASE_URL = "https://service.usemoss.dev/index";
|
|
4
|
+
export const DEFAULT_MODEL_ARTIFACT_ORIGIN = "https://models.moss.link";
|
|
5
|
+
const ARTIFACTS_PREFIX = "/artifacts/v1";
|
|
6
|
+
const RELEASE_FILE = "release.json";
|
|
7
|
+
const MODEL_FILE = "model.mossml";
|
|
8
|
+
const SUPPORTED_RELEASE_SCHEMA_VERSIONS = [1, 2];
|
|
9
|
+
const MAX_RELEASE_MANIFEST_BYTES = 1024 * 1024;
|
|
10
|
+
export class ModelDeliveryError extends Error {
|
|
11
|
+
constructor(message, status, code) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "ModelDeliveryError";
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function isCanonicalSha256(value) {
|
|
19
|
+
return /^[0-9a-f]{64}$/.test(value);
|
|
20
|
+
}
|
|
21
|
+
function isSafeRelativePath(value) {
|
|
22
|
+
if (!value || value.startsWith("/") || value.includes("\\"))
|
|
23
|
+
return false;
|
|
24
|
+
const parts = value.split("/");
|
|
25
|
+
return parts.every((part) => part.length > 0 && part !== "." && part !== "..");
|
|
26
|
+
}
|
|
27
|
+
export function parseArtifactOrigin(value) {
|
|
28
|
+
let url;
|
|
29
|
+
try {
|
|
30
|
+
url = new URL(value);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new ModelDeliveryError(`Model artifact origin is not a valid URL: ${String(error)}`);
|
|
34
|
+
}
|
|
35
|
+
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
36
|
+
if (!(url.protocol === "https:" || (url.protocol === "http:" && loopback))) {
|
|
37
|
+
throw new ModelDeliveryError(`Model artifact origin scheme '${url.protocol}' is not allowed for host '${url.hostname}'`);
|
|
38
|
+
}
|
|
39
|
+
if (url.pathname !== "/" || url.search || url.hash || url.username || url.password) {
|
|
40
|
+
throw new ModelDeliveryError("Model artifact origin must be scheme://host[:port] only");
|
|
41
|
+
}
|
|
42
|
+
return { protocol: url.protocol, host: url.host.toLowerCase() };
|
|
43
|
+
}
|
|
44
|
+
function validateGrantedUrl(url, origin, sku, version, object) {
|
|
45
|
+
let parsed;
|
|
46
|
+
try {
|
|
47
|
+
parsed = new URL(url);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
throw new ModelDeliveryError(`${object} url is not valid: ${String(error)}`);
|
|
51
|
+
}
|
|
52
|
+
const expectedPath = `${ARTIFACTS_PREFIX}/${sku}/${version}/${object}`;
|
|
53
|
+
if (parsed.protocol !== origin.protocol
|
|
54
|
+
|| parsed.host.toLowerCase() !== origin.host
|
|
55
|
+
|| parsed.pathname !== expectedPath
|
|
56
|
+
|| parsed.search
|
|
57
|
+
|| parsed.hash
|
|
58
|
+
|| parsed.username
|
|
59
|
+
|| parsed.password) {
|
|
60
|
+
throw new ModelDeliveryError(`${object} url on ${parsed.host} is outside ${origin.protocol}//${origin.host}${expectedPath}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function grantedObject(value, name) {
|
|
64
|
+
if (!value || typeof value !== "object") {
|
|
65
|
+
throw new ModelDeliveryError(`Model grant is missing '${name}'`);
|
|
66
|
+
}
|
|
67
|
+
const object = value;
|
|
68
|
+
if (typeof object.url !== "string"
|
|
69
|
+
|| typeof object.capability !== "string"
|
|
70
|
+
|| object.capability.trim() === ""
|
|
71
|
+
|| typeof object.expiresAtMs !== "number") {
|
|
72
|
+
throw new ModelDeliveryError(`Model grant '${name}' has an unsupported shape`);
|
|
73
|
+
}
|
|
74
|
+
return { url: object.url, capability: object.capability, expiresAtMs: object.expiresAtMs };
|
|
75
|
+
}
|
|
76
|
+
export function parseModelDeliveryGrant(json, sku, artifactOrigin = DEFAULT_MODEL_ARTIFACT_ORIGIN) {
|
|
77
|
+
let decoded;
|
|
78
|
+
try {
|
|
79
|
+
decoded = JSON.parse(json);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
throw new ModelDeliveryError(`Model grant is not valid JSON: ${String(error)}`);
|
|
83
|
+
}
|
|
84
|
+
if (!decoded || typeof decoded !== "object") {
|
|
85
|
+
throw new ModelDeliveryError("Model grant must be an object");
|
|
86
|
+
}
|
|
87
|
+
const body = decoded;
|
|
88
|
+
const artifact = body.modelArtifact;
|
|
89
|
+
const identity = artifact && typeof artifact === "object"
|
|
90
|
+
? exactModelArtifactIdentity(sku, typeof artifact.version === "string" ? artifact.version : undefined, typeof artifact.manifestSha256 === "string" ? artifact.manifestSha256 : undefined)
|
|
91
|
+
: null;
|
|
92
|
+
if (!identity) {
|
|
93
|
+
throw new ModelDeliveryError("Model grant carries an invalid model artifact identity");
|
|
94
|
+
}
|
|
95
|
+
const accepted = body.acceptedArtifactVersions ?? [];
|
|
96
|
+
if (!Array.isArray(accepted)
|
|
97
|
+
|| !accepted.every((version) => typeof version === "string" && exactModelArtifactIdentity(sku, version, identity.manifestSha256) !== null)) {
|
|
98
|
+
throw new ModelDeliveryError("Model grant carries an unsafe accepted artifact version");
|
|
99
|
+
}
|
|
100
|
+
const origin = parseArtifactOrigin(artifactOrigin);
|
|
101
|
+
const release = grantedObject(body.release, "release");
|
|
102
|
+
const model = grantedObject(body.model, "model");
|
|
103
|
+
validateGrantedUrl(release.url, origin, sku, identity.version, RELEASE_FILE);
|
|
104
|
+
validateGrantedUrl(model.url, origin, sku, identity.version, MODEL_FILE);
|
|
105
|
+
return {
|
|
106
|
+
modelId: sku,
|
|
107
|
+
identity,
|
|
108
|
+
release,
|
|
109
|
+
model,
|
|
110
|
+
acceptedArtifactVersions: accepted,
|
|
111
|
+
json,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
export function grantAcceptsStamp(grant, stamped) {
|
|
115
|
+
return ((stamped.version === grant.identity.version
|
|
116
|
+
&& stamped.manifestSha256 === grant.identity.manifestSha256)
|
|
117
|
+
|| grant.acceptedArtifactVersions.includes(stamped.version));
|
|
118
|
+
}
|
|
119
|
+
function issuerErrorCode(body) {
|
|
120
|
+
try {
|
|
121
|
+
const decoded = JSON.parse(body);
|
|
122
|
+
return typeof decoded.error === "string" ? decoded.error : "";
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return "";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export async function requestModelDeliveryGrant(options, sku, capabilityQuery) {
|
|
129
|
+
const fetchFn = options.fetch ?? fetch;
|
|
130
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_INDEX_BASE_URL).replace(/\/+$/, "");
|
|
131
|
+
const url = `${baseUrl}/model-artifacts/download?${capabilityQuery}`;
|
|
132
|
+
const send = async (authHeader) => fetchFn(url, {
|
|
133
|
+
method: "GET",
|
|
134
|
+
headers: { Authorization: authHeader, "x-project-id": options.projectId },
|
|
135
|
+
credentials: "omit",
|
|
136
|
+
});
|
|
137
|
+
let response = await send(await options.auth.getAuthHeader());
|
|
138
|
+
if (response.status === 401) {
|
|
139
|
+
await options.auth.invalidate();
|
|
140
|
+
response = await send(await options.auth.getAuthHeader());
|
|
141
|
+
}
|
|
142
|
+
if (!response.ok) {
|
|
143
|
+
const body = await response.text().catch(() => "");
|
|
144
|
+
const code = issuerErrorCode(body);
|
|
145
|
+
const hint = code === "MODEL_ARTIFACT_UNAVAILABLE" || code === "MODEL_ARTIFACT_ENCRYPTED_UNAVAILABLE"
|
|
146
|
+
? "; no sealed model artifact is published for this model yet"
|
|
147
|
+
: "";
|
|
148
|
+
throw new ModelDeliveryError(`Issuer refused the sealed model grant for '${sku}' (HTTP ${response.status} ${code})${hint}; no plaintext fallback`, response.status, code);
|
|
149
|
+
}
|
|
150
|
+
return parseModelDeliveryGrant(await response.text(), sku, options.artifactOrigin);
|
|
151
|
+
}
|
|
152
|
+
export async function fetchGrantedBytes(fetchFn, object, maxBytes) {
|
|
153
|
+
const response = await fetchFn(object.url, {
|
|
154
|
+
method: "GET",
|
|
155
|
+
headers: { Authorization: `Bearer ${object.capability}` },
|
|
156
|
+
credentials: "omit",
|
|
157
|
+
});
|
|
158
|
+
if (!response.ok) {
|
|
159
|
+
throw new ModelDeliveryError(`Failed to fetch '${object.url}': ${response.status}`, response.status);
|
|
160
|
+
}
|
|
161
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
162
|
+
if (maxBytes !== undefined && bytes.byteLength > maxBytes) {
|
|
163
|
+
throw new ModelDeliveryError(`'${object.url}' exceeds ${maxBytes} bytes`);
|
|
164
|
+
}
|
|
165
|
+
return bytes;
|
|
166
|
+
}
|
|
167
|
+
function parseReleaseFiles(value) {
|
|
168
|
+
if (!Array.isArray(value)) {
|
|
169
|
+
throw new ModelDeliveryError("Model release manifest has an unsupported shape");
|
|
170
|
+
}
|
|
171
|
+
return value.map((entry) => {
|
|
172
|
+
if (!entry || typeof entry !== "object") {
|
|
173
|
+
throw new ModelDeliveryError("Model release manifest contains an invalid file entry");
|
|
174
|
+
}
|
|
175
|
+
const file = entry;
|
|
176
|
+
if (typeof file.relativePath !== "string"
|
|
177
|
+
|| !isSafeRelativePath(file.relativePath)
|
|
178
|
+
|| typeof file.sha256 !== "string"
|
|
179
|
+
|| !isCanonicalSha256(file.sha256)
|
|
180
|
+
|| typeof file.sizeBytes !== "number"
|
|
181
|
+
|| !Number.isSafeInteger(file.sizeBytes)
|
|
182
|
+
|| file.sizeBytes < 0) {
|
|
183
|
+
throw new ModelDeliveryError("Model release manifest contains an invalid file identity");
|
|
184
|
+
}
|
|
185
|
+
return { relativePath: file.relativePath, sha256: file.sha256, sizeBytes: file.sizeBytes };
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
export async function verifyReleaseManifest(releaseBytes, grant) {
|
|
189
|
+
const digest = await sha256Hex(releaseBytes);
|
|
190
|
+
if (digest !== grant.identity.manifestSha256) {
|
|
191
|
+
throw new ModelDeliveryError(`Model release manifest digest mismatch: expected ${grant.identity.manifestSha256}, got ${digest}`);
|
|
192
|
+
}
|
|
193
|
+
let decoded;
|
|
194
|
+
try {
|
|
195
|
+
decoded = JSON.parse(new TextDecoder().decode(releaseBytes));
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
throw new ModelDeliveryError(`Model release manifest is invalid JSON: ${String(error)}`);
|
|
199
|
+
}
|
|
200
|
+
if (!decoded || typeof decoded !== "object") {
|
|
201
|
+
throw new ModelDeliveryError("Model release manifest must be an object");
|
|
202
|
+
}
|
|
203
|
+
const manifest = decoded;
|
|
204
|
+
if (typeof manifest.schemaVersion !== "number"
|
|
205
|
+
|| !SUPPORTED_RELEASE_SCHEMA_VERSIONS.includes(manifest.schemaVersion)) {
|
|
206
|
+
throw new ModelDeliveryError(`Unsupported model release manifest schema ${String(manifest.schemaVersion)}`);
|
|
207
|
+
}
|
|
208
|
+
if (manifest.modelId !== grant.modelId || manifest.artifactVersion !== grant.identity.version) {
|
|
209
|
+
throw new ModelDeliveryError("Model release manifest does not match the server-owned artifact identity");
|
|
210
|
+
}
|
|
211
|
+
const files = parseReleaseFiles(manifest.files);
|
|
212
|
+
const byPath = new Map();
|
|
213
|
+
for (const file of files) {
|
|
214
|
+
if (file.relativePath !== MODEL_FILE) {
|
|
215
|
+
throw new ModelDeliveryError(`Model release manifest declares unexpected file '${file.relativePath}'`);
|
|
216
|
+
}
|
|
217
|
+
if (byPath.has(file.relativePath)) {
|
|
218
|
+
throw new ModelDeliveryError(`Model release manifest repeats '${file.relativePath}'`);
|
|
219
|
+
}
|
|
220
|
+
byPath.set(file.relativePath, file);
|
|
221
|
+
}
|
|
222
|
+
const record = byPath.get(MODEL_FILE);
|
|
223
|
+
if (!record) {
|
|
224
|
+
throw new ModelDeliveryError(`Model release manifest is missing '${MODEL_FILE}'`);
|
|
225
|
+
}
|
|
226
|
+
return record;
|
|
227
|
+
}
|
|
228
|
+
export async function verifyModelBytes(bytes, record) {
|
|
229
|
+
if (bytes.byteLength !== record.sizeBytes) {
|
|
230
|
+
throw new ModelDeliveryError(`Model file '${record.relativePath}' has an unexpected size`);
|
|
231
|
+
}
|
|
232
|
+
const digest = await sha256Hex(bytes);
|
|
233
|
+
if (digest !== record.sha256) {
|
|
234
|
+
throw new ModelDeliveryError(`Model file '${record.relativePath}' failed SHA-256 verification`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
export async function loadSealedModel(options, stamped) {
|
|
238
|
+
const sku = stamped.modelId;
|
|
239
|
+
const fetchFn = options.fetch ?? fetch;
|
|
240
|
+
const exchange = options.runtime.newKeyExchange();
|
|
241
|
+
let grant;
|
|
242
|
+
let keys;
|
|
243
|
+
let consumed = false;
|
|
244
|
+
try {
|
|
245
|
+
grant = await requestModelDeliveryGrant(options, sku, exchange.capabilityQuery(sku));
|
|
246
|
+
if (!grantAcceptsStamp(grant, stamped)) {
|
|
247
|
+
throw new ModelDeliveryError(`Index model artifact ${stamped.version} is not served by the issuer's grant ${grant.identity.version}`);
|
|
248
|
+
}
|
|
249
|
+
consumed = true;
|
|
250
|
+
try {
|
|
251
|
+
keys = exchange.unwrap(grant.json, sku, options.projectId);
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
throw new ModelDeliveryError(`Issuer grant for '${sku}' cannot be unwrapped: ${String(error)}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
if (!consumed)
|
|
259
|
+
exchange.free();
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const releaseBytes = await fetchGrantedBytes(fetchFn, grant.release, MAX_RELEASE_MANIFEST_BYTES);
|
|
263
|
+
const record = await verifyReleaseManifest(releaseBytes, grant);
|
|
264
|
+
const modelBytes = await fetchGrantedBytes(fetchFn, grant.model);
|
|
265
|
+
await verifyModelBytes(modelBytes, record);
|
|
266
|
+
const sealed = options.runtime.openSealedModel(modelBytes, keys, sku);
|
|
267
|
+
try {
|
|
268
|
+
const graph = sealed.takeGraph();
|
|
269
|
+
const tokenizer = sealed.takeTokenizer();
|
|
270
|
+
return { grant, graph, tokenizer };
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
sealed.free();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
keys.free();
|
|
278
|
+
}
|
|
279
|
+
}
|