openany-cli-dev 0.0.0-stage → 0.1.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 +461 -2
- package/bin/openany.js +3 -0
- package/package.json +27 -4
- package/skills/openany/SKILL.md +347 -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/application.md +49 -0
- package/skills/openany-provider/references/application.zh-CN.md +51 -0
- package/skills/openany-provider/references/auth.md +59 -0
- package/skills/openany-provider/references/connections.md +38 -0
- package/skills/openany-provider/references/connections.zh-CN.md +33 -0
- package/skills/openany-provider/references/imports.md +38 -0
- package/skills/openany-provider/references/imports.zh-CN.md +55 -0
- package/skills/openany-provider/references/listing.md +29 -0
- package/skills/openany-provider/references/login.md +58 -0
- package/skills/openany-provider/references/login.zh-CN.md +59 -0
- package/skills/openany-provider/references/model-import.zh-CN.md +12 -0
- package/skills/openany-provider/references/models.md +107 -0
- package/skills/openany-provider/references/publishing.md +83 -0
- package/skills/openany-provider/references/publishing.zh-CN.md +81 -0
- package/skills/openany-provider/references/reviews.md +22 -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 +839 -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 +601 -0
- package/src/config.js +260 -0
- package/src/errors.js +53 -0
- package/src/http.js +237 -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/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
package/src/config.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mkdir,
|
|
3
|
+
readFile,
|
|
4
|
+
open,
|
|
5
|
+
rename,
|
|
6
|
+
unlink,
|
|
7
|
+
chmod,
|
|
8
|
+
lstat,
|
|
9
|
+
} from "node:fs/promises";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { CLIError } from "./errors.js";
|
|
14
|
+
import { windowsPermissions } from "./windows-permissions.js";
|
|
15
|
+
const empty = () => ({
|
|
16
|
+
version: 1,
|
|
17
|
+
keys: [],
|
|
18
|
+
activeKey: null,
|
|
19
|
+
sessions: {},
|
|
20
|
+
intents: {},
|
|
21
|
+
});
|
|
22
|
+
export class ConfigStore {
|
|
23
|
+
constructor(env = process.env) {
|
|
24
|
+
this.env = env;
|
|
25
|
+
this.directory = resolve(
|
|
26
|
+
env.OPENANY_DEV_CONFIG_DIR || join(homedir(), ".config", "openany-dev"),
|
|
27
|
+
);
|
|
28
|
+
this.path = join(this.directory, "credentials.json");
|
|
29
|
+
}
|
|
30
|
+
async read() {
|
|
31
|
+
try {
|
|
32
|
+
const metadata = await lstat(this.path);
|
|
33
|
+
if (!metadata.isFile() || metadata.isSymbolicLink())
|
|
34
|
+
throw new CLIError(
|
|
35
|
+
"CONFIG_UNSAFE",
|
|
36
|
+
"Credentials must be a regular file",
|
|
37
|
+
);
|
|
38
|
+
if (process.platform === "win32") await windowsPermissions(this.path);
|
|
39
|
+
if (process.platform !== "win32" && (metadata.mode & 0o077) !== 0)
|
|
40
|
+
throw new CLIError(
|
|
41
|
+
"CONFIG_UNSAFE",
|
|
42
|
+
"Credentials permissions must be 0600",
|
|
43
|
+
);
|
|
44
|
+
const state = JSON.parse(await readFile(this.path, "utf8"));
|
|
45
|
+
if (state.version !== 1 || !Array.isArray(state.keys))
|
|
46
|
+
throw new CLIError("CONFIG_INVALID", "Unsupported credentials format");
|
|
47
|
+
return { ...empty(), ...state };
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code === "ENOENT") return empty();
|
|
50
|
+
if (error instanceof SyntaxError)
|
|
51
|
+
throw new CLIError("CONFIG_INVALID", "Credentials are not valid JSON");
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async update(mutator) {
|
|
56
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
57
|
+
const metadata = await lstat(this.directory);
|
|
58
|
+
if (!metadata.isDirectory() || metadata.isSymbolicLink())
|
|
59
|
+
throw new CLIError(
|
|
60
|
+
"CONFIG_UNSAFE",
|
|
61
|
+
"Configuration directory must not be a symbolic link",
|
|
62
|
+
);
|
|
63
|
+
if (process.platform === "win32") await windowsPermissions(this.directory, true);
|
|
64
|
+
else await chmod(this.directory, 0o700);
|
|
65
|
+
const lockPath = join(this.directory, ".lock");
|
|
66
|
+
let lock;
|
|
67
|
+
try {
|
|
68
|
+
lock = await open(lockPath, "wx", 0o600);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error.code === "EEXIST")
|
|
71
|
+
throw new CLIError(
|
|
72
|
+
"CONFIG_LOCKED",
|
|
73
|
+
"Another command holds the configuration lock; verify it has stopped before removing .lock",
|
|
74
|
+
);
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
const temporary = join(this.directory, `.credentials-${randomUUID()}.tmp`);
|
|
78
|
+
try {
|
|
79
|
+
const state = await this.read();
|
|
80
|
+
const result = await mutator(state);
|
|
81
|
+
const file = await open(temporary, "wx", 0o600);
|
|
82
|
+
try {
|
|
83
|
+
await file.writeFile(JSON.stringify(state, null, 2) + "\n");
|
|
84
|
+
await file.sync();
|
|
85
|
+
} finally {
|
|
86
|
+
await file.close();
|
|
87
|
+
}
|
|
88
|
+
await rename(temporary, this.path);
|
|
89
|
+
return result;
|
|
90
|
+
} finally {
|
|
91
|
+
await unlink(temporary).catch((error) => {
|
|
92
|
+
if (error.code !== "ENOENT") throw error;
|
|
93
|
+
});
|
|
94
|
+
await lock.close();
|
|
95
|
+
await unlink(lockPath);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async backupAndLogout() {
|
|
99
|
+
const environmentOverrides = [
|
|
100
|
+
"OPENANY_DEV_API_KEY", "OPENANY_DEV_WALLET_ADDRESS", "OPENANY_DEV_WALLET_PRIVATE_KEY",
|
|
101
|
+
"OPENANY_DEV_AGENT_ID", "OPENANY_DEV_EMAIL",
|
|
102
|
+
].filter(name => this.env[name]?.trim());
|
|
103
|
+
const result = backupPath => ({
|
|
104
|
+
localConfigurationCleared: true,
|
|
105
|
+
loggedOut: environmentOverrides.length === 0,
|
|
106
|
+
backupPath,
|
|
107
|
+
environmentOverrides,
|
|
108
|
+
message: environmentOverrides.length
|
|
109
|
+
? "Local configuration cleared. Remove the listed environment variables in the calling environment before switching accounts."
|
|
110
|
+
: "Local configuration cleared. Choose API key, wallet, or email setup for the next account.",
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
const directory = await lstat(this.directory);
|
|
114
|
+
if (!directory.isDirectory() || directory.isSymbolicLink())
|
|
115
|
+
throw new CLIError("CONFIG_UNSAFE", "Configuration directory must not be a symbolic link");
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (error.code === "ENOENT") return result(null);
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
if (process.platform === "win32") await windowsPermissions(this.directory, true);
|
|
121
|
+
else await chmod(this.directory, 0o700);
|
|
122
|
+
const lockPath = join(this.directory, ".lock");
|
|
123
|
+
let lock;
|
|
124
|
+
try {
|
|
125
|
+
lock = await open(lockPath, "wx", 0o600);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error.code === "EEXIST")
|
|
128
|
+
throw new CLIError("CONFIG_LOCKED", "Another command holds the configuration lock; wait for it to finish before logging out");
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
// Validate the file and its permissions while holding the same lock as writers.
|
|
133
|
+
await this.read();
|
|
134
|
+
const backupPath = join(this.directory, `credentials.backup-${Date.now()}-${randomUUID()}.json`);
|
|
135
|
+
try {
|
|
136
|
+
// Same-directory rename atomically preserves the original file and its permissions.
|
|
137
|
+
await rename(this.path, backupPath);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error.code === "ENOENT") return result(null);
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
return result(backupPath);
|
|
143
|
+
} finally {
|
|
144
|
+
await lock.close();
|
|
145
|
+
await unlink(lockPath);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async getApiKey() {
|
|
149
|
+
if (this.env.OPENANY_DEV_API_KEY?.trim())
|
|
150
|
+
return this.env.OPENANY_DEV_API_KEY.trim();
|
|
151
|
+
const state = await this.read();
|
|
152
|
+
return state.keys.find((k) => k.label === state.activeKey)?.key || null;
|
|
153
|
+
}
|
|
154
|
+
async getEnvironment() {
|
|
155
|
+
const { settings = {} } = await this.read();
|
|
156
|
+
if (!settings || typeof settings !== "object" || Array.isArray(settings))
|
|
157
|
+
throw new CLIError("CONFIG_INVALID", "Invalid saved settings");
|
|
158
|
+
const env = { ...this.env };
|
|
159
|
+
for (const name of [
|
|
160
|
+
"OPENANY_DEV_WALLET_ADDRESS",
|
|
161
|
+
"OPENANY_DEV_WALLET_PRIVATE_KEY",
|
|
162
|
+
"OPENANY_DEV_AGENT_ID",
|
|
163
|
+
"OPENANY_DEV_EMAIL",
|
|
164
|
+
]) {
|
|
165
|
+
if (settings[name] !== undefined && typeof settings[name] !== "string")
|
|
166
|
+
throw new CLIError("CONFIG_INVALID", `Invalid saved ${name}`);
|
|
167
|
+
if (!env[name]?.trim() && settings[name]) env[name] = settings[name];
|
|
168
|
+
}
|
|
169
|
+
return env;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function configurationStatus(store, options = {}) {
|
|
174
|
+
const env = await store.getEnvironment();
|
|
175
|
+
const state = await store.read();
|
|
176
|
+
const key = await store.getApiKey();
|
|
177
|
+
const localKey = state.keys.find((item) => item.label === state.activeKey);
|
|
178
|
+
const metadata = env.OPENANY_DEV_API_KEY
|
|
179
|
+
? state.keys.find((item) => item.key === env.OPENANY_DEV_API_KEY)?.metadata
|
|
180
|
+
: localKey?.metadata;
|
|
181
|
+
const scenario = options.scenario ?? "call";
|
|
182
|
+
if (!["call", "wallet", "email", "payment"].includes(scenario)) {
|
|
183
|
+
throw new CLIError(
|
|
184
|
+
"INVALID_INPUT",
|
|
185
|
+
"Scenario must be call, wallet, email or payment",
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
const missing = [];
|
|
189
|
+
const result = {
|
|
190
|
+
scenario,
|
|
191
|
+
configured: false,
|
|
192
|
+
missing,
|
|
193
|
+
networkVerified: false,
|
|
194
|
+
};
|
|
195
|
+
function need(name, value) {
|
|
196
|
+
if (!value) missing.push(name);
|
|
197
|
+
}
|
|
198
|
+
if (scenario === "call" || scenario === "payment") {
|
|
199
|
+
need("OPENANY_DEV_API_KEY", key);
|
|
200
|
+
result.source = env.OPENANY_DEV_API_KEY ? "environment" : key ? "local" : null;
|
|
201
|
+
}
|
|
202
|
+
if (scenario === "wallet" || scenario === "payment") {
|
|
203
|
+
need("OPENANY_DEV_WALLET_ADDRESS", env.OPENANY_DEV_WALLET_ADDRESS);
|
|
204
|
+
if (!options.prepare)
|
|
205
|
+
need("OPENANY_DEV_WALLET_PRIVATE_KEY", env.OPENANY_DEV_WALLET_PRIVATE_KEY);
|
|
206
|
+
result.signing = options.prepare
|
|
207
|
+
? "external_signature_required"
|
|
208
|
+
: "local_key_unverified";
|
|
209
|
+
}
|
|
210
|
+
if (scenario === "wallet") need("OPENANY_DEV_AGENT_ID", env.OPENANY_DEV_AGENT_ID);
|
|
211
|
+
if (scenario === "email") {
|
|
212
|
+
need(
|
|
213
|
+
"OPENANY_DEV_EMAIL",
|
|
214
|
+
options.email || env.OPENANY_DEV_EMAIL || state.sessions.email?.email,
|
|
215
|
+
);
|
|
216
|
+
result.mailboxAccess = "agent_must_verify";
|
|
217
|
+
}
|
|
218
|
+
if (scenario === "payment") {
|
|
219
|
+
const identity = options.identity || metadata?.identity;
|
|
220
|
+
if (identity && !["wallet", "email"].includes(identity)) {
|
|
221
|
+
throw new CLIError(
|
|
222
|
+
"INVALID_INPUT",
|
|
223
|
+
"Payment identity must be wallet or email",
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
need("identity", identity);
|
|
227
|
+
result.identity = identity ?? null;
|
|
228
|
+
const policies = Object.values(state.paymentPolicies || {});
|
|
229
|
+
const policyReady = policies.some(
|
|
230
|
+
(policy) =>
|
|
231
|
+
Date.parse(policy.expiresAt) > Date.now() &&
|
|
232
|
+
(!identity || policy.identity === identity) &&
|
|
233
|
+
(!options.scope || policy.scope === options.scope),
|
|
234
|
+
);
|
|
235
|
+
need("payment_policy", policyReady);
|
|
236
|
+
const wallet = state.sessions.wallet;
|
|
237
|
+
const email = state.sessions.email;
|
|
238
|
+
result.identitySession =
|
|
239
|
+
identity === "wallet"
|
|
240
|
+
? {
|
|
241
|
+
type: "wallet",
|
|
242
|
+
configured: Boolean(
|
|
243
|
+
wallet?.token && Date.parse(wallet.expiresAt) > Date.now(),
|
|
244
|
+
),
|
|
245
|
+
}
|
|
246
|
+
: identity === "email"
|
|
247
|
+
? {
|
|
248
|
+
type: "email",
|
|
249
|
+
configured: Boolean(email?.accessToken && email?.workspaceId),
|
|
250
|
+
}
|
|
251
|
+
: { type: null, configured: false };
|
|
252
|
+
if (identity)
|
|
253
|
+
need(`${identity}_session`, result.identitySession.configured);
|
|
254
|
+
if (!policyReady)
|
|
255
|
+
result.hint =
|
|
256
|
+
"Use topups authorize with identity, network, max-single-usd, max-total-usd, scope and expires-at";
|
|
257
|
+
}
|
|
258
|
+
result.configured = missing.length === 0;
|
|
259
|
+
return result;
|
|
260
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export class CLIError extends Error {
|
|
2
|
+
constructor(code, message, details = {}) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = "CLIError";
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.details = details;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function requireValue(value, name) {
|
|
11
|
+
if (value === undefined || value === "" || value === true) {
|
|
12
|
+
throw new CLIError("INPUT_REQUIRED", `Missing ${name}`, {
|
|
13
|
+
missing: [name],
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function redact(value, secrets = [], space) {
|
|
20
|
+
const patterns = secrets
|
|
21
|
+
.filter((secret) => typeof secret === "string" && secret.length)
|
|
22
|
+
.sort((a, b) => b.length - a.length);
|
|
23
|
+
function clean(item) {
|
|
24
|
+
if (typeof item === "string") {
|
|
25
|
+
for (const secret of patterns)
|
|
26
|
+
item = item.split(secret).join("[REDACTED]");
|
|
27
|
+
return item.replace(
|
|
28
|
+
/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,
|
|
29
|
+
"Bearer [REDACTED]",
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
if (Array.isArray(item)) return item.map(clean);
|
|
33
|
+
if (item && typeof item === "object") {
|
|
34
|
+
return Object.fromEntries(
|
|
35
|
+
Object.entries(item).map(([key, child]) => [key, clean(child)]),
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
return item;
|
|
39
|
+
}
|
|
40
|
+
return typeof value === "string"
|
|
41
|
+
? clean(value)
|
|
42
|
+
: JSON.stringify(clean(value), null, space);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function errorRecord(error) {
|
|
46
|
+
return {
|
|
47
|
+
error: {
|
|
48
|
+
code: error.code || "INTERNAL_ERROR",
|
|
49
|
+
message: error.message || "Unexpected failure",
|
|
50
|
+
...(error.details || {}),
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { CLIError } from "./errors.js";
|
|
3
|
+
export const BACKEND_ORIGIN = "https://dev.openany.si";
|
|
4
|
+
export const GATEWAY_ORIGIN = "https://api-dev.openany.si";
|
|
5
|
+
export const unwrap = (response) => response.body?.data ?? response.body;
|
|
6
|
+
export function safePath(path, prefix = "/") {
|
|
7
|
+
if (
|
|
8
|
+
typeof path !== "string" ||
|
|
9
|
+
!path.startsWith(prefix) ||
|
|
10
|
+
path.startsWith("//") ||
|
|
11
|
+
/[\\?#\u0000-\u0020]/.test(path)
|
|
12
|
+
)
|
|
13
|
+
throw new CLIError("UNSAFE_PATH", "Invalid service path");
|
|
14
|
+
let decoded = path;
|
|
15
|
+
for (let i = 0; i < 5; i++) {
|
|
16
|
+
if (
|
|
17
|
+
decoded.split("/").some((v) => v === "." || v === "..") ||
|
|
18
|
+
/[\\?#\u0000-\u001f]/.test(decoded)
|
|
19
|
+
)
|
|
20
|
+
throw new CLIError("UNSAFE_PATH", "Invalid service path");
|
|
21
|
+
let next;
|
|
22
|
+
try {
|
|
23
|
+
next = decodeURIComponent(decoded);
|
|
24
|
+
} catch {
|
|
25
|
+
throw new CLIError("UNSAFE_PATH", "Malformed encoded service path");
|
|
26
|
+
}
|
|
27
|
+
if (next === decoded) return path;
|
|
28
|
+
decoded = next;
|
|
29
|
+
}
|
|
30
|
+
throw new CLIError("UNSAFE_PATH", "Excessively encoded service path");
|
|
31
|
+
}
|
|
32
|
+
export function modelUrl(value) {
|
|
33
|
+
// Validate the raw path before URL can normalize dot segments or backslashes.
|
|
34
|
+
const match = /^(https:\/\/[^/?#]+)(\/[^?#]*)?(\?[^#]*)?$/.exec(value);
|
|
35
|
+
if (!match)
|
|
36
|
+
throw new CLIError(
|
|
37
|
+
"INVALID_MODEL_URL",
|
|
38
|
+
"Example requires an absolute HTTPS URL without a fragment",
|
|
39
|
+
);
|
|
40
|
+
safePath(match[2] || "/");
|
|
41
|
+
let url;
|
|
42
|
+
try {
|
|
43
|
+
url = new URL(value);
|
|
44
|
+
} catch {
|
|
45
|
+
throw new CLIError("INVALID_MODEL_URL", "Invalid model request URL");
|
|
46
|
+
}
|
|
47
|
+
if (url.username || url.password || /[{}<>\s\\]/.test(match[1]))
|
|
48
|
+
throw new CLIError("INVALID_MODEL_URL", "Invalid model URL authority");
|
|
49
|
+
if (/[{}<>]/.test(match[3] || ""))
|
|
50
|
+
throw new CLIError(
|
|
51
|
+
"UNRESOLVED_PLACEHOLDER",
|
|
52
|
+
"Query placeholders are not supported",
|
|
53
|
+
);
|
|
54
|
+
return { origin: GATEWAY_ORIGIN, path: match[2] || "/", search: match[3] || "" };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class HttpClient {
|
|
58
|
+
constructor({
|
|
59
|
+
fetch: fetcher = globalThis.fetch,
|
|
60
|
+
apiKey,
|
|
61
|
+
timeoutMs = 120000,
|
|
62
|
+
} = {}) {
|
|
63
|
+
this.fetch = fetcher;
|
|
64
|
+
this.apiKey = apiKey;
|
|
65
|
+
this.timeoutMs = timeoutMs;
|
|
66
|
+
}
|
|
67
|
+
backend(path, options = {}) {
|
|
68
|
+
return this.request(BACKEND_ORIGIN, path, options);
|
|
69
|
+
}
|
|
70
|
+
gateway(path, options = {}) {
|
|
71
|
+
return this.request(GATEWAY_ORIGIN, path, options);
|
|
72
|
+
}
|
|
73
|
+
async model(url, options = {}) {
|
|
74
|
+
if (options.credential)
|
|
75
|
+
throw new CLIError(
|
|
76
|
+
"CREDENTIAL_SCOPE",
|
|
77
|
+
"Login credentials cannot be sent to model endpoints",
|
|
78
|
+
);
|
|
79
|
+
const { origin, path, search } = modelUrl(url);
|
|
80
|
+
return this.request(origin, path, {
|
|
81
|
+
...options,
|
|
82
|
+
rawSearch: search,
|
|
83
|
+
auth: "apiKey",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async request(
|
|
87
|
+
origin,
|
|
88
|
+
path,
|
|
89
|
+
{
|
|
90
|
+
method = "GET",
|
|
91
|
+
query,
|
|
92
|
+
rawSearch,
|
|
93
|
+
json,
|
|
94
|
+
body,
|
|
95
|
+
headers: extra,
|
|
96
|
+
credential,
|
|
97
|
+
auth,
|
|
98
|
+
allowStatuses = [],
|
|
99
|
+
} = {},
|
|
100
|
+
) {
|
|
101
|
+
safePath(path, origin === BACKEND_ORIGIN ? "/api/v1/" : "/");
|
|
102
|
+
if (origin !== BACKEND_ORIGIN && credential)
|
|
103
|
+
throw new CLIError(
|
|
104
|
+
"CREDENTIAL_SCOPE",
|
|
105
|
+
"Login credentials cannot be sent to the gateway",
|
|
106
|
+
);
|
|
107
|
+
if (
|
|
108
|
+
auth === "apiKey" &&
|
|
109
|
+
origin === BACKEND_ORIGIN &&
|
|
110
|
+
!/^\/api\/v1\/agent-api-(account|calls(?:\/[^/]+)?)$/.test(path)
|
|
111
|
+
)
|
|
112
|
+
throw new CLIError(
|
|
113
|
+
"CREDENTIAL_SCOPE",
|
|
114
|
+
"API key is not allowed on this backend endpoint",
|
|
115
|
+
);
|
|
116
|
+
const url = new URL(path, origin);
|
|
117
|
+
if (rawSearch) url.search = rawSearch;
|
|
118
|
+
for (const [key, value] of Object.entries(query || {}))
|
|
119
|
+
if (value !== undefined)
|
|
120
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
121
|
+
url.searchParams.append(key, String(item));
|
|
122
|
+
const headers = new Headers(extra);
|
|
123
|
+
for (const name of [
|
|
124
|
+
"authorization",
|
|
125
|
+
"cookie",
|
|
126
|
+
"x-workspace-id",
|
|
127
|
+
"proxy-authorization",
|
|
128
|
+
"host",
|
|
129
|
+
])
|
|
130
|
+
if (headers.has(name))
|
|
131
|
+
throw new CLIError(
|
|
132
|
+
"CREDENTIAL_SCOPE",
|
|
133
|
+
`Use the credential option for ${name}`,
|
|
134
|
+
);
|
|
135
|
+
if (auth === "apiKey") {
|
|
136
|
+
if (!this.apiKey)
|
|
137
|
+
throw new CLIError("CONFIG_REQUIRED", "Configure OPENANY_DEV_API_KEY", {
|
|
138
|
+
missing: ["OPENANY_DEV_API_KEY"],
|
|
139
|
+
});
|
|
140
|
+
headers.set("Authorization", `Bearer ${this.apiKey}`);
|
|
141
|
+
}
|
|
142
|
+
if (credential?.token)
|
|
143
|
+
headers.set("Authorization", `Bearer ${credential.token}`);
|
|
144
|
+
if (credential?.workspaceId)
|
|
145
|
+
headers.set("X-Workspace-Id", credential.workspaceId);
|
|
146
|
+
if (credential?.cookie) headers.set("Cookie", credential.cookie);
|
|
147
|
+
if (json !== undefined) {
|
|
148
|
+
if (!headers.has("Content-Type"))
|
|
149
|
+
headers.set("Content-Type", "application/json");
|
|
150
|
+
body = JSON.stringify(json);
|
|
151
|
+
}
|
|
152
|
+
if (!headers.has("Accept")) headers.set("Accept", "application/json");
|
|
153
|
+
if (origin === GATEWAY_ORIGIN) headers.set("x-request-id", randomUUID());
|
|
154
|
+
const signal = AbortSignal.timeout(this.timeoutMs);
|
|
155
|
+
let response;
|
|
156
|
+
try {
|
|
157
|
+
response = await this.fetch(url.toString(), {
|
|
158
|
+
method,
|
|
159
|
+
headers,
|
|
160
|
+
body,
|
|
161
|
+
signal,
|
|
162
|
+
redirect: "error",
|
|
163
|
+
credentials: "omit",
|
|
164
|
+
});
|
|
165
|
+
const contentType = response.headers.get("content-type") || "";
|
|
166
|
+
let result;
|
|
167
|
+
if (
|
|
168
|
+
contentType.includes("json") ||
|
|
169
|
+
contentType.startsWith("text/") ||
|
|
170
|
+
!contentType
|
|
171
|
+
) {
|
|
172
|
+
const text = await response.text();
|
|
173
|
+
try {
|
|
174
|
+
result = text ? JSON.parse(text) : null;
|
|
175
|
+
} catch {
|
|
176
|
+
if (contentType.includes("json"))
|
|
177
|
+
throw new CLIError(
|
|
178
|
+
"INVALID_RESPONSE",
|
|
179
|
+
"Service returned invalid JSON",
|
|
180
|
+
{
|
|
181
|
+
status: response.status,
|
|
182
|
+
requestId: response.headers.get("x-request-id"),
|
|
183
|
+
},
|
|
184
|
+
);
|
|
185
|
+
result = text;
|
|
186
|
+
}
|
|
187
|
+
} else result = new Uint8Array(await response.arrayBuffer());
|
|
188
|
+
const record = {
|
|
189
|
+
status: response.status,
|
|
190
|
+
headers: response.headers,
|
|
191
|
+
body: result,
|
|
192
|
+
contentType,
|
|
193
|
+
requestId: response.headers.get("x-request-id"),
|
|
194
|
+
};
|
|
195
|
+
if (
|
|
196
|
+
!allowStatuses.includes(response.status) &&
|
|
197
|
+
(!response.ok ||
|
|
198
|
+
result?.error ||
|
|
199
|
+
result?.success === false ||
|
|
200
|
+
(typeof result?.code === "string" &&
|
|
201
|
+
typeof result?.message === "string" &&
|
|
202
|
+
(Number(result.status) >= 400 ||
|
|
203
|
+
response.headers.get("x-openmodels-heartbeat") === "true")))
|
|
204
|
+
) {
|
|
205
|
+
const remote = result?.error ?? result;
|
|
206
|
+
throw new CLIError(
|
|
207
|
+
typeof remote?.code === "string"
|
|
208
|
+
? remote.code
|
|
209
|
+
: `HTTP_${response.status}`,
|
|
210
|
+
typeof remote?.message === "string"
|
|
211
|
+
? remote.message
|
|
212
|
+
: `Service request failed (${response.status})`,
|
|
213
|
+
{
|
|
214
|
+
status: response.status,
|
|
215
|
+
requestId: record.requestId ?? result?.requestId,
|
|
216
|
+
stage: origin === BACKEND_ORIGIN ? "backend" : "gateway",
|
|
217
|
+
},
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
return record;
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (error instanceof CLIError) throw error;
|
|
223
|
+
throw new CLIError(
|
|
224
|
+
signal.aborted ? "REQUEST_TIMEOUT" : "NETWORK_ERROR",
|
|
225
|
+
signal.aborted
|
|
226
|
+
? "Request timed out; execution may have occurred. Do not retry automatically."
|
|
227
|
+
: "Network request failed; execution may have occurred. Do not retry automatically.",
|
|
228
|
+
{
|
|
229
|
+
stage: origin === BACKEND_ORIGIN ? "backend" : "gateway",
|
|
230
|
+
outcome: method === "GET" ? "unknown" : "possibly_executed",
|
|
231
|
+
requestId: response?.headers.get("x-request-id") ?? null,
|
|
232
|
+
status: response?.status,
|
|
233
|
+
},
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|