openany-cli-dev 0.0.0-stage → 0.1.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.
- package/README.md +472 -2
- package/bin/openany.js +3 -0
- package/package.json +27 -4
- package/skills/openany/SKILL.md +353 -0
- package/skills/openany/SKILL.zh-CN.md +496 -0
- package/skills/openany-provider/SKILL.md +26 -0
- package/skills/openany-provider/SKILL.zh-CN.md +26 -0
- package/skills/openany-provider/references/apis.md +60 -0
- package/skills/openany-provider/references/apis.zh-CN.md +55 -0
- package/skills/openany-provider/references/application.md +49 -0
- package/skills/openany-provider/references/application.zh-CN.md +51 -0
- package/skills/openany-provider/references/auth.md +3 -0
- package/skills/openany-provider/references/auth.zh-CN.md +3 -0
- package/skills/openany-provider/references/connections.md +36 -0
- package/skills/openany-provider/references/connections.zh-CN.md +36 -0
- package/skills/openany-provider/references/imports.md +57 -0
- package/skills/openany-provider/references/imports.zh-CN.md +57 -0
- package/skills/openany-provider/references/listing.md +29 -0
- package/skills/openany-provider/references/listing.zh-CN.md +11 -0
- package/skills/openany-provider/references/login.md +57 -0
- package/skills/openany-provider/references/login.zh-CN.md +57 -0
- package/skills/openany-provider/references/model-import.md +11 -0
- package/skills/openany-provider/references/model-import.zh-CN.md +11 -0
- package/skills/openany-provider/references/models.md +107 -0
- package/skills/openany-provider/references/models.zh-CN.md +68 -0
- package/skills/openany-provider/references/publishing.md +40 -0
- package/skills/openany-provider/references/publishing.zh-CN.md +40 -0
- package/skills/openany-provider/references/reviews.md +22 -0
- package/skills/openany-provider/references/reviews.zh-CN.md +20 -0
- package/skills/openany-provider/templates/api-metadata.json +27 -0
- package/skills/openany-provider/templates/bindings.json +1 -0
- package/skills/openany-provider/templates/models-v2.json +545 -0
- package/skills/openany-provider/templates/models.json +10 -0
- package/skills/openany-provider/templates/provider-agent-api-template.json +697 -0
- package/skills/openany-provider/templates/seller-agent-api-import-template.json +822 -0
- package/skills/openany-provider/templates/seller-registration.json +26 -0
- package/src/auth-recovery.js +179 -0
- package/src/auth.js +1001 -0
- package/src/catalog.js +306 -0
- package/src/cli.js +605 -0
- package/src/config.js +260 -0
- package/src/errors.js +53 -0
- package/src/http.js +238 -0
- package/src/model-curl.js +359 -0
- package/src/model-materials.js +58 -0
- package/src/model-request.js +402 -0
- package/src/model-validation.js +56 -0
- package/src/models.js +188 -0
- package/src/native/config-acl.ps1 +34 -0
- package/src/native/connection-macos.js +109 -0
- package/src/native/connection-windows.ps1 +98 -0
- package/src/native/setup-macos.js +72 -0
- package/src/native/setup-windows.ps1 +83 -0
- package/src/native-prompt.js +85 -0
- package/src/payment-signing.js +362 -0
- package/src/prompt.js +69 -0
- package/src/provider-api-import-v2.js +72 -0
- package/src/provider-apis.js +3 -0
- package/src/provider-client.js +153 -0
- package/src/provider-connections.js +152 -0
- package/src/provider-import-format.js +289 -0
- package/src/provider-imports.js +402 -0
- package/src/provider-json.js +49 -0
- package/src/provider-model-import-v2.js +61 -0
- package/src/provider-models.js +253 -0
- package/src/provider-profile.js +65 -0
- package/src/provider-reviews.js +61 -0
- package/src/provider-state.js +176 -0
- package/src/provider.js +75 -0
- package/src/setup.js +201 -0
- package/src/tasks.js +53 -0
- package/src/topups.js +845 -0
- package/src/vendor/provider-apply/market-taxonomy.mjs +22 -0
- package/src/vendor/provider-apply/provenance.json +8 -0
- package/src/vendor/provider-apply/registration.mjs +151 -0
- package/src/vendor/provider-import/api-categories.json +29 -0
- package/src/vendor/provider-import/api-fields.json +33 -0
- package/src/vendor/provider-import/model-fields.json +44 -0
- package/src/wallet.js +213 -0
- package/src/windows-permissions.js +22 -0
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
import { apiImportVersion, validateApiImportCategories } from "./provider-api-import-v2.js";
|
|
2
|
+
import { modelImportVersion } from "./provider-model-import-v2.js";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { CLIError, requireValue } from "./errors.js";
|
|
5
|
+
import {
|
|
6
|
+
parseImport,
|
|
7
|
+
applyBindings,
|
|
8
|
+
manifest,
|
|
9
|
+
} from "./provider-import-format.js";
|
|
10
|
+
import { digest, uncertain, uuid } from "./provider-state.js";
|
|
11
|
+
import { asyncConfigurationFields, checkConfiguration, hasArticleContent, hasSellerDescription, isResourceApi, resourceContentFields } from "./provider-models.js";
|
|
12
|
+
import { readProviderJSON } from "./provider-json.js";
|
|
13
|
+
export function batchResult(batch) {
|
|
14
|
+
const summary = {
|
|
15
|
+
ready: 0,
|
|
16
|
+
waiting_connection: 0,
|
|
17
|
+
needs_information: 0,
|
|
18
|
+
created: 0,
|
|
19
|
+
conflict: 0,
|
|
20
|
+
failed: 0,
|
|
21
|
+
unknown: 0,
|
|
22
|
+
};
|
|
23
|
+
for (const item of batch.items)
|
|
24
|
+
summary[item.stage] = (summary[item.stage] || 0) + 1;
|
|
25
|
+
return {
|
|
26
|
+
id: batch.id,
|
|
27
|
+
type: batch.type,
|
|
28
|
+
applicationId: batch.application,
|
|
29
|
+
summary,
|
|
30
|
+
items: batch.items.map(
|
|
31
|
+
({
|
|
32
|
+
itemId,
|
|
33
|
+
source,
|
|
34
|
+
stage,
|
|
35
|
+
families,
|
|
36
|
+
missingFields,
|
|
37
|
+
errorCode,
|
|
38
|
+
resourceId,
|
|
39
|
+
operation,
|
|
40
|
+
verifications,
|
|
41
|
+
reviews,
|
|
42
|
+
}) => ({
|
|
43
|
+
itemId,
|
|
44
|
+
source,
|
|
45
|
+
stage,
|
|
46
|
+
...(families && { families }),
|
|
47
|
+
missingFields,
|
|
48
|
+
errorCode,
|
|
49
|
+
resourceId,
|
|
50
|
+
operation,
|
|
51
|
+
verifications,
|
|
52
|
+
reviews,
|
|
53
|
+
}),
|
|
54
|
+
),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function missingModelCurl(item, type) {
|
|
58
|
+
const example = item.configuration?.price?.curlExample;
|
|
59
|
+
return type === "model" && (typeof example !== "string" || !example.trim());
|
|
60
|
+
}
|
|
61
|
+
async function previewFamilies(item, client) {
|
|
62
|
+
item.families = [];
|
|
63
|
+
const byModel = new Map();
|
|
64
|
+
for (const [index, route] of item.configuration.routes.entries()) {
|
|
65
|
+
const publicModel = route.publicModel?.trim();
|
|
66
|
+
if (!publicModel && route.familyId == null) continue;
|
|
67
|
+
if (!publicModel) throw new CLIError("IMPORT_FORMAT", "A family selection requires a public model ID");
|
|
68
|
+
let family = byModel.get(publicModel);
|
|
69
|
+
if (!family) {
|
|
70
|
+
const options = await client.request("/model-families", { query: { publicModel } });
|
|
71
|
+
if (!Array.isArray(options) || options.some(f => !f || typeof f.id !== "string" || typeof f.name !== "string" || typeof f.assigned !== "boolean"))
|
|
72
|
+
throw new CLIError("INVALID_RESPONSE", "Model family options are unavailable");
|
|
73
|
+
const assigned = options.filter(f => f.assigned);
|
|
74
|
+
family = { publicModel, routeIndices: [], readOnly: assigned.length > 0, options: assigned.length ? assigned : options };
|
|
75
|
+
byModel.set(publicModel, family);
|
|
76
|
+
item.families.push(family);
|
|
77
|
+
}
|
|
78
|
+
family.routeIndices.push(index);
|
|
79
|
+
if (route.familyId == null) continue;
|
|
80
|
+
if (family.readOnly) throw new CLIError("MODEL_FAMILY_LOCKED", "Public model already belongs to a family");
|
|
81
|
+
if (!family.options.some(f => f.id === route.familyId)) throw new CLIError("MODEL_FAMILY_UNAVAILABLE", "Select an existing family");
|
|
82
|
+
if (family.selectedId) throw new CLIError("DUPLICATE_FAMILY_SELECTION", "Choose a family only once per public model");
|
|
83
|
+
family.selectedId = route.familyId;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function apiImportRequest(item) {
|
|
87
|
+
const { upstreamKeyId, ...fields } = item.configuration;
|
|
88
|
+
return {
|
|
89
|
+
upstreamKeyId,
|
|
90
|
+
expectedUpstreamRevision: item.connectionRevision,
|
|
91
|
+
file: { schemaVersion: "provider-agent-api-v1", apis: [fields] },
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function importedApiResult(result) {
|
|
96
|
+
const item = result?.items?.[0];
|
|
97
|
+
if (result?.status !== "completed" || !item || item.status === "unknown")
|
|
98
|
+
throw new CLIError("INVALID_RESPONSE", "API import has no final item result");
|
|
99
|
+
if (item.status === "created" && typeof item.apiId === "string" && item.apiId)
|
|
100
|
+
return { id: item.apiId };
|
|
101
|
+
if (item.status === "created")
|
|
102
|
+
throw new CLIError("INVALID_RESPONSE", "API import has no resource ID");
|
|
103
|
+
if (item.status === "skipped_duplicate")
|
|
104
|
+
throw new CLIError("ROUTE_CONFLICT", "The API route already exists", { status: 409 });
|
|
105
|
+
throw new CLIError(item.issues?.[0]?.code || "IMPORT_FAILED", "API import could not create the draft");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function prepare(item, type, client) {
|
|
109
|
+
if (item.errorCode?.startsWith("UNSUPPORTED_")) return item;
|
|
110
|
+
const c = item.configuration;
|
|
111
|
+
item.missingFields = [];
|
|
112
|
+
delete item.errorCode;
|
|
113
|
+
const refs = type === "model" ? c.routes : [c];
|
|
114
|
+
try {
|
|
115
|
+
if (type === "model") {
|
|
116
|
+
await previewFamilies(item, client);
|
|
117
|
+
if (item.source.schemaVersion === modelImportVersion) {
|
|
118
|
+
if (!hasSellerDescription(c.price.description)) item.missingFields.push("price.description");
|
|
119
|
+
for (const family of item.families)
|
|
120
|
+
if (!family.readOnly && !family.selectedId)
|
|
121
|
+
item.missingFields.push(`routes[${family.routeIndices[0]}].familyId`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (type === "api") {
|
|
125
|
+
if (!hasSellerDescription(c.description)) item.missingFields.push("description");
|
|
126
|
+
item.missingFields.push(...asyncConfigurationFields(c));
|
|
127
|
+
if (isResourceApi(c.catalogType))
|
|
128
|
+
for (const key of resourceContentFields)
|
|
129
|
+
if (!hasArticleContent(c[key])) item.missingFields.push(key);
|
|
130
|
+
}
|
|
131
|
+
if (missingModelCurl(item, type)) item.missingFields.push("price.curlExample");
|
|
132
|
+
if (refs.some((r) => !r.upstreamKeyId)) {
|
|
133
|
+
item.stage = "waiting_connection";
|
|
134
|
+
item.missingFields.push(...refs.flatMap((r, i) =>
|
|
135
|
+
r.upstreamKeyId
|
|
136
|
+
? []
|
|
137
|
+
: [type === "model" ? `routes[${i}].upstreamKeyId` : "upstreamKeyId"],
|
|
138
|
+
));
|
|
139
|
+
return item;
|
|
140
|
+
}
|
|
141
|
+
if (item.missingFields.length) {
|
|
142
|
+
item.stage = "needs_information";
|
|
143
|
+
return item;
|
|
144
|
+
}
|
|
145
|
+
for (const route of refs) {
|
|
146
|
+
const connection = await client.request(
|
|
147
|
+
"/connections/" + uuid(route.upstreamKeyId),
|
|
148
|
+
);
|
|
149
|
+
if (
|
|
150
|
+
connection.status !== "active" ||
|
|
151
|
+
!Number.isInteger(connection.revision)
|
|
152
|
+
)
|
|
153
|
+
throw new CLIError("CONNECTION_NOT_READY", "Connection must be active");
|
|
154
|
+
if (
|
|
155
|
+
type === "api" &&
|
|
156
|
+
item.source.baseUrl &&
|
|
157
|
+
new URL(connection.baseUrl).origin !==
|
|
158
|
+
new URL(item.source.baseUrl).origin
|
|
159
|
+
)
|
|
160
|
+
throw new CLIError(
|
|
161
|
+
"CONNECTION_SOURCE_MISMATCH",
|
|
162
|
+
"Connection origin differs from the OpenAPI server",
|
|
163
|
+
);
|
|
164
|
+
if (
|
|
165
|
+
type === "api" &&
|
|
166
|
+
item.source.authRequirement === "authenticated" &&
|
|
167
|
+
connection.authType === "none"
|
|
168
|
+
)
|
|
169
|
+
throw new CLIError(
|
|
170
|
+
"AUTH_TYPE_MISMATCH",
|
|
171
|
+
"Authenticated operation requires an authenticated connection",
|
|
172
|
+
);
|
|
173
|
+
if (type === "model")
|
|
174
|
+
route.expectedUpstreamRevision = connection.revision;
|
|
175
|
+
else item.connectionRevision = connection.revision;
|
|
176
|
+
}
|
|
177
|
+
if (type === "api") {
|
|
178
|
+
for (const key of ["requestContentType", "config"])
|
|
179
|
+
if (!c[key]) item.missingFields.push(key);
|
|
180
|
+
for (const key of ["inputs", "mappings", "billing", "charge_condition"])
|
|
181
|
+
if (!c.config || !Object.hasOwn(c.config, key))
|
|
182
|
+
item.missingFields.push("config." + key);
|
|
183
|
+
if (item.missingFields.length) {
|
|
184
|
+
item.stage = "needs_information";
|
|
185
|
+
return item;
|
|
186
|
+
}
|
|
187
|
+
const preview = await client.request("/agent-api-imports/preview", {
|
|
188
|
+
method: "POST",
|
|
189
|
+
json: apiImportRequest(item),
|
|
190
|
+
});
|
|
191
|
+
if (preview.items?.[0]?.status !== "ready") {
|
|
192
|
+
item.stage =
|
|
193
|
+
preview.items?.[0]?.status === "skipped_duplicate"
|
|
194
|
+
? "conflict"
|
|
195
|
+
: "failed";
|
|
196
|
+
item.errorCode =
|
|
197
|
+
preview.items?.[0]?.issues?.[0]?.code || "IMPORT_VALIDATION_FAILED";
|
|
198
|
+
return item;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
item.stage = "ready";
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (
|
|
204
|
+
["SESSION_CHANGED", "UNAUTHORIZED", "FORBIDDEN"].includes(error.code) ||
|
|
205
|
+
[401, 403].includes(error.details?.status)
|
|
206
|
+
)
|
|
207
|
+
throw error;
|
|
208
|
+
item.stage = error.code === "MODEL_FAMILY_LOCKED" ? "conflict" : "failed";
|
|
209
|
+
item.errorCode = error.code || "PREVIEW_FAILED";
|
|
210
|
+
}
|
|
211
|
+
return item;
|
|
212
|
+
}
|
|
213
|
+
export async function runImports(action, client, ctx) {
|
|
214
|
+
const o = ctx.options;
|
|
215
|
+
let batch;
|
|
216
|
+
if (action === "preview") {
|
|
217
|
+
requireValue(o.type, "--type");
|
|
218
|
+
await client.capabilities(o.type);
|
|
219
|
+
if (o.type === "model") await client.request("/schemas/model-import");
|
|
220
|
+
const document = await ctx.input();
|
|
221
|
+
const metadata = o["metadata-file"]
|
|
222
|
+
? await readProviderJSON(o["metadata-file"])
|
|
223
|
+
: undefined;
|
|
224
|
+
let items = parseImport(o.type, document, metadata);
|
|
225
|
+
if (o["bindings-file"])
|
|
226
|
+
items = applyBindings(items, await readProviderJSON(o["bindings-file"]), o.type);
|
|
227
|
+
batch = {
|
|
228
|
+
id: randomUUID(),
|
|
229
|
+
userId: client.identity.userId,
|
|
230
|
+
application: client.application,
|
|
231
|
+
type: o.type,
|
|
232
|
+
sourceDigest: digest(document),
|
|
233
|
+
items,
|
|
234
|
+
};
|
|
235
|
+
for (const item of items) await prepare(item, batch.type, client);
|
|
236
|
+
} else {
|
|
237
|
+
uuid(requireValue(o.batch, "--batch"), "batch");
|
|
238
|
+
batch = structuredClone(
|
|
239
|
+
(await ctx.store.read()).provider?.batches?.[o.batch],
|
|
240
|
+
);
|
|
241
|
+
if (!batch)
|
|
242
|
+
throw new CLIError("BATCH_NOT_FOUND", "Local import batch was not found");
|
|
243
|
+
if (
|
|
244
|
+
batch.userId !== client.identity.userId ||
|
|
245
|
+
batch.application !== client.application
|
|
246
|
+
)
|
|
247
|
+
throw new CLIError(
|
|
248
|
+
"SESSION_CHANGED",
|
|
249
|
+
"Import belongs to another account or supplier",
|
|
250
|
+
);
|
|
251
|
+
if (action === "status") return batchResult(batch);
|
|
252
|
+
if (!["run", "resume"].includes(action))
|
|
253
|
+
throw new CLIError(
|
|
254
|
+
"UNKNOWN_COMMAND",
|
|
255
|
+
"Imports support preview|run|status|resume",
|
|
256
|
+
);
|
|
257
|
+
await client.capabilities(batch.type);
|
|
258
|
+
if (o["bindings-file"] || o["metadata-file"]) {
|
|
259
|
+
const changed = structuredClone(batch.items);
|
|
260
|
+
if (o["metadata-file"])
|
|
261
|
+
for (const entry of manifest(
|
|
262
|
+
await readProviderJSON(o["metadata-file"]),
|
|
263
|
+
"Metadata",
|
|
264
|
+
batch.type,
|
|
265
|
+
)) {
|
|
266
|
+
if (
|
|
267
|
+
!entry.configuration ||
|
|
268
|
+
typeof entry.configuration !== "object" ||
|
|
269
|
+
Array.isArray(entry.configuration)
|
|
270
|
+
)
|
|
271
|
+
throw new CLIError(
|
|
272
|
+
"IMPORT_FORMAT",
|
|
273
|
+
"Metadata requires configuration",
|
|
274
|
+
);
|
|
275
|
+
const item = changed.find((x) => x.itemId === entry.itemId);
|
|
276
|
+
if (!item)
|
|
277
|
+
throw new CLIError("IMPORT_FORMAT", "Unknown metadata item");
|
|
278
|
+
if (["created", "unknown"].includes(item.stage))
|
|
279
|
+
throw new CLIError(
|
|
280
|
+
"ITEM_READONLY",
|
|
281
|
+
"Recover unknown writes before changing input",
|
|
282
|
+
);
|
|
283
|
+
if (
|
|
284
|
+
(entry.configuration.method &&
|
|
285
|
+
entry.configuration.method !== item.source.method) ||
|
|
286
|
+
(entry.configuration.pathTemplate &&
|
|
287
|
+
entry.configuration.pathTemplate !== item.source.path)
|
|
288
|
+
)
|
|
289
|
+
throw new CLIError(
|
|
290
|
+
"SOURCE_MISMATCH",
|
|
291
|
+
"Source method/path cannot change",
|
|
292
|
+
);
|
|
293
|
+
item.configuration = {
|
|
294
|
+
...item.configuration,
|
|
295
|
+
...entry.configuration,
|
|
296
|
+
};
|
|
297
|
+
if (item.source.schemaVersion === apiImportVersion)
|
|
298
|
+
validateApiImportCategories(item.configuration.categories, item.itemId);
|
|
299
|
+
}
|
|
300
|
+
const bound = o["bindings-file"]
|
|
301
|
+
? applyBindings(changed, await readProviderJSON(o["bindings-file"]), batch.type)
|
|
302
|
+
: changed;
|
|
303
|
+
for (let i = 0; i < bound.length; i++)
|
|
304
|
+
if (
|
|
305
|
+
["created", "unknown"].includes(batch.items[i].stage) &&
|
|
306
|
+
digest(bound[i].configuration) !==
|
|
307
|
+
digest(batch.items[i].configuration)
|
|
308
|
+
)
|
|
309
|
+
throw new CLIError(
|
|
310
|
+
"ITEM_READONLY",
|
|
311
|
+
"Completed or unknown items cannot change",
|
|
312
|
+
);
|
|
313
|
+
for (let i = 0; i < bound.length; i++) {
|
|
314
|
+
if (bound[i].configuration) checkConfiguration(bound[i].configuration);
|
|
315
|
+
if (
|
|
316
|
+
digest(bound[i].configuration) !==
|
|
317
|
+
digest(batch.items[i].configuration)
|
|
318
|
+
)
|
|
319
|
+
delete bound[i].operation;
|
|
320
|
+
}
|
|
321
|
+
batch.items = bound;
|
|
322
|
+
}
|
|
323
|
+
for (const item of batch.items) {
|
|
324
|
+
if (item.stage === "created") continue;
|
|
325
|
+
// Older batches may have an unresolved write without a cURL example.
|
|
326
|
+
// Preserve its unknown outcome without sending the invalid payload again.
|
|
327
|
+
if (item.stage === "unknown" && missingModelCurl(item, batch.type)) {
|
|
328
|
+
item.missingFields = ["price.curlExample"];
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (item.stage !== "unknown") {
|
|
332
|
+
// Older local batches stored the overview in the price object.
|
|
333
|
+
if (batch.type === "model" && item.configuration?.price && Object.hasOwn(item.configuration.price, "overviewHtml")) {
|
|
334
|
+
const { overviewHtml, ...price } = item.configuration.price;
|
|
335
|
+
item.configuration = { overviewHtml, ...item.configuration, price };
|
|
336
|
+
}
|
|
337
|
+
await prepare(item, batch.type, client);
|
|
338
|
+
}
|
|
339
|
+
if (!["ready", "unknown"].includes(item.stage)) continue;
|
|
340
|
+
const websiteApi = batch.type === "api" && item.source.schemaVersion === apiImportVersion;
|
|
341
|
+
const payload = websiteApi ? apiImportRequest(item) : item.configuration;
|
|
342
|
+
const writeDigest = digest(payload);
|
|
343
|
+
if (item.stage !== "unknown" && item.operation && item.writeDigest !== writeDigest)
|
|
344
|
+
delete item.operation;
|
|
345
|
+
item.writeDigest = writeDigest;
|
|
346
|
+
item.operation ??= `import-${batch.id}-${digest(item.itemId).slice(0, 12)}-${writeDigest.slice(0, 16)}`;
|
|
347
|
+
// Persist the exact write and key before network I/O. An unknown result is
|
|
348
|
+
// recovered using that snapshot, never by looking up a resource by name.
|
|
349
|
+
item.stage = "unknown";
|
|
350
|
+
await save(batch, client, ctx);
|
|
351
|
+
try {
|
|
352
|
+
const result = await client.write(
|
|
353
|
+
websiteApi ? "/agent-api-imports" : batch.type === "model" ? "/models" : "/agent-apis",
|
|
354
|
+
"POST",
|
|
355
|
+
payload,
|
|
356
|
+
item.operation,
|
|
357
|
+
{ recover: action === "resume", ...(websiteApi && { selectResult: importedApiResult }) },
|
|
358
|
+
);
|
|
359
|
+
item.resourceId = result.id || result.price?.id;
|
|
360
|
+
if (!item.resourceId)
|
|
361
|
+
throw new CLIError(
|
|
362
|
+
"INVALID_RESPONSE",
|
|
363
|
+
"Create response has no resource ID",
|
|
364
|
+
);
|
|
365
|
+
for (const family of item.families ?? []) {
|
|
366
|
+
if (!family.selectedId) continue;
|
|
367
|
+
family.readOnly = true;
|
|
368
|
+
family.options = family.options.filter(f => f.id === family.selectedId).map(f => ({ ...f, assigned: true }));
|
|
369
|
+
}
|
|
370
|
+
item.stage = "created";
|
|
371
|
+
delete item.errorCode;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (
|
|
374
|
+
["SESSION_CHANGED", "UNAUTHORIZED", "FORBIDDEN"].includes(
|
|
375
|
+
error.code,
|
|
376
|
+
) ||
|
|
377
|
+
[401, 403].includes(error.details?.status)
|
|
378
|
+
)
|
|
379
|
+
throw error;
|
|
380
|
+
item.stage = uncertain(error)
|
|
381
|
+
? "unknown"
|
|
382
|
+
: Number(error.details?.status) === 409
|
|
383
|
+
? "conflict"
|
|
384
|
+
: "failed";
|
|
385
|
+
item.errorCode = error.code || "CREATE_FAILED";
|
|
386
|
+
}
|
|
387
|
+
await save(batch, client, ctx);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
await save(batch, client, ctx);
|
|
391
|
+
return batchResult(batch);
|
|
392
|
+
}
|
|
393
|
+
async function save(batch, client, ctx) {
|
|
394
|
+
await client.credential();
|
|
395
|
+
return ctx.store.update((s) => {
|
|
396
|
+
if (s.sessions.email?.userId !== batch.userId)
|
|
397
|
+
throw new CLIError("SESSION_CHANGED", "Account changed");
|
|
398
|
+
s.provider ??= { operations: {}, batches: {} };
|
|
399
|
+
s.provider.batches ??= {};
|
|
400
|
+
s.provider.batches[batch.id] = batch;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readFile, lstat } from "node:fs/promises";
|
|
2
|
+
import { CLIError } from "./errors.js";
|
|
3
|
+
function decimal(s) {
|
|
4
|
+
let [mantissa, exp = "0"] = s.toLowerCase().split("e");
|
|
5
|
+
let sign = "";
|
|
6
|
+
if (mantissa.startsWith("-")) {
|
|
7
|
+
sign = "-";
|
|
8
|
+
mantissa = mantissa.slice(1);
|
|
9
|
+
}
|
|
10
|
+
const [whole, fraction = ""] = mantissa.split(".");
|
|
11
|
+
let digits = (whole + fraction).replace(/^0+/, "");
|
|
12
|
+
let exponent = Number(exp) - fraction.length;
|
|
13
|
+
while (digits.endsWith("0")) {
|
|
14
|
+
digits = digits.slice(0, -1);
|
|
15
|
+
exponent++;
|
|
16
|
+
}
|
|
17
|
+
return digits ? `${sign}${digits}e${exponent}` : "0";
|
|
18
|
+
}
|
|
19
|
+
export function parseProviderJSON(text) {
|
|
20
|
+
if (Buffer.byteLength(text) > 8 * 1024 * 1024)
|
|
21
|
+
throw new CLIError("IMPORT_LIMIT", "JSON file exceeds 8 MiB");
|
|
22
|
+
// Refuse numeric rounding before parsing rather than silently changing an API
|
|
23
|
+
// condition or fixed upstream request. Monetary amounts use decimal strings.
|
|
24
|
+
for (const match of text.matchAll(
|
|
25
|
+
/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g,
|
|
26
|
+
))
|
|
27
|
+
if (!match[0].startsWith('"')) {
|
|
28
|
+
const number = Number(match[0]);
|
|
29
|
+
if (
|
|
30
|
+
!Number.isFinite(number) ||
|
|
31
|
+
decimal(match[0]) !== decimal(String(number))
|
|
32
|
+
)
|
|
33
|
+
throw new CLIError(
|
|
34
|
+
"NUMBER_PRECISION",
|
|
35
|
+
"JSON number cannot be represented exactly; use a supported string field or revise the value",
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(text);
|
|
40
|
+
} catch {
|
|
41
|
+
throw new CLIError("INVALID_INPUT", "Input is not valid JSON");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function readProviderJSON(path) {
|
|
45
|
+
const stat = await lstat(path);
|
|
46
|
+
if (!stat.isFile() || stat.size > 8 * 1024 * 1024)
|
|
47
|
+
throw new CLIError("IMPORT_FORMAT", "Use a regular JSON file up to 8 MiB");
|
|
48
|
+
return parseProviderJSON(await readFile(path, "utf8"));
|
|
49
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { CLIError } from "./errors.js";
|
|
3
|
+
const fields = JSON.parse(readFileSync(new URL("./vendor/provider-import/model-fields.json", import.meta.url), "utf8"));
|
|
4
|
+
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
5
|
+
function rename(value, names, path) {
|
|
6
|
+
if (!object(value)) throw new CLIError("IMPORT_FORMAT", `${path} must be an object`);
|
|
7
|
+
const result = { ...value };
|
|
8
|
+
for (const [external, internal] of Object.entries(names)) {
|
|
9
|
+
if (Object.hasOwn(value, internal))
|
|
10
|
+
throw new CLIError("IMPORT_FORMAT", `${path}: use ${external} instead of ${internal}`);
|
|
11
|
+
if (Object.hasOwn(value, external)) {
|
|
12
|
+
result[internal] = value[external];
|
|
13
|
+
delete result[external];
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
18
|
+
// Normalize the website's editable template into the existing draft pipeline.
|
|
19
|
+
// Pricing strings are copied verbatim; connection/family choices remain separate.
|
|
20
|
+
export const modelImportVersion = "seller-model-config-v2";
|
|
21
|
+
|
|
22
|
+
export function modelImportV2(document) {
|
|
23
|
+
if (!object(document) || document.schemaVersion !== modelImportVersion ||
|
|
24
|
+
!Array.isArray(document.models) || !document.models.length || document.models.length > 100 ||
|
|
25
|
+
Object.keys(document).some(k => !["schemaVersion", "description", "models", "templateGuide", "fieldGuide"].includes(k)) ||
|
|
26
|
+
(Object.hasOwn(document, "description") && typeof document.description !== "string") ||
|
|
27
|
+
["templateGuide", "fieldGuide"].some(k => Object.hasOwn(document, k) && !object(document[k])))
|
|
28
|
+
throw new CLIError("IMPORT_FORMAT", "Use seller-model-config-v2 with 1–100 models and optional guide objects");
|
|
29
|
+
if (Buffer.byteLength(JSON.stringify(document)) > 2 * 1024 * 1024)
|
|
30
|
+
throw new CLIError("IMPORT_FORMAT", "Website model templates must not exceed 2 MiB");
|
|
31
|
+
const seenModels = new Set(), seenRoutes = new Set();
|
|
32
|
+
return { schemaVersion: 1, items: document.models.map((entry, index) => {
|
|
33
|
+
const path = `models[${index}]`;
|
|
34
|
+
const { overviewHtml, ...price } = rename(entry, fields.model, path);
|
|
35
|
+
const quantity = price.billingUnit === "token" ? "1000000" :
|
|
36
|
+
["request", "image", "second", "minute"].includes(price.billingUnit) ? "1" : null;
|
|
37
|
+
if (!quantity || price.priceUnitQuantity !== quantity)
|
|
38
|
+
throw new CLIError("IMPORT_FORMAT", `${path}.priceUnitQuantity: token requires string 1000000; request/image/second/minute require string 1`);
|
|
39
|
+
delete price.priceUnitQuantity;
|
|
40
|
+
for (const [key, group] of [["upstreamPath", "endpoint"], ["timePricingRules", "schedule"], ["pricingTiers", "prices"]]) {
|
|
41
|
+
if (!Object.hasOwn(price, key)) continue;
|
|
42
|
+
const sourceKey = key === "upstreamPath" ? "endpoints" : key;
|
|
43
|
+
if (!Array.isArray(price[key])) throw new CLIError("IMPORT_FORMAT", `${path}.${sourceKey} must be an array`);
|
|
44
|
+
price[key] = price[key].map((value, i) => rename(value, fields[group], `${path}.${sourceKey}[${i}]`));
|
|
45
|
+
}
|
|
46
|
+
const publicModel = Object.hasOwn(price, "publicModel") ? price.publicModel : price.model;
|
|
47
|
+
if (typeof price.model !== "string" || !price.model.trim() || typeof publicModel !== "string" || !publicModel.trim())
|
|
48
|
+
throw new CLIError("IMPORT_FORMAT", `${path} requires nonempty modelId and publicModelId when supplied`);
|
|
49
|
+
for (const [seen, id] of [[seenModels, price.model], [seenRoutes, publicModel]]) {
|
|
50
|
+
const normalized = id.trim().toLowerCase();
|
|
51
|
+
if (seen.has(normalized)) throw new CLIError("DUPLICATE_ITEM", `Duplicate model identity in ${path}`);
|
|
52
|
+
seen.add(normalized);
|
|
53
|
+
}
|
|
54
|
+
const route = { publicModel: publicModel.trim(), upstreamKeyId: null, status: "active",
|
|
55
|
+
matchRules: price.matchRules ?? {}, operations: price.operations ?? [] };
|
|
56
|
+
delete price.publicModel;
|
|
57
|
+
delete price.matchRules;
|
|
58
|
+
delete price.operations;
|
|
59
|
+
return { itemId: `model-${index + 1}`, configuration: { price, routes: [route], ...(overviewHtml !== undefined && { overviewHtml }) } };
|
|
60
|
+
}) };
|
|
61
|
+
}
|