agent402-openclaw 0.2.0 → 0.2.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 CHANGED
@@ -11,15 +11,24 @@ Guide: https://agent402.tools/guides/openclaw-model-provider
11
11
 
12
12
  ```bash
13
13
  openclaw plugins install agent402-openclaw
14
- AGENT402_CREDITS_KEY=a402_... agent402-openclaw setup --write # key by env (or `--credits-key -` on stdin); buy one by card at https://agent402.tools/credits
14
+ AGENT402_CREDITS_KEY=a402_... npx agent402-openclaw setup --write # key by env (or `--credits-key -` on stdin); buy one by card at https://agent402.tools/credits
15
15
  openclaw gateway restart
16
16
  ```
17
17
 
18
- `setup` stores the key under `~/.openclaw/agent402/credits.key` (0600) and prints
19
- the `openclaw.json` block; add `--write` to merge it in (`agent402/auto` becomes
20
- the primary model). The plugin starts a loopback proxy (`127.0.0.1:8412`) that
18
+ (`openclaw plugins install` copies the plugin into `~/.openclaw/extensions` and
19
+ does not link its CLI, hence `npx`.) `setup` stores the key under
20
+ `~/.openclaw/agent402/credits.key` (0600) and prints the `openclaw.json` block;
21
+ add `--write` to merge it in. The primary model it writes is the cheapest
22
+ metered model that can hold OpenClaw's own prompt: OpenClaw sends roughly 70k
23
+ characters of system prompt and tool schemas before your first word, and the
24
+ routed `auto` tier caps input at 16k, so `auto` stays listed for short one-off
25
+ prompts but is never made primary (OpenClaw would refuse every turn as a
26
+ context overflow). The plugin starts a loopback proxy (`127.0.0.1:8412`) that
21
27
  pays Agent402 and forwards; OpenClaw only ever sees a local OpenAI-compatible URL.
22
28
 
29
+ Tested in CI against a real `openclaw@latest` install: plugin install, setup,
30
+ model listing, gateway boot and one agent turn (`test-real-install.js`).
31
+
23
32
  No OpenClaw? `agent402-openclaw proxy` runs the proxy alone; point any OpenAI
24
33
  client at `http://127.0.0.1:8412/v1` with model `auto`.
25
34
 
@@ -53,7 +62,7 @@ the key.
53
62
 
54
63
  ## Commands
55
64
 
56
- - `agent402-openclaw setup [--credits-key K | --credits-key - (stdin) | AGENT402_CREDITS_KEY env] [--write] [--port N]`
65
+ - `agent402-openclaw setup [--credits-key K | --credits-key - (stdin) | AGENT402_CREDITS_KEY env] [--write] [--port N] [--flat]`
57
66
  - `agent402-openclaw proxy [--port N] [--upstream URL]`
58
67
  - `agent402-openclaw doctor`
59
68
 
package/cli.js CHANGED
@@ -9,7 +9,7 @@ import { homedir } from "node:os";
9
9
  import { join } from "node:path";
10
10
  import { STATE_DIR, CREDITS_KEY_FILE, resolveCreditsKey, resolvePayFetch } from "./index.js";
11
11
  import { startProxy, loadRoutes, DEFAULT_UPSTREAM } from "./proxy.js";
12
- import { providerModelsConfig, stripTrailingSlashes } from "./models.js";
12
+ import { providerModelsConfig, stripTrailingSlashes, defaultPrimary, AUTO_ID, OPENCLAW_MIN_INPUT_CHARS } from "./models.js";
13
13
  import { DEFAULT_PORT, PROVIDER_ID } from "./provider.js";
14
14
 
15
15
  const args = process.argv.slice(2);
@@ -20,18 +20,26 @@ const out = (s) => process.stdout.write(s + "\n");
20
20
 
21
21
  /** The provider block for openclaw.json (JSON, so it can be merged; OpenClaw reads JSON5 which is a superset). */
22
22
  export function configBlock({ port = DEFAULT_PORT, routes }) {
23
+ const primary = defaultPrimary(routes);
23
24
  return {
24
- agents: { defaults: { model: { primary: `${PROVIDER_ID}/auto` } } },
25
+ agents: { defaults: { model: { primary: `${PROVIDER_ID}/${primary ? primary.id : AUTO_ID}` } } },
25
26
  models: { providers: { [PROVIDER_ID]: { ...providerModelsConfig(`http://127.0.0.1:${port}`, routes), timeoutSeconds: 120 } } },
26
27
  };
27
28
  }
28
29
 
29
- function mergeInto(target, block) {
30
+ function mergeInto(target, block, { port = DEFAULT_PORT } = {}) {
30
31
  const t = target && typeof target === "object" ? target : {};
31
32
  t.agents = t.agents || {}; t.agents.defaults = t.agents.defaults || {};
32
33
  t.agents.defaults.model = { ...(t.agents.defaults.model || {}), primary: block.agents.defaults.model.primary };
33
34
  t.models = t.models || {}; t.models.providers = t.models.providers || {};
34
35
  t.models.providers[PROVIDER_ID] = block.models.providers[PROVIDER_ID];
36
+ // The plugin service reads ITS port from plugins.entries.<id>.config, not from
37
+ // the provider baseUrl - a --port that only moved the baseUrl left the proxy
38
+ // on 8412 and OpenClaw dialing a port nobody listened on (real-install test).
39
+ if (port !== DEFAULT_PORT) {
40
+ t.plugins = t.plugins || {}; t.plugins.entries = t.plugins.entries || {};
41
+ t.plugins.entries[PROVIDER_ID] = { ...(t.plugins.entries[PROVIDER_ID] || {}), config: { ...(t.plugins.entries[PROVIDER_ID]?.config || {}), port } };
42
+ }
35
43
  return t;
36
44
  }
37
45
 
@@ -64,6 +72,10 @@ async function main() {
64
72
  let routes;
65
73
  try { routes = await loadRoutes(upstream, fetch, { pricing }); } catch (e) { console.error(`could not read ${upstream}/v1/models: ${e?.message || e}`); return 2; }
66
74
  const block = configBlock({ port, routes });
75
+ const primary = block.agents.defaults.model.primary;
76
+ if (primary === `${PROVIDER_ID}/${AUTO_ID}`) {
77
+ console.error(`WARNING: no model in this catalog (${pricing} pricing) accepts the ~${Math.round(OPENCLAW_MIN_INPUT_CHARS / 1000)}k chars OpenClaw sends before your first word; primary falls back to ${primary}, which will answer "Context overflow" on every turn. Rerun without --flat to use the metered route.`);
78
+ }
67
79
  const cfgPath = join(process.env.AGENT402_OPENCLAW_HOME || join(homedir(), ".openclaw"), "openclaw.json");
68
80
  if (has("--write")) {
69
81
  let existing = {};
@@ -77,10 +89,10 @@ async function main() {
77
89
  let mode = 0o600;
78
90
  try { if (existsSync(cfgPath)) mode = statSync(cfgPath).mode & 0o777; } catch { /* keep 0600 */ }
79
91
  const tmp = `${cfgPath}.${process.pid}.tmp`;
80
- writeFileSync(tmp, JSON.stringify(mergeInto(existing, block), null, 2) + "\n", { mode });
92
+ writeFileSync(tmp, JSON.stringify(mergeInto(existing, block, { port }), null, 2) + "\n", { mode });
81
93
  try { chmodSync(tmp, mode); } catch { /* best effort */ }
82
94
  renameSync(tmp, cfgPath);
83
- out(`wrote provider "${PROVIDER_ID}" + primary model ${PROVIDER_ID}/auto into ${cfgPath}; run: openclaw gateway restart`);
95
+ out(`wrote provider "${PROVIDER_ID}" + primary model ${primary} into ${cfgPath}; run: openclaw gateway restart`);
84
96
  } else {
85
97
  out(`add to ${cfgPath} (or rerun with --write):`);
86
98
  out(JSON.stringify(block, null, 2));
package/models.js CHANGED
@@ -8,6 +8,23 @@
8
8
 
9
9
  export const AUTO_ID = "auto";
10
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
+
11
28
  /** Linear trailing-slash strip (a regex like /\/+$/ is polynomial on long runs of "/"). */
12
29
  export function stripTrailingSlashes(s) {
13
30
  let str = String(s ?? ""); let end = str.length;
@@ -40,8 +57,8 @@ export function routesFromCatalog(catalog, { pricing = "metered" } = {}) {
40
57
  tier: useMetered ? "v1-chat-metered" : (x.tier || null),
41
58
  priceUsd: useMetered ? (Number(x.meteredFromUsd) || x.priceUsd) : x.priceUsd,
42
59
  metered: useMetered,
43
- maxTokens: Number(x.maxTokens) || 1024,
44
- maxInputChars: Number(x.maxInputChars) || 32_000,
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),
45
62
  stealth: !!x.stealth,
46
63
  });
47
64
  }
@@ -58,6 +75,23 @@ export function routesFromCatalog(catalog, { pricing = "metered" } = {}) {
58
75
  return routes;
59
76
  }
60
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
+ const PRIMARY_PREFERENCE = ["anthropic/claude-haiku-4.5", "openai/gpt-4.1-mini", "google/gemini-2.5-flash", "openai/gpt-4o-mini"];
81
+
82
+ /** The route OpenClaw should make its primary model: the first preferred id
83
+ * that fits OPENCLAW_MIN_INPUT_CHARS, else the cheapest fitting one, else
84
+ * null (nothing in this catalog can hold OpenClaw's prompt - the caller says
85
+ * so instead of writing a primary that fails every turn). `auto` is never
86
+ * chosen: its input cap is the routed tier's. */
87
+ export function defaultPrimary(routes, { minInputChars = OPENCLAW_MIN_INPUT_CHARS } = {}) {
88
+ const fits = [...routes.values()].filter((r) => r.id !== AUTO_ID && !r.stealth && r.maxInputChars >= minInputChars);
89
+ if (!fits.length) return null;
90
+ for (const id of PRIMARY_PREFERENCE) { const r = fits.find((x) => x.id === id); if (r) return r; }
91
+ fits.sort((a, b) => a.priceUsd - b.priceUsd || a.id.localeCompare(b.id));
92
+ return fits[0];
93
+ }
94
+
61
95
  const priceLabel = (usd) => (usd < 0.01 ? `$${usd.toFixed(3)}` : `$${usd.toFixed(2)}`);
62
96
 
63
97
  /** OpenClaw `models[]` entries for a provider block. `auto` first. */
@@ -6,5 +6,48 @@
6
6
  "onStartup": true
7
7
  },
8
8
  "enabledByDefault": true,
9
- "providers": ["agent402"]
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)."
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
+ }
41
+ },
42
+ "uiHints": {
43
+ "creditsKey": {
44
+ "label": "Credits key",
45
+ "help": "Buy by card at https://agent402.tools/credits",
46
+ "sensitive": true
47
+ },
48
+ "walletKey": {
49
+ "label": "Wallet key",
50
+ "sensitive": true
51
+ }
52
+ }
10
53
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent402-openclaw",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "OpenClaw model provider for Agent402: auto-routed and explicit LLM models at a flat per-call price, paid by card (prepaid credits key) or in USDC over x402 through a local proxy. Zero dependencies; x402 wallet payment is an optional peer.",
5
5
  "type": "module",
6
6
  "main": "index.js",