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.
Files changed (80) hide show
  1. package/README.md +472 -2
  2. package/bin/openany.js +3 -0
  3. package/package.json +27 -4
  4. package/skills/openany/SKILL.md +353 -0
  5. package/skills/openany/SKILL.zh-CN.md +496 -0
  6. package/skills/openany-provider/SKILL.md +26 -0
  7. package/skills/openany-provider/SKILL.zh-CN.md +26 -0
  8. package/skills/openany-provider/references/apis.md +60 -0
  9. package/skills/openany-provider/references/apis.zh-CN.md +55 -0
  10. package/skills/openany-provider/references/application.md +49 -0
  11. package/skills/openany-provider/references/application.zh-CN.md +51 -0
  12. package/skills/openany-provider/references/auth.md +3 -0
  13. package/skills/openany-provider/references/auth.zh-CN.md +3 -0
  14. package/skills/openany-provider/references/connections.md +36 -0
  15. package/skills/openany-provider/references/connections.zh-CN.md +36 -0
  16. package/skills/openany-provider/references/imports.md +57 -0
  17. package/skills/openany-provider/references/imports.zh-CN.md +57 -0
  18. package/skills/openany-provider/references/listing.md +29 -0
  19. package/skills/openany-provider/references/listing.zh-CN.md +11 -0
  20. package/skills/openany-provider/references/login.md +57 -0
  21. package/skills/openany-provider/references/login.zh-CN.md +57 -0
  22. package/skills/openany-provider/references/model-import.md +11 -0
  23. package/skills/openany-provider/references/model-import.zh-CN.md +11 -0
  24. package/skills/openany-provider/references/models.md +107 -0
  25. package/skills/openany-provider/references/models.zh-CN.md +68 -0
  26. package/skills/openany-provider/references/publishing.md +40 -0
  27. package/skills/openany-provider/references/publishing.zh-CN.md +40 -0
  28. package/skills/openany-provider/references/reviews.md +22 -0
  29. package/skills/openany-provider/references/reviews.zh-CN.md +20 -0
  30. package/skills/openany-provider/templates/api-metadata.json +27 -0
  31. package/skills/openany-provider/templates/bindings.json +1 -0
  32. package/skills/openany-provider/templates/models-v2.json +545 -0
  33. package/skills/openany-provider/templates/models.json +10 -0
  34. package/skills/openany-provider/templates/provider-agent-api-template.json +697 -0
  35. package/skills/openany-provider/templates/seller-agent-api-import-template.json +822 -0
  36. package/skills/openany-provider/templates/seller-registration.json +26 -0
  37. package/src/auth-recovery.js +179 -0
  38. package/src/auth.js +1001 -0
  39. package/src/catalog.js +306 -0
  40. package/src/cli.js +605 -0
  41. package/src/config.js +260 -0
  42. package/src/errors.js +53 -0
  43. package/src/http.js +238 -0
  44. package/src/model-curl.js +359 -0
  45. package/src/model-materials.js +58 -0
  46. package/src/model-request.js +402 -0
  47. package/src/model-validation.js +56 -0
  48. package/src/models.js +188 -0
  49. package/src/native/config-acl.ps1 +34 -0
  50. package/src/native/connection-macos.js +109 -0
  51. package/src/native/connection-windows.ps1 +98 -0
  52. package/src/native/setup-macos.js +72 -0
  53. package/src/native/setup-windows.ps1 +83 -0
  54. package/src/native-prompt.js +85 -0
  55. package/src/payment-signing.js +362 -0
  56. package/src/prompt.js +69 -0
  57. package/src/provider-api-import-v2.js +72 -0
  58. package/src/provider-apis.js +3 -0
  59. package/src/provider-client.js +153 -0
  60. package/src/provider-connections.js +152 -0
  61. package/src/provider-import-format.js +289 -0
  62. package/src/provider-imports.js +402 -0
  63. package/src/provider-json.js +49 -0
  64. package/src/provider-model-import-v2.js +61 -0
  65. package/src/provider-models.js +253 -0
  66. package/src/provider-profile.js +65 -0
  67. package/src/provider-reviews.js +61 -0
  68. package/src/provider-state.js +176 -0
  69. package/src/provider.js +75 -0
  70. package/src/setup.js +201 -0
  71. package/src/tasks.js +53 -0
  72. package/src/topups.js +845 -0
  73. package/src/vendor/provider-apply/market-taxonomy.mjs +22 -0
  74. package/src/vendor/provider-apply/provenance.json +8 -0
  75. package/src/vendor/provider-apply/registration.mjs +151 -0
  76. package/src/vendor/provider-import/api-categories.json +29 -0
  77. package/src/vendor/provider-import/api-fields.json +33 -0
  78. package/src/vendor/provider-import/model-fields.json +44 -0
  79. package/src/wallet.js +213 -0
  80. package/src/windows-permissions.js +22 -0
@@ -0,0 +1,152 @@
1
+ import { CLIError, requireValue } from "./errors.js";
2
+ import { terminalInput } from "./prompt.js";
3
+ import { assertNoSecrets, uuid } from "./provider-state.js";
4
+ const authTypes = [
5
+ "none",
6
+ "Authorization",
7
+ "api-key",
8
+ "X-API-Key",
9
+ "xi-api-key",
10
+ "X-Treg-Token",
11
+ "authorization_raw",
12
+ "raw_authorization",
13
+ "query",
14
+ "path",
15
+ ];
16
+ async function ask(ctx, label, validate, { hidden = false } = {}) {
17
+ for (;;) {
18
+ const value = await terminalInput(ctx.stdin, ctx.stderr, label, { hidden });
19
+ if (hidden && value) ctx.secrets.push(value);
20
+ const error = validate(value);
21
+ if (!error) return value;
22
+ ctx.stderr.write(`${error}\n`);
23
+ }
24
+ }
25
+
26
+ async function connectionInput(ctx) {
27
+ validateCreationOptions(ctx);
28
+ const label = await ask(ctx, "Connection label", v =>
29
+ !v || v.length > 120 ? "Enter a label of 1–120 characters." : null);
30
+ const baseUrl = await ask(ctx, "Base URL", validateBaseUrl);
31
+ ctx.stderr.write(authTypes.map((type, i) => ` ${i + 1}. ${type}`).join("\n") + "\n");
32
+ const selected = await ask(ctx, "Authentication type (number or name)", v =>
33
+ authTypes.some(type => type.toLowerCase() === v.toLowerCase()) ||
34
+ authTypes.some((_, i) => String(i + 1) === v)
35
+ ? null : "Select a listed authentication type.");
36
+ const authType = authTypes.find(type => type.toLowerCase() === selected.toLowerCase()) || authTypes[Number(selected) - 1];
37
+ const input = { label, baseUrl, authType };
38
+ if (["query", "path"].includes(authType))
39
+ input.authParamName = await ask(ctx, "Authentication parameter name", v =>
40
+ v ? null : "Enter an authentication parameter name.");
41
+ return input;
42
+ }
43
+
44
+ function validateCreationOptions(ctx) {
45
+ requireValue(ctx.options.application, "--application");
46
+ uuid(ctx.options.application, "application");
47
+ requireValue(ctx.options.operation, "--operation");
48
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(ctx.options.operation))
49
+ throw new CLIError("INVALID_INPUT", "Operation must use 1–128 letters, digits, dots, underscores or hyphens.");
50
+ }
51
+
52
+ function validateBaseUrl(v) {
53
+ const message = "Enter an HTTP(S) URL up to 2048 characters without credentials, query or fragment.";
54
+ try {
55
+ const url = new URL(v);
56
+ return v.length > 2048 || !/^https?:\/\//i.test(v) ||
57
+ url.username || url.password || v.includes("?") || v.includes("#")
58
+ ? message : null;
59
+ } catch {
60
+ return message;
61
+ }
62
+ }
63
+
64
+ async function guiConnectionInput(ctx) {
65
+ validateCreationOptions(ctx);
66
+ const { nativePrompt } = await import("./native-prompt.js");
67
+ const prompt = ctx.nativePrompt || nativePrompt;
68
+ const deadline = Date.now() + 300_000;
69
+ let error = "";
70
+ for (;;) {
71
+ const timeoutMs = deadline - Date.now();
72
+ if (timeoutMs <= 0) throw new CLIError("GUI_TIMEOUT", "Connection creation timed out; nothing was submitted.");
73
+ const reply = await prompt({ mode: "connection", authTypes, error }, { timeoutMs });
74
+ if (reply?.cancelled) throw new CLIError("CANCELLED", "Connection creation cancelled; nothing was submitted.");
75
+ if (!reply || Array.isArray(reply) ||
76
+ !["label", "baseUrl", "authType", "secret"].every(key => typeof reply[key] === "string") ||
77
+ (reply.authParamName !== undefined && typeof reply.authParamName !== "string"))
78
+ throw new CLIError("GUI_PROTOCOL_ERROR", "The native connection dialog returned invalid input.");
79
+ if (reply.secret) ctx.secrets.push(reply.secret);
80
+ const label = reply.label.trim(), baseUrl = reply.baseUrl.trim();
81
+ const authType = authTypes.find(type => type.toLowerCase() === reply.authType.toLowerCase());
82
+ const authParamName = reply.authParamName?.trim();
83
+ const secret = reply.secret.trim();
84
+ error = !label || label.length > 120 ? "Enter a label of 1–120 characters."
85
+ : validateBaseUrl(baseUrl) || (!authType ? "Select a listed authentication type."
86
+ : ["query", "path"].includes(authType) && !authParamName ? "Enter an authentication parameter name."
87
+ : authType !== "none" && (!secret || secret.length > 16384) ? "Enter an API key of 1–16384 characters." : "");
88
+ if (error) {
89
+ ctx.stderr.write(error + "\n");
90
+ continue;
91
+ }
92
+ const input = { label, baseUrl, authType };
93
+ if (["query", "path"].includes(authType)) input.authParamName = authParamName;
94
+ return { input, secret };
95
+ }
96
+ }
97
+
98
+ export async function runConnections(action, client, ctx) {
99
+ if (action === "list")
100
+ return client.request("/connections", {
101
+ query: { limit: ctx.options.limit, cursor: ctx.options.cursor },
102
+ });
103
+ if (action === "get")
104
+ return client.request("/connections/" + uuid(ctx.options.id));
105
+ if (action !== "create")
106
+ throw new CLIError(
107
+ "UNKNOWN_COMMAND",
108
+ "Connections support list|get|create",
109
+ );
110
+ const interactive = ctx.stdin?.isTTY && !ctx.options.json &&
111
+ !ctx.options["non-interactive"] && !ctx.options.stdin &&
112
+ ctx.options.file === undefined && ctx.options.input === undefined;
113
+ const gui = ctx.options.gui ? await guiConnectionInput(ctx) : null;
114
+ const input = gui ? gui.input : interactive ? await connectionInput(ctx) : await ctx.input();
115
+ if (!input || typeof input !== "object" || Array.isArray(input))
116
+ throw new CLIError("INVALID_INPUT", "Connection must be an object");
117
+ assertNoSecrets(input);
118
+ if (
119
+ typeof input.authType !== "string" ||
120
+ !authTypes.some(
121
+ (value) => value.toLowerCase() === input.authType.toLowerCase(),
122
+ )
123
+ )
124
+ throw new CLIError(
125
+ "AUTH_TYPE_REQUIRED",
126
+ "Specify a supported authentication type explicitly",
127
+ );
128
+ if (input.authType.toLowerCase() !== "none") {
129
+ let key = gui ? gui.secret : ctx.env.OPENANY_DEV_UPSTREAM_API_KEY;
130
+ if (ctx.options.stdin) {
131
+ key = "";
132
+ for await (const chunk of ctx.stdin) {
133
+ key += chunk;
134
+ if (key.length > 16384)
135
+ throw new CLIError("INVALID_INPUT", "Credential exceeds size limit");
136
+ }
137
+ key = key.trim();
138
+ }
139
+ if (!key && interactive)
140
+ key = await ask(ctx, "API key (hidden input)", v =>
141
+ !v || v.length > 16384 ? "Enter an API key of 1–16384 characters." : null,
142
+ { hidden: true });
143
+ if (!key)
144
+ throw new CLIError(
145
+ "UPSTREAM_CREDENTIAL_REQUIRED",
146
+ "Set OPENANY_DEV_UPSTREAM_API_KEY or provide the key with --stdin; never put it in configuration files",
147
+ );
148
+ ctx.secrets.push(key);
149
+ input.apiKey = key;
150
+ }
151
+ return client.write("/connections", "POST", input, ctx.options.operation);
152
+ }
@@ -0,0 +1,289 @@
1
+ import { apiImportV2, apiImportVersion, maxApiItemIdLength } from "./provider-api-import-v2.js";
2
+ import { modelImportV2, modelImportVersion } from "./provider-model-import-v2.js";
3
+ import { importOpenApi } from "./vendor/provider-apply/registration.mjs";
4
+ import { CLIError } from "./errors.js";
5
+ import { assertNoSecrets, digest } from "./provider-state.js";
6
+ import { checkConfiguration } from "./provider-models.js";
7
+ const object = (v) => v && typeof v === "object" && !Array.isArray(v);
8
+ export function manifest(value, name, type) {
9
+ const maxItemIdLength = type === "api" ? maxApiItemIdLength : 128;
10
+ if (
11
+ !object(value) ||
12
+ value.schemaVersion !== 1 ||
13
+ !Array.isArray(value.items) ||
14
+ value.items.length > 100 ||
15
+ Object.keys(value).some((k) => !["schemaVersion", "items"].includes(k))
16
+ )
17
+ throw new CLIError(
18
+ "IMPORT_FORMAT",
19
+ `${name} requires schemaVersion 1 and at most 100 items`,
20
+ );
21
+ assertNoSecrets(value);
22
+ const seen = new Set();
23
+ for (const item of value.items) {
24
+ if (
25
+ !object(item) ||
26
+ typeof item.itemId !== "string" ||
27
+ !item.itemId.trim() ||
28
+ item.itemId.length > maxItemIdLength
29
+ )
30
+ throw new CLIError(
31
+ "IMPORT_FORMAT",
32
+ `Each item requires itemId (1–${maxItemIdLength} characters)`,
33
+ );
34
+ if (seen.has(item.itemId))
35
+ throw new CLIError("DUPLICATE_ITEM", "Duplicate itemId", {
36
+ itemId: item.itemId,
37
+ });
38
+ seen.add(item.itemId);
39
+ }
40
+ return value.items;
41
+ }
42
+ function prices(value) {
43
+ if (!value || typeof value !== "object") return;
44
+ for (const [k, v] of Object.entries(value)) {
45
+ if (
46
+ [
47
+ "actualPrompt",
48
+ "actualCompletion",
49
+ "cacheCreationPrompt",
50
+ "cacheReadPrompt",
51
+ ].includes(k) &&
52
+ v !== null
53
+ ) {
54
+ if (typeof v !== "string" || !/^\d+(?:\.\d{1,6})?$/.test(v))
55
+ throw new CLIError(
56
+ "INVALID_PRICE",
57
+ "Model prices must be decimal strings with at most six fractional digits",
58
+ { field: k },
59
+ );
60
+ const [whole, fraction = ""] = v.split(".");
61
+ if (
62
+ BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0")) >
63
+ 9223372036854775807n
64
+ )
65
+ throw new CLIError("INVALID_PRICE", "Price exceeds supported range", {
66
+ field: k,
67
+ });
68
+ } else if (typeof v === "object") prices(v);
69
+ }
70
+ }
71
+ const hasReference = (v) =>
72
+ object(v) || Array.isArray(v)
73
+ ? Object.entries(v).some(([k, x]) => k === "$ref" || hasReference(x))
74
+ : false;
75
+ export function parseImport(
76
+ type,
77
+ document,
78
+ metadata = { schemaVersion: 1, items: [] },
79
+ ) {
80
+ assertNoSecrets(document);
81
+ const websiteModel = type === "model" && (document?.schemaVersion === modelImportVersion || document?.models !== undefined);
82
+ if (websiteModel)
83
+ document = modelImportV2(document);
84
+ const supplements = new Map(
85
+ manifest(metadata, "Metadata", type).map((v) => [v.itemId, v.configuration]),
86
+ );
87
+ let items = [];
88
+ if (type === "model") {
89
+ items = manifest(document, "Model manifest").map((item) => {
90
+ if (
91
+ Object.keys(item).some((k) => !["itemId", "configuration"].includes(k))
92
+ )
93
+ throw new CLIError("IMPORT_FORMAT", "Unexpected model item field");
94
+ const c = item.configuration;
95
+ checkConfiguration(c);
96
+ if (!object(c.price) || !Array.isArray(c.routes) || !c.routes.length)
97
+ throw new CLIError(
98
+ "IMPORT_FORMAT",
99
+ "Model configuration requires price and routes",
100
+ { itemId: item.itemId },
101
+ );
102
+ prices(c.price);
103
+ return {
104
+ itemId: item.itemId,
105
+ configuration: c,
106
+ source: { itemId: item.itemId, ...(websiteModel && { schemaVersion: modelImportVersion }) },
107
+ };
108
+ });
109
+ } else if (type === "api" && (document?.schemaVersion === apiImportVersion || document?.apis !== undefined)) {
110
+ if (supplements.size)
111
+ throw new CLIError("IMPORT_FORMAT", "Put API configuration in the website template; metadata is for OpenAPI sources");
112
+ items = apiImportV2(document);
113
+ } else if (type === "api") {
114
+ if (
115
+ !object(document) ||
116
+ !String(document.openapi).startsWith("3.") ||
117
+ !object(document.paths)
118
+ )
119
+ throw new CLIError(
120
+ "IMPORT_FORMAT",
121
+ "Upload an OpenAPI 3.x JSON document or a provider-agent-api-v2 template",
122
+ );
123
+ for (const [path, operations] of Object.entries(document.paths)) {
124
+ if (!object(operations))
125
+ throw new CLIError(
126
+ "IMPORT_FORMAT",
127
+ "OpenAPI path item must be an object",
128
+ );
129
+ if (operations.$ref) {
130
+ items.push({
131
+ itemId: `PATH ${path}`,
132
+ source: { path },
133
+ errorCode: "UNSUPPORTED_REFERENCE",
134
+ });
135
+ continue;
136
+ }
137
+ for (const [method, operation] of Object.entries(operations)) {
138
+ if (
139
+ ["summary", "description", "servers", "parameters"].includes(
140
+ method,
141
+ ) ||
142
+ method.startsWith("x-")
143
+ )
144
+ continue;
145
+ const itemId = `${method.toUpperCase()} ${path}`,
146
+ source = { method: method.toUpperCase(), path };
147
+ if (
148
+ !["get", "post", "put", "patch", "delete"].includes(method) ||
149
+ !object(operation)
150
+ ) {
151
+ items.push({ itemId, source, errorCode: "UNSUPPORTED_OPERATION" });
152
+ continue;
153
+ }
154
+ if (hasReference(operation) || hasReference(operations.parameters)) {
155
+ items.push({ itemId, source, errorCode: "UNSUPPORTED_REFERENCE" });
156
+ continue;
157
+ }
158
+ const contentTypes = Object.keys(operation.requestBody?.content || {});
159
+ if (
160
+ contentTypes.length &&
161
+ !contentTypes.some((value) =>
162
+ ["application/json", "application/x-www-form-urlencoded"].includes(
163
+ value,
164
+ ),
165
+ )
166
+ ) {
167
+ items.push({ itemId, source, errorCode: "UNSUPPORTED_CONTENT_TYPE" });
168
+ continue;
169
+ }
170
+ const converted = importOpenApi({
171
+ ...document,
172
+ servers: operation.servers || operations.servers || document.servers,
173
+ paths: { [path]: { [method]: operation } },
174
+ });
175
+ const e = converted.endpoints[0],
176
+ extra = supplements.get(itemId) || {};
177
+ if (
178
+ (extra.method && extra.method !== e.method) ||
179
+ (extra.pathTemplate && extra.pathTemplate !== e.path)
180
+ )
181
+ throw new CLIError(
182
+ "SOURCE_MISMATCH",
183
+ "Metadata cannot override the source method or path",
184
+ { itemId },
185
+ );
186
+ checkConfiguration(extra);
187
+ const security = operation.security ?? document.security;
188
+ items.push({
189
+ itemId,
190
+ source: {
191
+ ...source,
192
+ baseUrl: converted.baseUrl,
193
+ authRequirement:
194
+ Array.isArray(security) && security.length === 0
195
+ ? "none"
196
+ : Array.isArray(security) && security.length
197
+ ? "authenticated"
198
+ : "unknown",
199
+ },
200
+ configuration: {
201
+ name: e.name,
202
+ description: e.description,
203
+ ...extra,
204
+ method: e.method,
205
+ pathTemplate: e.path,
206
+ },
207
+ });
208
+ }
209
+ }
210
+ } else
211
+ throw new CLIError("IMPORT_FORMAT", "Import type must be api or model");
212
+ if (!items.length || items.length > 100)
213
+ throw new CLIError("IMPORT_LIMIT", "Imports require 1–100 items");
214
+ const seen = new Set(items.map((i) => i.itemId));
215
+ for (const id of supplements.keys())
216
+ if (!seen.has(id))
217
+ throw new CLIError(
218
+ "IMPORT_FORMAT",
219
+ "Metadata item does not exist in source",
220
+ { itemId: id },
221
+ );
222
+ return items.map((item) => ({
223
+ ...item,
224
+ inputDigest: digest(item),
225
+ stage: item.errorCode ? "failed" : "needs_information",
226
+ missingFields: [],
227
+ }));
228
+ }
229
+ export function applyBindings(items, value, type) {
230
+ const bindings = new Map(
231
+ manifest(value, "Bindings", type).map((v) => [v.itemId, v]),
232
+ );
233
+ const ids = new Set(items.map((v) => v.itemId));
234
+ for (const id of bindings.keys())
235
+ if (!ids.has(id))
236
+ throw new CLIError("IMPORT_FORMAT", "Binding item does not exist", {
237
+ itemId: id,
238
+ });
239
+ return items.map((item) => {
240
+ const b = bindings.get(item.itemId);
241
+ if (!b) return item;
242
+ const next = structuredClone(item);
243
+ if (!next.configuration)
244
+ throw new CLIError(
245
+ "IMPORT_FORMAT",
246
+ "Cannot bind an unsupported operation",
247
+ );
248
+ if (
249
+ Object.keys(b).some(
250
+ (k) => !["itemId", "upstreamKeyId", "routes"].includes(k),
251
+ )
252
+ )
253
+ throw new CLIError("IMPORT_FORMAT", "Unknown connection binding field");
254
+ if (b.upstreamKeyId) next.configuration.upstreamKeyId = b.upstreamKeyId;
255
+ if (b.routes) {
256
+ if (!Array.isArray(b.routes) || !next.configuration.routes)
257
+ throw new CLIError(
258
+ "IMPORT_FORMAT",
259
+ "Routes bindings are only valid for models",
260
+ );
261
+ const seen = new Set();
262
+ for (const r of b.routes) {
263
+ if (
264
+ !Number.isInteger(r.index) ||
265
+ r.index < 0 ||
266
+ r.index >= next.configuration.routes.length ||
267
+ seen.has(r.index) ||
268
+ Object.keys(r).some((k) => !["index", "upstreamKeyId", "familyId"].includes(k))
269
+ )
270
+ throw new CLIError(
271
+ "IMPORT_FORMAT",
272
+ "Invalid or duplicate route binding",
273
+ );
274
+ seen.add(r.index);
275
+ const route = next.configuration.routes[r.index];
276
+ if (Object.hasOwn(r, "upstreamKeyId")) route.upstreamKeyId = r.upstreamKeyId;
277
+ if (Object.hasOwn(r, "familyId")) {
278
+ if (r.familyId === null) delete route.familyId;
279
+ else route.familyId = r.familyId;
280
+ }
281
+ }
282
+ }
283
+ next.inputDigest = digest({
284
+ source: next.source,
285
+ configuration: next.configuration,
286
+ });
287
+ return next;
288
+ });
289
+ }