@kianwoon/modelweaver 0.3.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.
@@ -0,0 +1,126 @@
1
+ # Contributing to ModelWeaver
2
+
3
+ Thanks for your interest in contributing. This guide covers what you need to get started.
4
+
5
+ ## Prerequisites
6
+
7
+ - **Node.js** >= 18 (ESM is required)
8
+ - **npm** (bundled with Node.js)
9
+
10
+ ## Setup
11
+
12
+ 1. Fork the repository and clone your fork locally.
13
+ 2. Install dependencies:
14
+
15
+ ```bash
16
+ npm install
17
+ ```
18
+
19
+ 3. Verify everything works:
20
+
21
+ ```bash
22
+ npm test
23
+ npm run build
24
+ ```
25
+
26
+ ## Development
27
+
28
+ Start the dev server with hot reload:
29
+
30
+ ```bash
31
+ npm run dev
32
+ ```
33
+
34
+ To test against real providers, create a `modelweaver.yaml` in the project root (or run `npx modelweaver init` to use the interactive wizard). Set the required API keys as environment variables, then start the server. The config file is auto-detected.
35
+
36
+ ## Project Structure
37
+
38
+ ```
39
+ src/
40
+ index.ts CLI entry point -- arg parsing, server startup, graceful shutdown
41
+ server.ts Hono app setup, request routing, error handling
42
+ proxy.ts Request forwarding, SSE streaming, fallback chains
43
+ router.ts Model name to tier matching (sonnet/opus/haiku)
44
+ config.ts YAML config loading, env var resolution, Zod validation
45
+ types.ts TypeScript interfaces and shared types
46
+ logger.ts Structured logging (info/warn/error/debug)
47
+ presets.ts Provider templates used by the init wizard
48
+ init.ts Interactive setup wizard (prompts-based)
49
+ tests/
50
+ *.test.ts Vitest test files (one per source module)
51
+ helpers/ Shared test utilities (mock provider, etc.)
52
+ .github/workflows/
53
+ ci.yml CI pipeline: type check, build, test on Node 18/20/22
54
+ ```
55
+
56
+ ## Testing
57
+
58
+ Tests use Vitest. Run them with:
59
+
60
+ ```bash
61
+ npm test # single run
62
+ npm run test:watch # watch mode
63
+ ```
64
+
65
+ Test files live in `tests/` and mirror the source structure -- one `.test.ts` file per module. Shared helpers go in `tests/helpers/`. The `mock-provider` helper starts a local HTTP server that returns canned responses for integration tests.
66
+
67
+ When adding a feature, include tests that cover the happy path and relevant edge cases.
68
+
69
+ ## Building
70
+
71
+ ```bash
72
+ npm run build
73
+ ```
74
+
75
+ tsup bundles the source to `dist/` as ESM. The output is what gets published and what the CLI entry point references.
76
+
77
+ ## Code Style
78
+
79
+ - **TypeScript strict mode** is enabled. Do not use `any`.
80
+ - **ESM only** -- the project uses `"type": "module"`.
81
+ - **Import extensions**: use `.js` extensions for local imports:
82
+ ```typescript
83
+ import { foo } from './bar.js';
84
+ ```
85
+ - **Node built-ins**: use the `node:` prefix:
86
+ ```typescript
87
+ import { readFileSync } from 'node:fs';
88
+ ```
89
+ - **Config validation**: all config shapes are defined as Zod schemas in `config.ts`.
90
+ - **API keys**: never hardcode keys. Use the `${ENV_VAR}` syntax in config, resolved at runtime.
91
+ - No linter or formatter is configured yet, so follow the patterns you see in the existing code.
92
+
93
+ ## Pull Requests
94
+
95
+ 1. Branch off `main`.
96
+ 2. Make your changes and add tests.
97
+ 3. Ensure `npm test` and `npm run build` pass locally.
98
+ 4. Open a PR with a clear description of what changed and why.
99
+ 5. CI must pass before merge. The pipeline runs type checking, the build, and the full test suite on Node 18, 20, and 22.
100
+
101
+ Keep PRs focused. If a change spans multiple concerns, consider splitting into separate PRs.
102
+
103
+ ## Adding a New Provider
104
+
105
+ Adding a new provider is a single-step process. Open `src/presets.ts` and add a new entry to the `PRESETS` array following the `ProviderPreset` interface:
106
+
107
+ ```typescript
108
+ {
109
+ id: "my-provider", // machine-readable key used in config
110
+ name: "My Provider", // display name shown in the init wizard
111
+ baseUrl: "https://api.example.com",
112
+ envKey: "MY_PROVIDER_API_KEY", // suggested environment variable
113
+ authType: "bearer", // "bearer" or "anthropic"
114
+ models: {
115
+ sonnet: "model-id-for-sonnet-tier",
116
+ opus: "model-id-for-opus-tier",
117
+ haiku: "model-id-for-haiku-tier",
118
+ },
119
+ }
120
+ ```
121
+
122
+ The init wizard will automatically offer the new provider. No other files need to change.
123
+
124
+ ## License
125
+
126
+ By contributing, you agree that your code will be licensed under the [Apache-2.0](https://opensource.org/licenses/Apache-2.0) license.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,289 @@
1
+ <p align="center">
2
+ <img src="gui/icons/icon.png" alt="ModelWeaver" width="96" />
3
+ </p>
4
+
5
+ # ModelWeaver
6
+
7
+ Multi-provider model orchestration proxy for Claude Code. Route different agent roles to different model providers with automatic fallback, exact model routing, config hot-reload, and crash recovery.
8
+
9
+ [![CI](https://github.com/kianwoon/modelweaver/actions/workflows/ci.yml/badge.svg)](https://github.com/kianwoon/modelweaver/actions/workflows/ci.yml) [![CodeQL](https://github.com/kianwoon/modelweaver/actions/workflows/codeql.yml/badge.svg)](https://github.com/kianwoon/modelweaver/actions/workflows/codeql.yml) [![Release](https://github.com/kianwoon/modelweaver/actions/workflows/release.yml/badge.svg)](https://github.com/kianwoon/modelweaver/actions/workflows/release.yml) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![GitHub stars](https://img.shields.io/github/stars/kianwoon/modelweaver?style=social)](https://github.com/kianwoon/modelweaver/stargazers)
10
+
11
+
12
+ <img width="358" height="479" alt="Screenshot 2026-03-20 at 5 11 55 AM" src="https://github.com/user-attachments/assets/a973a707-0cd7-4701-8d19-f6cd028f6c56" />
13
+
14
+
15
+ ## How It Works
16
+
17
+ ModelWeaver sits between Claude Code and upstream model providers as a local HTTP proxy. It inspects the `model` field in each Anthropic Messages API request and routes it to the best-fit provider.
18
+
19
+ ```
20
+ Claude Code ──→ ModelWeaver ──→ Anthropic (primary)
21
+ (localhost) ──→ OpenRouter (fallback)
22
+
23
+ 1. Match exact model name (modelRouting)
24
+ 2. Match tier via substring (tierPatterns)
25
+ 3. Fallback on 429 / 5xx errors
26
+ ```
27
+
28
+ ## Features
29
+
30
+ - **Tier-based routing** — route by model family (sonnet/opus/haiku) using substring pattern matching
31
+ - **Exact model routing** — route specific model names to dedicated providers (checked first)
32
+ - **Automatic fallback** — transparent failover on rate limits (429) and server errors (5xx)
33
+ - **Model name rewriting** — each provider in the chain can use a different model name
34
+ - **Interactive setup wizard** — guided configuration with API key validation
35
+ - **Config hot-reload** — changes to config file are picked up automatically, no restart needed
36
+ - **Daemon mode** — run as a background process with start/stop/status/remove commands
37
+ - **Crash recovery** — auto-restarts on crash with rate limiting (max 5 restarts/60s)
38
+ - **Multiple auth types** — supports `x-api-key` (Anthropic) and `Bearer` token auth
39
+ - **Per-provider timeouts** — configurable timeout with AbortController
40
+ - **Structured logging** — JSON logs with request IDs for tracing
41
+ - **Env var substitution** — config references like `${API_KEY}` resolved from environment
42
+ - **Circuit breaker** — per-provider circuit breaker with closed/open/half-open states, prevents hammering unhealthy providers
43
+ - **Adaptive fallback** — on 429 rate limits, automatically races remaining providers simultaneously instead of sequential fallback
44
+ - **Connection pooling** — per-provider undici Agent dispatcher with configurable pool size, closes old agents on config reload
45
+ - **Health endpoint** — `/api/status` returns circuit breaker state and uptime
46
+ - **Desktop GUI** — native app with one-command launch (`modelweaver gui`), auto-downloads from GitHub Releases
47
+
48
+ ## Prerequisites
49
+
50
+ - **Node.js** 20 or later — [Install Node.js](https://nodejs.org)
51
+ - `npx` — included with Node.js (no separate install needed)
52
+
53
+ ## Installation
54
+
55
+ ModelWeaver requires no permanent install — `npx` downloads and runs it on the fly. But if you prefer a global install:
56
+
57
+ ```bash
58
+ npm install -g modelweaver
59
+ ```
60
+
61
+ After that, replace `npx modelweaver` with `modelweaver` in all commands below.
62
+
63
+ ## Quick Start
64
+
65
+ ### 1. Run the setup wizard
66
+
67
+ ```bash
68
+ npx modelweaver init
69
+ ```
70
+
71
+ The wizard guides you through:
72
+ - Selecting from 6 preset providers (Anthropic, OpenRouter, Together AI, GLM/Z.ai, Minimax, Fireworks)
73
+ - Testing API keys to verify connectivity
74
+ - Setting up model routing tiers
75
+ - Auto-configuring `~/.claude/settings.json` for Claude Code integration
76
+
77
+ ### 2. Start ModelWeaver
78
+
79
+ ```bash
80
+ # Foreground (see logs in terminal)
81
+ npx modelweaver
82
+
83
+ # Background daemon (auto-restarts on crash)
84
+ npx modelweaver start
85
+ ```
86
+
87
+ ### 3. Point Claude Code to ModelWeaver
88
+
89
+ ```bash
90
+ export ANTHROPIC_BASE_URL=http://localhost:3456
91
+ export ANTHROPIC_API_KEY=unused-but-required
92
+ claude
93
+ ```
94
+
95
+ ## CLI Commands
96
+
97
+ ```bash
98
+ npx modelweaver init # Interactive setup wizard
99
+ npx modelweaver start # Start as background daemon
100
+ npx modelweaver stop # Stop background daemon
101
+ npx modelweaver status # Show daemon status
102
+ npx modelweaver remove # Stop daemon + remove PID and log files
103
+ npx modelweaver gui # Launch desktop GUI (auto-downloads binary)
104
+ npx modelweaver [options] # Run in foreground
105
+ ```
106
+
107
+ ### CLI Options
108
+
109
+ ```
110
+ -p, --port <number> Server port (default: from config)
111
+ -c, --config <path> Config file path (auto-detected)
112
+ -v, --verbose Enable debug logging (default: off)
113
+ -h, --help Show help
114
+ ```
115
+
116
+ ## Daemon Mode
117
+
118
+ Run ModelWeaver as a background process that survives terminal closure and auto-recovers from crashes.
119
+
120
+ ```bash
121
+ npx modelweaver start # Start (forks monitor + daemon)
122
+ npx modelweaver status # Check if running
123
+ npx modelweaver stop # Graceful stop (SIGTERM → SIGKILL after 5s)
124
+ npx modelweaver remove # Stop + remove PID file + log file
125
+ ```
126
+
127
+ **How it works**: `start` forks a lightweight monitor process that owns the PID file. The monitor spawns the actual daemon worker. If the worker crashes, the monitor auto-restarts it after a 2-second delay (up to 5 restarts per 60-second window to prevent crash loops).
128
+
129
+ ```
130
+ modelweaver.pid → Monitor process (handles signals, watches child)
131
+ └── modelweaver.worker.pid → Daemon worker (runs HTTP server)
132
+ ```
133
+
134
+ **Files**:
135
+ - `~/.modelweaver/modelweaver.pid` — monitor PID
136
+ - `~/.modelweaver/modelweaver.worker.pid` — worker PID
137
+ - `~/.modelweaver/modelweaver.log` — daemon output log
138
+
139
+ ## Desktop GUI
140
+
141
+ ModelWeaver ships a native desktop GUI built with Tauri. No Rust toolchain needed — the binary is auto-downloaded from GitHub Releases.
142
+
143
+ ```bash
144
+ npx modelweaver gui
145
+ ```
146
+
147
+ First run downloads the latest binary for your platform (~10-30 MB). Subsequent launches use the cached version.
148
+
149
+ **Supported platforms:**
150
+
151
+ | Platform | Format |
152
+ |---|---|
153
+ | macOS (Apple Silicon) | `.dmg` |
154
+ | macOS (Intel) | `.dmg` |
155
+ | Linux (x86_64) | `.AppImage` |
156
+ | Windows (x86_64) | `.msi` |
157
+
158
+ **Cached files** are stored in `~/.modelweaver/gui/` with version tracking — new versions download automatically on the next `gui` launch.
159
+
160
+ ## Configuration
161
+
162
+ ### Config file locations
163
+
164
+ Checked in order (first found wins):
165
+ 1. `./modelweaver.yaml` (project-local)
166
+ 2. `~/.modelweaver/config.yaml` (user-global)
167
+
168
+ ### Full config schema
169
+
170
+ ```yaml
171
+ server:
172
+ port: 3456 # Server port (default: 3456)
173
+ host: localhost # Bind address (default: localhost)
174
+
175
+ providers:
176
+ anthropic:
177
+ baseUrl: https://api.anthropic.com
178
+ apiKey: ${ANTHROPIC_API_KEY} # Env var substitution
179
+ timeout: 30000 # Request timeout in ms (default: 30000)
180
+ poolSize: 10 # Connection pool size (default: varies by provider)
181
+ authType: anthropic # "anthropic" | "bearer" (default: anthropic)
182
+ openrouter:
183
+ baseUrl: https://openrouter.ai/api
184
+ apiKey: ${OPENROUTER_API_KEY}
185
+ authType: bearer
186
+ timeout: 60000
187
+
188
+ # Tier-based routing (substring pattern matching)
189
+ routing:
190
+ sonnet:
191
+ - provider: anthropic
192
+ model: claude-sonnet-4-20250514 # Optional: rewrite model name
193
+ - provider: openrouter
194
+ model: anthropic/claude-sonnet-4 # Fallback
195
+ opus:
196
+ - provider: anthropic
197
+ model: claude-opus-4-20250514
198
+ haiku:
199
+ - provider: anthropic
200
+ model: claude-haiku-4-5-20251001
201
+
202
+ # Pattern matching: model name includes any string → matched to tier
203
+ tierPatterns:
204
+ sonnet: ["sonnet", "3-5-sonnet", "3.5-sonnet"]
205
+ opus: ["opus", "3-opus", "3.5-opus"]
206
+ haiku: ["haiku", "3-haiku", "3.5-haiku"]
207
+
208
+ # Exact model name routing (checked FIRST, before tier patterns)
209
+ modelRouting:
210
+ "glm-5-turbo":
211
+ - provider: anthropic # Route to specific provider
212
+ "MiniMax-M2.7":
213
+ - provider: openrouter
214
+ model: minimax/MiniMax-M2.7 # With model name rewrite
215
+ ```
216
+
217
+ ### Routing priority
218
+
219
+ 1. **Exact model name** (`modelRouting`) — if the request model matches exactly, use that route
220
+ 2. **Tier pattern** (`tierPatterns` + `routing`) — substring match the model name against patterns, then use the tier's provider chain
221
+ 3. **No match** — returns 502 with a descriptive error listing configured tiers and model routes
222
+
223
+ ### Provider chain behavior
224
+
225
+ - **First provider is primary**, rest are fallbacks
226
+ - **Fallback triggers** on: 429 (rate limit), 5xx (server error), network timeout
227
+ - **Adaptive race mode** — when a 429 is received, remaining providers are raced simultaneously (not sequentially) for faster recovery
228
+ - **Circuit breaker** — providers that repeatedly fail are temporarily skipped (auto-recovers after cooldown)
229
+ - **No fallback on**: 4xx (bad request, auth failure, forbidden) — returned immediately
230
+ - **Model rewriting**: each provider entry can override the `model` field in the request body
231
+
232
+ ### Supported providers
233
+
234
+ | Provider | Auth Type | Base URL |
235
+ |---|---|---|
236
+ | Anthropic | `x-api-key` | `https://api.anthropic.com` |
237
+ | OpenRouter | Bearer | `https://openrouter.ai/api` |
238
+ | Together AI | Bearer | `https://api.together.xyz` |
239
+ | GLM (Z.ai) | `x-api-key` | `https://api.z.ai/api/anthropic` |
240
+ | Minimax | `x-api-key` | `https://api.minimax.io/anthropic` |
241
+ | Fireworks | Bearer | `https://api.fireworks.ai/inference/v1` |
242
+
243
+ Any OpenAI/Anthropic-compatible API works — just set `baseUrl` and `authType` appropriately.
244
+
245
+ ### Config hot-reload
246
+
247
+ In daemon mode, ModelWeaver watches the config file for changes and reloads automatically (debounced 300ms). You can also send a manual reload signal:
248
+
249
+ ```bash
250
+ kill -SIGUSR1 $(cat ~/.modelweaver/modelweaver.pid)
251
+ ```
252
+
253
+ Or just re-run `npx modelweaver init` — it automatically signals the running daemon to reload.
254
+
255
+ ## API
256
+
257
+ ### Health check
258
+
259
+ ```bash
260
+ curl http://localhost:3456/api/status
261
+ ```
262
+
263
+ Returns circuit breaker state for all providers and server uptime.
264
+
265
+ ## How Claude Code Uses Model Tiers
266
+
267
+ Claude Code sends different model names for different agent roles:
268
+
269
+ | Agent Role | Model Tier | Typical Model Name |
270
+ |---|---|---|
271
+ | Main conversation, coding | Sonnet | `claude-sonnet-4-20250514` |
272
+ | Explore (codebase search) | Haiku | `claude-haiku-4-5-20251001` |
273
+ | Plan (analysis) | Sonnet | `claude-sonnet-4-20250514` |
274
+ | Complex subagents | Opus | `claude-opus-4-20250514` |
275
+
276
+ ModelWeaver uses the model name to determine which agent tier is calling, then routes accordingly.
277
+
278
+ ## Development
279
+
280
+ ```bash
281
+ npm install # Install dependencies
282
+ npm test # Run tests (174 tests)
283
+ npm run build # Build for production (tsup)
284
+ npm run dev # Run in dev mode (tsx)
285
+ ```
286
+
287
+ ## License
288
+
289
+ Apache-2.0
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ function s(t){let o={debug:0,info:1,warn:2,error:3};function n(e,r,g){if(o[e]<o[t])return;let i={timestamp:new Date().toISOString(),level:e,message:r,...g};process.stdout.write(JSON.stringify(i)+`
3
+ `)}return{info:(e,r)=>n("info",e,r),debug:(e,r)=>n("debug",e,r),warn:(e,r)=>n("warn",e,r),error:(e,r)=>n("error",e,r)}}export{s as a};
4
+ //# sourceMappingURL=chunk-OMWFRIHF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/logger.ts"],"sourcesContent":["// src/logger.ts\nexport type LogLevel = \"info\" | \"debug\" | \"warn\" | \"error\";\n\nexport interface Logger {\n info: (message: string, data?: Record<string, unknown>) => void;\n debug: (message: string, data?: Record<string, unknown>) => void;\n warn: (message: string, data?: Record<string, unknown>) => void;\n error: (message: string, data?: Record<string, unknown>) => void;\n}\n\nexport function createLogger(level: LogLevel): Logger {\n const levels = { debug: 0, info: 1, warn: 2, error: 3 } as const;\n\n function log(lvl: LogLevel, message: string, data?: Record<string, unknown>) {\n if (levels[lvl] < levels[level]) return;\n const entry = {\n timestamp: new Date().toISOString(),\n level: lvl,\n message,\n ...data,\n };\n process.stdout.write(JSON.stringify(entry) + \"\\n\");\n }\n\n return {\n info: (msg, data?) => log(\"info\", msg, data),\n debug: (msg, data?) => log(\"debug\", msg, data),\n warn: (msg, data?) => log(\"warn\", msg, data),\n error: (msg, data?) => log(\"error\", msg, data),\n };\n}\n"],"mappings":";AAUO,SAASA,EAAaC,EAAyB,CACpD,IAAMC,EAAS,CAAE,MAAO,EAAG,KAAM,EAAG,KAAM,EAAG,MAAO,CAAE,EAEtD,SAASC,EAAIC,EAAeC,EAAiBC,EAAgC,CAC3E,GAAIJ,EAAOE,CAAG,EAAIF,EAAOD,CAAK,EAAG,OACjC,IAAMM,EAAQ,CACZ,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,MAAOH,EACP,QAAAC,EACA,GAAGC,CACL,EACA,QAAQ,OAAO,MAAM,KAAK,UAAUC,CAAK,EAAI;AAAA,CAAI,CACnD,CAEA,MAAO,CACL,KAAM,CAACC,EAAKF,IAAUH,EAAI,OAAQK,EAAKF,CAAI,EAC3C,MAAO,CAACE,EAAKF,IAAUH,EAAI,QAASK,EAAKF,CAAI,EAC7C,KAAM,CAACE,EAAKF,IAAUH,EAAI,OAAQK,EAAKF,CAAI,EAC3C,MAAO,CAACE,EAAKF,IAAUH,EAAI,QAASK,EAAKF,CAAI,CAC/C,CACF","names":["createLogger","level","levels","log","lvl","message","data","entry","msg"]}
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import{spawn as N,execFile as W,execFileSync as $}from"child_process";import{access as L,readFile as E,writeFile as M,unlink as I,mkdir as G}from"fs/promises";import{join as f}from"path";import{dirname as U}from"path";import{fileURLToPath as _}from"url";import{createServer as O}from"net";function d(){return process.platform==="win32"}var m=f(process.env.HOME||process.env.USERPROFILE||"",".modelweaver"),D=null;function Q(n){D=n}function y(){return f(m,"modelweaver.pid")}function c(){return f(m,"modelweaver.log")}async function R(){try{await L(m)}catch{await G(m,{recursive:!0})}}async function Y(n){await R();try{await M(y(),`${n}
3
+ `,{flag:"wx"})}catch(e){if(e.code==="EEXIST")return;throw e}}async function w(){let n=y();try{let e=await E(n,"utf-8"),t=parseInt(e.trim(),10);return isNaN(t)?null:t}catch{return null}}async function u(){let n=y();try{await I(n)}catch{}}function b(){return f(m,"modelweaver.worker.pid")}async function Z(n){await R(),await M(b(),`${n}
4
+ `)}async function v(){let n=b();try{let e=await E(n,"utf-8"),t=parseInt(e.trim(),10);return isNaN(t)?null:t}catch{return null}}async function P(){let n=b();try{await I(n)}catch{}}function a(n){try{return process.kill(n,0),!0}catch{return!1}}function x(n){return new Promise(e=>{if(d()){try{W("netstat",["-ano"],{encoding:"utf-8",timeout:3e3},(t,r)=>{if(t){e([]);return}let i=[];for(let o of(r||"").split(`
5
+ `))if(o.includes("LISTENING")&&o.includes(`:${n}`)){let s=o.trim().split(/\s+/),l=parseInt(s[s.length-1],10);!isNaN(l)&&l>0&&i.push(l)}e(i)})}catch{e([]);return}return}W("lsof",["-ti",`:${n}`,"-sTCP:LISTEN"],{encoding:"utf-8",timeout:3e3},(t,r)=>{if(t){e([]);return}let i=(r||"").trim();e(i?i.split(`
6
+ `).map(Number).filter(o=>!isNaN(o)):[])})})}async function h(n){if(D!==null)return D;try{let{loadConfig:e}=await import("./config-FYJATRN4.js"),{config:t}=e(n??void 0);return t.server.port}catch{return 3456}}async function T(n,e=5e3){for(let r of n)try{process.kill(r,"SIGTERM")}catch{}let t=Date.now()+e;for(;Date.now()<t;){if(n.every(r=>!a(r)))return!0;await new Promise(r=>setTimeout(r,200))}for(let r of n)if(d())try{$("taskkill",["/F","/PID",String(r),"/T"],{stdio:"ignore"})}catch{}else try{process.kill(r,"SIGKILL")}catch{}return!0}async function C(n){let e=await w();if(e===null){let t=n??await h();if(t!==null&&t>0){let r=await x(t);if(r.length>0){let i=r.filter(o=>a(o));if(i.length>0)return{running:!0,pid:i[0],message:`ModelWeaver is running (PID ${i[0]}, detected on port ${t}; PID file missing)`}}}return{running:!1,message:"ModelWeaver is not running (no PID file found)"}}return a(e)?{running:!0,pid:e,message:`ModelWeaver is running (PID ${e})`}:(await u(),{running:!1,message:"ModelWeaver is not running (stale PID file cleaned up)"})}function A(n){return new Promise(e=>{let t=O();t.once("error",r=>{r.code==="EADDRINUSE"?e(!0):e(!1)}),t.once("listening",()=>{t.close(()=>e(!1))}),t.listen(n)})}async function ee(n,e,t){let r=await C(e);if(r.running)return{success:!1,pid:r.pid,message:`ModelWeaver is already running (PID ${r.pid})`,logPath:c()};let i=e??await h()??3456;if(await A(i))return{success:!1,message:`Port ${i} is already in use. Is ModelWeaver or another process running on it?`,logPath:c()};let o=_(import.meta.url),s=U(o),p=[f(s,"index.js"),"--monitor"];n&&p.push("--config",n),e&&p.push("--port",String(e)),t&&p.push("--verbose"),N(process.execPath,p,{detached:!0,stdio:"ignore",env:{...process.env}}).unref();let g;for(let S=0;S<20;S++){let k=await w();if(k!==null){g=k;break}await new Promise(F=>setTimeout(F,100))}return g?{success:!0,pid:g,message:`ModelWeaver started in background (PID ${g})`,logPath:c()}:{success:!1,message:"Daemon started but PID file was not created. Check logs at "+c(),logPath:c()}}async function K(n){let e=await w();if(e===null){let r=n??await h();if(r!==null&&r>0){let o=(await x(r)).filter(s=>a(s));if(o.length>0){let s=await v(),l=[...o];return s!==null&&a(s)&&!l.includes(s)&&l.push(s),await T(l),await P(),{success:!0,message:`ModelWeaver stopped (found on port ${r}, PIDs ${o.join(", ")}; PID file was missing)`}}}return{success:!1,message:"ModelWeaver is not running (no PID file found)"}}if(!a(e)){let r=await v();return r!==null&&a(r)&&(await T([r]),await P()),await u(),{success:!1,message:"ModelWeaver is not running (stale PID file cleaned up)"}}try{process.kill(e,"SIGTERM")}catch{return{success:!1,message:`Failed to stop daemon (PID ${e})`}}let t=Date.now()+5e3;for(;Date.now()<t;){if(!a(e))return await u(),{success:!0,message:`ModelWeaver stopped (PID ${e})`};await new Promise(r=>setTimeout(r,100))}try{d()?$("taskkill",["/F","/PID",String(e),"/T"],{stdio:"ignore"}):process.kill(e,"SIGKILL")}catch{}return await u(),await P(),{success:!0,message:`ModelWeaver force-stopped (PID ${e})`}}async function j(){let n=c();try{await I(n)}catch{}}async function ne(){let n=await K();return await j(),await P(),{success:n.success||n.message.includes("not running"),message:n.success?"ModelWeaver stopped and cleaned up (PID file + log file removed)":n.message.includes("not running")?"ModelWeaver is not running. Log file cleaned up.":n.message}}async function te(n){let e=await w();if(e===null){let t=n??await h();if(t!==null&&t>0){let i=(await x(t)).filter(o=>a(o));if(i.length>0){for(let o of i)try{d()?console.log(` Windows detected \u2014 reload signal not supported for PID ${o}. Use 'modelweaver stop && modelweaver start' instead.`):process.kill(o,"SIGHUP")}catch{}console.log(` Sent reload signal to ${i.length} process(es) on port ${t}.`);return}}console.log(" Daemon is not running.");return}if(!a(e)){await u(),console.log(" Daemon is not running (stale PID file cleaned up).");return}try{if(d()){let t=await v();t!==null?(process.kill(t,"SIGTERM"),console.log(` Killed worker (PID ${t}) on Windows \u2014 monitor will restart it.`)):console.log(" No worker PID file found \u2014 cannot reload.")}else process.kill(e,"SIGHUP"),console.log(` Sent reload signal to daemon (PID ${e}).`)}catch{console.log(" Failed to send reload signal \u2014 daemon may not be running.")}}function re(n,e=300){let t=null;return{reload(){t&&clearTimeout(t),t=setTimeout(()=>{t=null,n()},e)},dispose(){t&&(clearTimeout(t),t=null)}}}export{Q as a,y as b,c,R as d,Y as e,w as f,u as g,b as h,Z as i,v as j,P as k,a as l,x as m,h as n,C as o,A as p,ee as q,K as r,j as s,ne as t,te as u,re as v};
7
+ //# sourceMappingURL=chunk-P2HBWASF.js.map