@openclaw/chutes-provider 0.0.0 → 2026.6.9

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/dist/oauth.js ADDED
@@ -0,0 +1,149 @@
1
+ import { generatePkceVerifierChallenge, toFormUrlEncoded } from "openclaw/plugin-sdk/provider-auth";
2
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
3
+ import { randomBytes } from "node:crypto";
4
+ import { resolveExpiresAtMsFromDurationSeconds } from "openclaw/plugin-sdk/number-runtime";
5
+ import { parseOAuthCallbackInput, waitForLocalOAuthCallback } from "openclaw/plugin-sdk/provider-auth-runtime";
6
+ import { readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
7
+ //#region extensions/chutes/oauth.ts
8
+ /**
9
+ * Chutes OAuth PKCE login flow.
10
+ */
11
+ const CHUTES_AUTHORIZE_ENDPOINT = "https://api.chutes.ai/idp/authorize";
12
+ const CHUTES_TOKEN_ENDPOINT = "https://api.chutes.ai/idp/token";
13
+ const CHUTES_USERINFO_ENDPOINT = "https://api.chutes.ai/idp/userinfo";
14
+ const CHUTES_TOKEN_ERROR_BODY_LIMIT_BYTES = 8 * 1024;
15
+ function parseRedirectUri(redirectUri) {
16
+ const url = new URL(redirectUri);
17
+ if (url.protocol !== "http:") throw new Error(`Chutes OAuth redirect URI must be http:// (got ${redirectUri})`);
18
+ const hostname = url.hostname || "127.0.0.1";
19
+ if (hostname !== "localhost" && hostname !== "127.0.0.1" && hostname !== "::1") throw new Error(`Chutes OAuth redirect hostname must be loopback (got ${hostname}). Use http://127.0.0.1:<port>/...`);
20
+ return {
21
+ hostname,
22
+ port: url.port ? Number.parseInt(url.port, 10) : 80,
23
+ pathname: url.pathname || "/"
24
+ };
25
+ }
26
+ function parseManualOAuthInput(input, expectedState) {
27
+ const parsed = parseOAuthCallbackInput(input, {
28
+ invalidInput: "Paste the full redirect URL (must include code + state).",
29
+ missingState: "Missing 'state' parameter. Paste the full redirect URL."
30
+ });
31
+ if ("error" in parsed) throw new Error(parsed.error);
32
+ if (parsed.state !== expectedState) throw new Error("OAuth state mismatch - possible CSRF attack. Please retry login.");
33
+ return parsed;
34
+ }
35
+ function buildAuthorizeUrl(params) {
36
+ return `${CHUTES_AUTHORIZE_ENDPOINT}?${new URLSearchParams({
37
+ client_id: params.clientId,
38
+ redirect_uri: params.redirectUri,
39
+ response_type: "code",
40
+ scope: params.scopes.join(" "),
41
+ state: params.state,
42
+ code_challenge: params.challenge,
43
+ code_challenge_method: "S256"
44
+ }).toString()}`;
45
+ }
46
+ function resolveChutesExpiresAt(value, now) {
47
+ return resolveExpiresAtMsFromDurationSeconds(value, {
48
+ nowMs: now,
49
+ bufferMs: 300 * 1e3,
50
+ minRemainingMs: 3e4
51
+ });
52
+ }
53
+ async function fetchChutesUserInfo(params) {
54
+ const response = await (params.fetchFn ?? fetch)(CHUTES_USERINFO_ENDPOINT, { headers: { Authorization: `Bearer ${params.accessToken}` } });
55
+ if (!response.ok) return null;
56
+ const data = await response.json();
57
+ return data && typeof data === "object" ? data : null;
58
+ }
59
+ async function exchangeChutesCodeForTokens(params) {
60
+ const fetchFn = params.fetchFn ?? fetch;
61
+ const now = params.now ?? Date.now();
62
+ const body = new URLSearchParams(toFormUrlEncoded({
63
+ grant_type: "authorization_code",
64
+ client_id: params.app.clientId,
65
+ code: params.code,
66
+ redirect_uri: params.app.redirectUri,
67
+ code_verifier: params.codeVerifier
68
+ }));
69
+ if (params.app.clientSecret) body.set("client_secret", params.app.clientSecret);
70
+ const response = await fetchFn(CHUTES_TOKEN_ENDPOINT, {
71
+ method: "POST",
72
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
73
+ body
74
+ });
75
+ if (!response.ok) {
76
+ const detail = await readResponseTextLimited(response, CHUTES_TOKEN_ERROR_BODY_LIMIT_BYTES).catch(() => "");
77
+ throw new Error(`Chutes token exchange failed: ${detail}`);
78
+ }
79
+ const data = await response.json();
80
+ const access = normalizeOptionalString(data.access_token);
81
+ const refresh = normalizeOptionalString(data.refresh_token);
82
+ const expires = resolveChutesExpiresAt(data.expires_in, now);
83
+ if (!access) throw new Error("Chutes token exchange returned no access_token");
84
+ if (!refresh) throw new Error("Chutes token exchange returned no refresh_token");
85
+ if (expires === void 0) throw new Error("Chutes token exchange returned invalid expires_in");
86
+ const info = await fetchChutesUserInfo({
87
+ accessToken: access,
88
+ fetchFn
89
+ });
90
+ return {
91
+ access,
92
+ refresh,
93
+ expires,
94
+ email: info?.username,
95
+ accountId: info?.sub,
96
+ clientId: params.app.clientId
97
+ };
98
+ }
99
+ /** Runs Chutes OAuth and returns refreshable stored credentials. */
100
+ async function loginChutes(params) {
101
+ const { verifier, challenge } = generatePkceVerifierChallenge();
102
+ const state = params.createState?.() ?? randomBytes(16).toString("hex");
103
+ const timeoutMs = params.timeoutMs ?? 180 * 1e3;
104
+ const url = buildAuthorizeUrl({
105
+ clientId: params.app.clientId,
106
+ redirectUri: params.app.redirectUri,
107
+ scopes: params.app.scopes,
108
+ state,
109
+ challenge
110
+ });
111
+ let codeAndState;
112
+ if (params.manual) {
113
+ await params.onAuth({ url });
114
+ params.onProgress?.("Waiting for redirect URL...");
115
+ codeAndState = parseManualOAuthInput(await params.onPrompt({
116
+ message: "Paste the redirect URL",
117
+ placeholder: `${params.app.redirectUri}?code=...&state=...`
118
+ }), state);
119
+ } else {
120
+ const redirect = parseRedirectUri(params.app.redirectUri);
121
+ const callback = waitForLocalOAuthCallback({
122
+ expectedState: state,
123
+ timeoutMs,
124
+ port: redirect.port,
125
+ callbackPath: redirect.pathname,
126
+ redirectUri: params.app.redirectUri,
127
+ successTitle: "Chutes OAuth complete",
128
+ hostname: redirect.hostname,
129
+ onProgress: params.onProgress
130
+ }).catch(async () => {
131
+ params.onProgress?.("OAuth callback not detected; paste redirect URL...");
132
+ return parseManualOAuthInput(await params.onPrompt({
133
+ message: "Paste the redirect URL",
134
+ placeholder: `${params.app.redirectUri}?code=...&state=...`
135
+ }), state);
136
+ });
137
+ await params.onAuth({ url });
138
+ codeAndState = await callback;
139
+ }
140
+ params.onProgress?.("Exchanging code for tokens...");
141
+ return await exchangeChutesCodeForTokens({
142
+ app: params.app,
143
+ code: codeAndState.code,
144
+ codeVerifier: verifier,
145
+ fetchFn: params.fetchFn
146
+ });
147
+ }
148
+ //#endregion
149
+ export { loginChutes };
@@ -0,0 +1,62 @@
1
+ import { CHUTES_BASE_URL, CHUTES_DEFAULT_MODEL_REF, CHUTES_MODEL_CATALOG, buildChutesModelDefinition } from "./models.js";
2
+ import { applyAgentDefaultModelPrimary, applyProviderConfigWithModelCatalogPreset } from "openclaw/plugin-sdk/provider-onboard";
3
+ //#region extensions/chutes/onboard.ts
4
+ /**
5
+ * Chutes onboarding config helpers for OAuth and API-key setup.
6
+ */
7
+ /**
8
+ * Apply Chutes provider configuration without changing the default model.
9
+ * Registers all catalog models and sets provider aliases (chutes-fast, etc.).
10
+ */
11
+ function applyChutesProviderConfig(cfg) {
12
+ return applyProviderConfigWithModelCatalogPreset(cfg, {
13
+ providerId: "chutes",
14
+ api: "openai-completions",
15
+ baseUrl: CHUTES_BASE_URL,
16
+ catalogModels: CHUTES_MODEL_CATALOG.map(buildChutesModelDefinition),
17
+ aliases: [
18
+ ...CHUTES_MODEL_CATALOG.map((model) => `chutes/${model.id}`),
19
+ {
20
+ modelRef: "chutes-fast",
21
+ alias: "chutes/zai-org/GLM-4.7-FP8"
22
+ },
23
+ {
24
+ modelRef: "chutes-vision",
25
+ alias: "chutes/chutesai/Mistral-Small-3.2-24B-Instruct-2506"
26
+ },
27
+ {
28
+ modelRef: "chutes-pro",
29
+ alias: "chutes/deepseek-ai/DeepSeek-V3.2-TEE"
30
+ }
31
+ ]
32
+ });
33
+ }
34
+ /**
35
+ * Apply Chutes provider configuration AND set Chutes as the default model.
36
+ */
37
+ function applyChutesConfig(cfg) {
38
+ const next = applyChutesProviderConfig(cfg);
39
+ return {
40
+ ...next,
41
+ agents: {
42
+ ...next.agents,
43
+ defaults: {
44
+ ...next.agents?.defaults,
45
+ model: {
46
+ primary: CHUTES_DEFAULT_MODEL_REF,
47
+ fallbacks: ["chutes/deepseek-ai/DeepSeek-V3.2-TEE", "chutes/Qwen/Qwen3-32B"]
48
+ },
49
+ imageModel: {
50
+ primary: "chutes/chutesai/Mistral-Small-3.2-24B-Instruct-2506",
51
+ fallbacks: ["chutes/chutesai/Mistral-Small-3.1-24B-Instruct-2503"]
52
+ }
53
+ }
54
+ }
55
+ };
56
+ }
57
+ /** Applies Chutes provider config and sets the default model for API-key auth. */
58
+ function applyChutesApiKeyConfig(cfg) {
59
+ return applyAgentDefaultModelPrimary(applyChutesProviderConfig(cfg), CHUTES_DEFAULT_MODEL_REF);
60
+ }
61
+ //#endregion
62
+ export { CHUTES_DEFAULT_MODEL_REF, applyChutesApiKeyConfig, applyChutesConfig, applyChutesProviderConfig };
@@ -0,0 +1,25 @@
1
+ import { CHUTES_BASE_URL, CHUTES_MODEL_CATALOG, buildChutesModelDefinition, discoverChutesModels } from "./models.js";
2
+ //#region extensions/chutes/provider-catalog.ts
3
+ /** Builds the static Chutes provider catalog from bundled model metadata. */
4
+ function buildStaticChutesProvider() {
5
+ return {
6
+ baseUrl: CHUTES_BASE_URL,
7
+ api: "openai-completions",
8
+ models: CHUTES_MODEL_CATALOG.map(buildChutesModelDefinition)
9
+ };
10
+ }
11
+ /**
12
+ * Build the Chutes provider with dynamic model discovery.
13
+ * Falls back to the static catalog on failure.
14
+ * Accepts an optional access token (API key or OAuth access token) for authenticated discovery.
15
+ */
16
+ async function buildChutesProvider(accessToken) {
17
+ const models = await discoverChutesModels(accessToken);
18
+ return {
19
+ baseUrl: CHUTES_BASE_URL,
20
+ api: "openai-completions",
21
+ models: models.length > 0 ? models : CHUTES_MODEL_CATALOG.map(buildChutesModelDefinition)
22
+ };
23
+ }
24
+ //#endregion
25
+ export { buildChutesProvider, buildStaticChutesProvider };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@openclaw/chutes-provider",
3
+ "version": "2026.6.9",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "@openclaw/chutes-provider",
9
+ "version": "2026.6.9"
10
+ }
11
+ }
12
+ }