agent402-model-provider 0.0.0-stage → 0.7.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/models.js ADDED
@@ -0,0 +1,122 @@
1
+ // Model list for OpenClaw, built from the gateway's own GET /v1/models so the
2
+ // plugin never carries a hand-typed catalog (a stale id would be a paid 502
3
+ // for the user). "auto" is always first: it is the routed tier and the
4
+ // recommended primary. Every other entry is an explicit model id with the
5
+ // tier's flat per-call price in its display name, because OpenClaw's cost
6
+ // fields are per token and Agent402 bills per call - those stay at zero so
7
+ // the UI never shows a made-up per-token figure.
8
+
9
+ export const AUTO_ID = "auto";
10
+
11
+ /** The metered route's own caps (llm-gateway-kit TIERS["v1-chat-metered"]),
12
+ * used when the catalog entry does not carry `meteredMaxInputChars` /
13
+ * `meteredMaxTokens` (gateways older than 2026-08-26). A metered call is
14
+ * validated against the METERED tier's limits, never the model's flat home
15
+ * tier - so a nano model that takes 12k chars flat takes 200k chars metered. */
16
+ export const METERED_MAX_INPUT_CHARS = 200_000;
17
+ export const METERED_MAX_TOKENS = 8192;
18
+
19
+ /** What a model must accept to be OpenClaw's primary. Measured on OpenClaw
20
+ * 2026.7.1 with the stock agent: ~33k chars of system prompt plus ~37k chars
21
+ * of tool schemas BEFORE the user's first word, and OpenClaw's own precheck
22
+ * refuses the turn ("Context overflow") when that exceeds the model's
23
+ * contextWindow. The routed `auto` tier caps input at 16k chars, so a primary
24
+ * of `agent402/auto` never completes a single turn - found by the real-install
25
+ * test, invisible to every stub. */
26
+ export const OPENCLAW_MIN_INPUT_CHARS = 80_000;
27
+
28
+ /** Linear trailing-slash strip (a regex like /\/+$/ is polynomial on long runs of "/"). */
29
+ export function stripTrailingSlashes(s) {
30
+ let str = String(s ?? ""); let end = str.length;
31
+ while (end > 0 && str.charCodeAt(end - 1) === 47) end--;
32
+ return str.slice(0, end);
33
+ }
34
+
35
+
36
+ /** The raw catalog entry -> { id, endpoint, tier, priceUsd, maxTokens, maxInputChars }.
37
+ *
38
+ * `pricing`: "metered" (default) routes every explicit model to the gateway's
39
+ * metered endpoint when the catalog advertises one (`x402.meteredEndpoint`):
40
+ * the 402 quotes each request from its body, from `meteredFromUsd`, instead
41
+ * of the tier's flat price - a short call costs a fraction of a cent, a long
42
+ * one pays for what it asks. "flat" keeps every model on its home tier.
43
+ * `auto` always stays on the routed tier (the metered route needs an explicit
44
+ * model). */
45
+ export function routesFromCatalog(catalog, { pricing = "metered" } = {}) {
46
+ const data = Array.isArray(catalog?.data) ? catalog.data : [];
47
+ const routes = new Map();
48
+ const metered = pricing !== "flat";
49
+ for (const m of data) {
50
+ const x = m?.x402;
51
+ if (!m?.id || !x?.endpoint || typeof x.priceUsd !== "number") continue;
52
+ if (String(m.id).endsWith("*")) continue; // family wildcard, not an id
53
+ const useMetered = metered && typeof x.meteredEndpoint === "string" && x.meteredEndpoint.startsWith("/");
54
+ routes.set(m.id, {
55
+ id: m.id,
56
+ endpoint: useMetered ? x.meteredEndpoint : x.endpoint,
57
+ tier: useMetered ? "v1-chat-metered" : (x.tier || null),
58
+ priceUsd: useMetered ? (Number(x.meteredFromUsd) || x.priceUsd) : x.priceUsd,
59
+ metered: useMetered,
60
+ maxTokens: useMetered ? (Number(x.meteredMaxTokens) || METERED_MAX_TOKENS) : (Number(x.maxTokens) || 1024),
61
+ maxInputChars: useMetered ? (Number(x.meteredMaxInputChars) || METERED_MAX_INPUT_CHARS) : (Number(x.maxInputChars) || 32_000),
62
+ stealth: !!x.stealth,
63
+ });
64
+ }
65
+ // The routed tier accepts a bare "auto" (model optional); expose it under
66
+ // that id whatever the catalog lists for the tier's own prefixes.
67
+ const autoRow = data.find((m) => m?.x402?.tier === "v1-chat-auto");
68
+ if (autoRow) {
69
+ routes.set(AUTO_ID, {
70
+ id: AUTO_ID, endpoint: autoRow.x402.endpoint, tier: "v1-chat-auto",
71
+ priceUsd: autoRow.x402.priceUsd, maxTokens: Number(autoRow.x402.maxTokens) || 1024,
72
+ maxInputChars: Number(autoRow.x402.maxInputChars) || 32_000, stealth: false,
73
+ });
74
+ }
75
+ return routes;
76
+ }
77
+
78
+ /** Preferred primaries, in order: capable tool-callers that are cheap when
79
+ * metered. Only consulted among routes that can hold OpenClaw's prompt. */
80
+ // Exported so the gateway's live-catalog guard (scripts/test-gateway-model-ids.js)
81
+ // fails the day any of these ids carries an expiration date upstream: the first
82
+ // pick is haiku-4.5, whose retirement floor is 2026-10-15 with no notice yet.
83
+ // google/gemini-2.5-flash left this list 2026-09-18: the live catalog stamps it
84
+ // expiration_date 2026-10-20, which is exactly what that guard was written to
85
+ // catch on its first run.
86
+ export const PRIMARY_PREFERENCE = ["anthropic/claude-haiku-4.5", "openai/gpt-4.1-mini", "openai/gpt-4o-mini"];
87
+
88
+ /** The route OpenClaw should make its primary model: the first preferred id
89
+ * that fits OPENCLAW_MIN_INPUT_CHARS, else the cheapest fitting one, else
90
+ * null (nothing in this catalog can hold OpenClaw's prompt - the caller says
91
+ * so instead of writing a primary that fails every turn). `auto` is never
92
+ * chosen: its input cap is the routed tier's. */
93
+ export function defaultPrimary(routes, { minInputChars = OPENCLAW_MIN_INPUT_CHARS } = {}) {
94
+ const fits = [...routes.values()].filter((r) => r.id !== AUTO_ID && !r.stealth && r.maxInputChars >= minInputChars);
95
+ if (!fits.length) return null;
96
+ for (const id of PRIMARY_PREFERENCE) { const r = fits.find((x) => x.id === id); if (r) return r; }
97
+ fits.sort((a, b) => a.priceUsd - b.priceUsd || a.id.localeCompare(b.id));
98
+ return fits[0];
99
+ }
100
+
101
+ const priceLabel = (usd) => (usd < 0.01 ? `$${usd.toFixed(3)}` : `$${usd.toFixed(2)}`);
102
+
103
+ /** OpenClaw `models[]` entries for a provider block. `auto` first. */
104
+ export function openclawModels(routes) {
105
+ const rows = [...routes.values()].filter((r) => !r.stealth);
106
+ rows.sort((a, b) => (a.id === AUTO_ID ? -1 : b.id === AUTO_ID ? 1 : a.priceUsd - b.priceUsd || a.id.localeCompare(b.id)));
107
+ return rows.map((r) => ({
108
+ id: r.id,
109
+ name: r.id === AUTO_ID ? `Agent402 auto (routed, ${priceLabel(r.priceUsd)}/call)` : r.metered ? `${r.id} (metered, from ${priceLabel(r.priceUsd)}/call)` : `${r.id} (${priceLabel(r.priceUsd)}/call)`,
110
+ reasoning: false,
111
+ input: ["text"],
112
+ // Flat per-call billing: OpenClaw's per-token cost display does not apply.
113
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
114
+ contextWindow: Math.min(Math.floor(r.maxInputChars / 4), 128_000),
115
+ maxTokens: r.maxTokens,
116
+ }));
117
+ }
118
+
119
+ /** OpenClaw ModelProviderConfig pointing at the local proxy. */
120
+ export function providerModelsConfig(baseUrl, routes) {
121
+ return { baseUrl: `${stripTrailingSlashes(baseUrl)}/v1`, api: "openai-completions", models: openclawModels(routes) };
122
+ }
@@ -0,0 +1,64 @@
1
+ {
2
+ "id": "agent402",
3
+ "name": "Agent402",
4
+ "description": "Agent402 model provider: an auto-routed tier at a flat per-call price and explicit frontier models priced per request, paid in USDC over x402 or with a prepaid credits key. Same key reaches 500+ pay-per-call tools.",
5
+ "activation": {
6
+ "onStartup": true
7
+ },
8
+ "enabledByDefault": true,
9
+ "providers": [
10
+ "agent402"
11
+ ],
12
+ "configSchema": {
13
+ "type": "object",
14
+ "additionalProperties": false,
15
+ "properties": {
16
+ "creditsKey": {
17
+ "type": "string",
18
+ "description": "Agent402 prepaid credits key (a402_...). Precedence: this, then AGENT402_CREDITS_KEY, then ~/.openclaw/agent402/credits.key."
19
+ },
20
+ "walletKey": {
21
+ "type": "string",
22
+ "description": "Optional EVM private key for x402 USDC payment (needs @x402/fetch + @x402/evm + viem installed). Precedence: this, then AGENT402_WALLET_KEY, then the wallet `setup` generates at ~/.openclaw/agent402/wallet.key."
23
+ },
24
+ "port": {
25
+ "type": "number",
26
+ "description": "Loopback proxy port (default 8412)."
27
+ },
28
+ "upstream": {
29
+ "type": "string",
30
+ "description": "Agent402 gateway base URL (default https://agent402.tools)."
31
+ },
32
+ "pricing": {
33
+ "type": "string",
34
+ "enum": [
35
+ "metered",
36
+ "flat"
37
+ ],
38
+ "description": "metered (default): explicit models pay a per-request quote; flat: every model on its flat tier."
39
+ },
40
+ "maxPerCallUsd": {
41
+ "type": [
42
+ "number",
43
+ "string"
44
+ ],
45
+ "description": "Per-call ceiling in USD for wallet (x402) payments, checked before signing and again on the signed amount before sending (default 5; 0 or \"off\" turns it off; a value that does not parse keeps the default). Also AGENT402_MAX_PER_CALL_USD."
46
+ },
47
+ "allowUncappedPayments": {
48
+ "type": "boolean",
49
+ "description": "Accepted for earlier configurations; 0 or \"off\" turns the ceiling off without it, so this changes nothing. Also AGENT402_ALLOW_UNCAPPED_PAYMENTS=true."
50
+ }
51
+ }
52
+ },
53
+ "uiHints": {
54
+ "creditsKey": {
55
+ "label": "Credits key",
56
+ "help": "Issued at https://agent402.tools/credits; that page says whether new keys are on sale",
57
+ "sensitive": true
58
+ },
59
+ "walletKey": {
60
+ "label": "Wallet key",
61
+ "sensitive": true
62
+ }
63
+ }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,94 @@
1
1
  {
2
2
  "name": "agent402-model-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Agent402 model provider for use with OpenClaw (Agentic Finance over x402 or MPP): an auto-routed tier at a flat per-call price and explicit LLM models priced per request, paid in USDC over x402, or with a prepaid credits key, through a local proxy. Zero dependencies; x402 wallet payment is an optional peer. Formerly agent402-openclaw.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ },
13
+ "./proxy": {
14
+ "types": "./proxy.d.ts",
15
+ "default": "./proxy.js"
16
+ },
17
+ "./models": {
18
+ "types": "./models.d.ts",
19
+ "default": "./models.js"
20
+ }
21
+ },
22
+ "bin": {
23
+ "agent402-model-provider": "cli.js"
24
+ },
25
+ "files": [
26
+ "index.js",
27
+ "index.d.ts",
28
+ "known-assets.js",
29
+ "provider.js",
30
+ "models.js",
31
+ "models.d.ts",
32
+ "proxy.js",
33
+ "proxy.d.ts",
34
+ "cli.js",
35
+ "openclaw.plugin.json",
36
+ "README.md"
37
+ ],
38
+ "openclaw": {
39
+ "extensions": [
40
+ "./index.js"
41
+ ],
42
+ "compat": {
43
+ "pluginApi": ">=2026.7.1"
44
+ },
45
+ "build": {
46
+ "openclawVersion": "2026.8.1"
47
+ },
48
+ "install": {
49
+ "minHostVersion": ">=2026.7.1",
50
+ "npmSpec": "agent402-model-provider"
51
+ }
52
+ },
53
+ "engines": {
54
+ "node": ">=18"
55
+ },
56
+ "scripts": {
57
+ "test": "node test.js"
58
+ },
59
+ "peerDependencies": {
60
+ "@x402/evm": ">=2.20.0 <3",
61
+ "@x402/fetch": ">=2.20.0 <3",
62
+ "viem": ">=2.48.11 <3"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@x402/evm": {
66
+ "optional": true
67
+ },
68
+ "@x402/fetch": {
69
+ "optional": true
70
+ },
71
+ "viem": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "keywords": [
76
+ "openclaw",
77
+ "openclaw-plugin",
78
+ "llm-router",
79
+ "x402",
80
+ "mpp",
81
+ "ai-agents",
82
+ "usdc",
83
+ "agent402",
84
+ "agentic-commerce"
85
+ ],
86
+ "author": "Cardhavok LLC (doing business as Havok Holdings LLC)",
87
+ "license": "MIT",
88
+ "repository": {
89
+ "type": "git",
90
+ "url": "git+https://github.com/MikeyPetrillo/Agent402.git",
91
+ "directory": "openclaw"
92
+ },
93
+ "homepage": "https://agent402.tools/guides/openclaw-model-provider"
94
+ }
package/provider.js ADDED
@@ -0,0 +1,45 @@
1
+ // The OpenClaw ProviderPlugin. Its `models` getter always points at the local
2
+ // proxy URL - the configured port before the proxy is up, the live one after -
3
+ // so OpenClaw persists a loopback baseUrl and never the remote gateway (which
4
+ // would 402 without the proxy's payment step in between).
5
+ import { providerModelsConfig, routesFromCatalog } from "./models.js";
6
+
7
+ // The MODEL PROVIDER id: what a user writes in openclaw.json ("agent402/auto").
8
+ // User-facing and stable - renaming it would break every existing config.
9
+ export const PROVIDER_ID = "agent402";
10
+ // The PLUGIN id, which is a different thing: OpenClaw keys plugins.entries by
11
+ // the MANIFEST id, and since 2026.8.1 it requires that id to equal the npm
12
+ // package name ("Plugin manifest id ... differs from npm package name ...").
13
+ // They were both "agent402", so nothing distinguished them until the host
14
+ // started checking. Writing config under the provider id while the host reads
15
+ // it under the manifest id is the same defect as the 2026-08-26 --port bug,
16
+ // where setup moved the baseUrl and the service kept reading the old key.
17
+ export const PLUGIN_ID = "agent402";
18
+ export const DEFAULT_PORT = 8412;
19
+
20
+ let activeProxy = null;
21
+ let cachedRoutes = null;
22
+ export function setActiveProxy(p) { activeProxy = p; }
23
+ export function getActiveProxy() { return activeProxy; }
24
+ export function setCachedRoutes(r) { cachedRoutes = r; }
25
+
26
+ /** Minimal offline route table so the provider registers even before /v1/models is read. */
27
+ export const BOOTSTRAP_ROUTES = routesFromCatalog({ data: [
28
+ { id: "auto", x402: { tier: "v1-chat-auto", endpoint: "/v1/auto/chat/completions", priceUsd: 0.01, maxTokens: 1024, maxInputChars: 32_000 } },
29
+ ] });
30
+
31
+ export function buildProvider({ port = DEFAULT_PORT } = {}) {
32
+ return {
33
+ id: PROVIDER_ID,
34
+ label: "Agent402",
35
+ docsPath: "https://agent402.tools/guides/openclaw-model-provider",
36
+ aliases: ["a402"],
37
+ envVars: ["AGENT402_CREDITS_KEY", "AGENT402_WALLET_KEY"],
38
+ get models() {
39
+ const base = activeProxy ? activeProxy.baseUrl : `http://127.0.0.1:${port}`;
40
+ return providerModelsConfig(base, cachedRoutes || BOOTSTRAP_ROUTES);
41
+ },
42
+ // No provider auth: the proxy carries the credits key or signs the payment.
43
+ auth: [],
44
+ };
45
+ }
package/proxy.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ // Type declarations for agent402-model-provider/proxy: the local OpenAI- and
2
+ // Anthropic-compatible proxy that pays each call.
3
+ import type { RouteTable } from "./models.js";
4
+
5
+ export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
6
+
7
+ export const DEFAULT_UPSTREAM: string;
8
+ export const PKG_VERSION: string;
9
+ export const MESSAGES_UPSTREAM_PATH: string;
10
+
11
+ export interface ProxyOptions {
12
+ /** Default "https://agent402.tools". */
13
+ upstream?: string;
14
+ /** A prepaid credits key (a402_...). */
15
+ creditsKey?: string | null;
16
+ /** An x402-paying fetch for wallet payment. */
17
+ payFetch?: FetchLike | null;
18
+ /** Plain fetch (tests inject one). */
19
+ fetch?: FetchLike;
20
+ /** 0 = an ephemeral port. */
21
+ port?: number;
22
+ /** Default 127.0.0.1 (loopback only: anyone who can reach the port spends the key). */
23
+ host?: string;
24
+ /** Pre-loaded routes; else read from the upstream. */
25
+ routes?: RouteTable | null;
26
+ /** "metered" (default): explicit models pay per-request quotes; "flat": home tiers. */
27
+ pricing?: "metered" | "flat";
28
+ log?: (message: string) => void;
29
+ }
30
+
31
+ export interface RunningProxy {
32
+ baseUrl: string;
33
+ port: number;
34
+ mode: "credits" | "x402" | "unpaid";
35
+ upstream: string;
36
+ pricing: "metered" | "flat";
37
+ stats(): { requests: number; forwarded: number; errors: number; startedAt: string };
38
+ /** Reread /v1/models; resolves to the model count. */
39
+ refreshModels(): Promise<number>;
40
+ close(): Promise<void>;
41
+ }
42
+
43
+ export function startProxy(opts?: ProxyOptions): Promise<RunningProxy>;
44
+ export function loadRoutes(upstream: string, fetchImpl?: FetchLike, opts?: { pricing?: "metered" | "flat" }): Promise<RouteTable>;
45
+ /** An upstream refusal carrying an x402 offer, in the OpenAI error shape; null for any other body. */
46
+ export function refusalAsOpenAIError(status: number, doc: unknown): { error: { message: string; type: string; code: string | null }; [key: string]: unknown } | null;
47
+ /** The same refusal in the Anthropic error shape; null for any other body. */
48
+ export function refusalAsAnthropicError(status: number, doc: unknown): { type: "error"; error: { type: string; message: string }; [key: string]: unknown } | null;