modelweaver 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.
@@ -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,174 @@
1
+ # ModelWeaver
2
+
3
+ [![CI](https://github.com/kianwoon/modelweaver/actions/workflows/ci.yml/badge.svg)](https://github.com/kianwoon/modelweaver/actions/workflows/ci.yml)
4
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
+ [![GitHub stars](https://img.shields.io/github/stars/kianwoon/modelweaver?style=social)](https://github.com/kianwoon/modelweaver/stargazers)
6
+
7
+ Multi-provider model orchestration proxy for Claude Code. Route different agent roles (planning, coding, research, review) to different model providers based on what each model does best.
8
+
9
+ ## How It Works
10
+
11
+ 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, matches it to an agent tier (sonnet/opus/haiku), and routes to the best-fit provider with automatic fallback on failure.
12
+
13
+ ```
14
+ Claude Code ──→ ModelWeaver ──→ Anthropic (primary)
15
+ (localhost) ──→ OpenRouter (fallback)
16
+
17
+ Inspects model field
18
+ Routes by tier
19
+ Falls back on error
20
+ ```
21
+
22
+ ## Interactive Setup
23
+
24
+ The fastest way to get started — run the setup wizard:
25
+
26
+ ```bash
27
+ npx modelweaver init
28
+ ```
29
+
30
+ The wizard guides you through:
31
+ - Selecting and configuring providers (Anthropic, OpenRouter, Together AI, Google Vertex, Fireworks)
32
+ - Testing API keys to verify connectivity
33
+ - Setting up model routing (sonnet, opus, haiku tiers)
34
+ - Generating `modelweaver.yaml` and `.env` files
35
+
36
+ ## Quick Start
37
+
38
+ ### 1. Create a config file
39
+
40
+ ```bash
41
+ cp modelweaver.example.yaml modelweaver.yaml
42
+ ```
43
+
44
+ ```yaml
45
+ server:
46
+ port: 3456
47
+
48
+ providers:
49
+ anthropic:
50
+ baseUrl: https://api.anthropic.com
51
+ apiKey: ${ANTHROPIC_API_KEY}
52
+ openrouter:
53
+ baseUrl: https://openrouter.ai/api
54
+ apiKey: ${OPENROUTER_API_KEY}
55
+
56
+ routing:
57
+ sonnet:
58
+ - provider: anthropic
59
+ model: claude-sonnet-4-20250514
60
+ - provider: openrouter
61
+ model: anthropic/claude-sonnet-4
62
+ opus:
63
+ - provider: anthropic
64
+ model: claude-opus-4-20250514
65
+ - provider: openrouter
66
+ model: anthropic/claude-opus-4
67
+ haiku:
68
+ - provider: anthropic
69
+ model: claude-haiku-4-5-20251001
70
+ - provider: openrouter
71
+ model: anthropic/claude-haiku-4
72
+
73
+ tierPatterns:
74
+ sonnet: ["sonnet", "3-5-sonnet", "3.5-sonnet"]
75
+ opus: ["opus", "3-opus", "3.5-opus"]
76
+ haiku: ["haiku", "3-haiku", "3.5-haiku"]
77
+ ```
78
+
79
+ ### 2. Set provider API keys
80
+
81
+ ```bash
82
+ export ANTHROPIC_API_KEY=sk-ant-...
83
+ export OPENROUTER_API_KEY=sk-or-...
84
+ ```
85
+
86
+ ### 3. Start ModelWeaver
87
+
88
+ ```bash
89
+ npx modelweaver
90
+ ```
91
+
92
+ ```
93
+ ModelWeaver v0.1.0
94
+ Config: ./modelweaver.yaml
95
+ Listening: http://localhost:3456
96
+
97
+ Routes:
98
+ sonnet → anthropic (primary), openrouter (fallback)
99
+ opus → anthropic (primary), openrouter (fallback)
100
+ haiku → anthropic (primary), openrouter (fallback)
101
+ ```
102
+
103
+ ### 4. Point Claude Code to ModelWeaver
104
+
105
+ ```bash
106
+ export ANTHROPIC_BASE_URL=http://localhost:3456
107
+ export ANTHROPIC_API_KEY=unused-but-required
108
+ claude
109
+ ```
110
+
111
+ ## CLI Options
112
+
113
+ ```
114
+ npx modelweaver [options]
115
+
116
+ -p, --port <number> Server port (default: 3456)
117
+ -c, --config <path> Config file path (auto-detected)
118
+ -v, --verbose Enable debug logging (default: off)
119
+ -h, --help Show help
120
+ ```
121
+
122
+ ## Configuration
123
+
124
+ ### Config File Locations
125
+
126
+ Checked in order (first found wins):
127
+ 1. `./modelweaver.yaml` (project-local)
128
+ 2. `~/.modelweaver/config.yaml` (user-global)
129
+
130
+ ### Routing
131
+
132
+ Each model name is matched against `tierPatterns` using case-sensitive substring matching. The first tier whose patterns contain a match wins. The ordered list under that tier defines the provider fallback chain.
133
+
134
+ - **Provider chain order matters** — first provider is primary, rest are fallbacks
135
+ - **Model override** — use the `model` field to rewrite the model name per provider (different providers may use different model names)
136
+ - **Fallback triggers** — 429 (rate limit) and 5xx errors
137
+ - **No fallback on** — 4xx errors (bad request, auth failure, forbidden)
138
+
139
+ ### API Keys
140
+
141
+ API keys are stored as environment variables only. Config references them with `${VAR_NAME}` syntax. ModelWeaver validates all keys are set on startup and fails fast if any are missing.
142
+
143
+ ## How Claude Code Uses Model Tiers
144
+
145
+ Claude Code sends different model names for different agent roles:
146
+
147
+ | Agent Role | Model Tier | Typical Model Name |
148
+ |---|---|---|
149
+ | Main conversation, coding | Sonnet | `claude-sonnet-4-20250514` |
150
+ | Explore (codebase search) | Haiku | `claude-haiku-4-5-20251001` |
151
+ | Plan (analysis) | Sonnet | `claude-sonnet-4-20250514` |
152
+ | Complex subagents | Opus | `claude-opus-4-20250514` |
153
+
154
+ ModelWeaver uses the model name to determine which agent tier is calling, then routes accordingly.
155
+
156
+ ## Development
157
+
158
+ ```bash
159
+ # Install dependencies
160
+ npm install
161
+
162
+ # Run tests
163
+ npm test
164
+
165
+ # Run in dev mode
166
+ npm run dev
167
+
168
+ # Build for production
169
+ npm run build
170
+ ```
171
+
172
+ ## License
173
+
174
+ Apache-2.0
package/dist/index.js ADDED
@@ -0,0 +1,460 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { serve } from "@hono/node-server";
5
+
6
+ // src/server.ts
7
+ import { Hono } from "hono";
8
+
9
+ // src/router.ts
10
+ function matchTier(modelName, tierPatterns) {
11
+ for (const [tier, patterns] of tierPatterns) {
12
+ for (const pattern of patterns) {
13
+ if (modelName.includes(pattern)) {
14
+ return tier;
15
+ }
16
+ }
17
+ }
18
+ return null;
19
+ }
20
+ function buildRoutingChain(tier, routing) {
21
+ return routing.get(tier) || [];
22
+ }
23
+ function resolveRequest(model, requestId, config, rawBody) {
24
+ const tier = matchTier(model, config.tierPatterns);
25
+ if (!tier) return null;
26
+ return {
27
+ requestId,
28
+ model,
29
+ tier,
30
+ providerChain: buildRoutingChain(tier, config.routing),
31
+ startTime: Date.now(),
32
+ rawBody
33
+ };
34
+ }
35
+
36
+ // src/proxy.ts
37
+ var FORWARD_HEADERS = /* @__PURE__ */ new Set([
38
+ "anthropic-version",
39
+ "anthropic-beta",
40
+ "content-type",
41
+ "accept"
42
+ ]);
43
+ function isRetriable(status) {
44
+ return status === 429 || status >= 500;
45
+ }
46
+ function buildOutboundUrl(baseUrl, incomingPath) {
47
+ return `${baseUrl}${incomingPath}`;
48
+ }
49
+ function buildOutboundHeaders(incomingHeaders, provider, requestId) {
50
+ const headers = new Headers();
51
+ for (const name of FORWARD_HEADERS) {
52
+ const value = incomingHeaders.get(name);
53
+ if (value) headers.set(name, value);
54
+ }
55
+ headers.set("x-api-key", provider.apiKey);
56
+ headers.set("x-request-id", requestId);
57
+ try {
58
+ const url = new URL(provider.baseUrl);
59
+ headers.set("host", url.host);
60
+ } catch {
61
+ }
62
+ return headers;
63
+ }
64
+ async function forwardRequest(provider, entry, ctx, incomingRequest) {
65
+ const outgoingPath = incomingRequest.url.replace(/^https?:\/\/[^/]+/, "");
66
+ const url = buildOutboundUrl(provider.baseUrl, outgoingPath);
67
+ let body = ctx.rawBody;
68
+ const contentType = incomingRequest.headers.get("content-type") || "";
69
+ if (contentType.includes("application/json") && entry.model) {
70
+ try {
71
+ const parsed = JSON.parse(ctx.rawBody);
72
+ parsed.model = entry.model;
73
+ body = JSON.stringify(parsed);
74
+ } catch {
75
+ }
76
+ }
77
+ const headers = buildOutboundHeaders(incomingRequest.headers, provider, ctx.requestId);
78
+ headers.set("content-length", new TextEncoder().encode(body).byteLength.toString());
79
+ const controller = new AbortController();
80
+ const timeout = setTimeout(() => controller.abort(), provider.timeout);
81
+ try {
82
+ const response = await fetch(url, {
83
+ method: "POST",
84
+ headers,
85
+ body,
86
+ signal: controller.signal
87
+ });
88
+ clearTimeout(timeout);
89
+ return response;
90
+ } catch (error) {
91
+ clearTimeout(timeout);
92
+ const message = error instanceof DOMException && error.name === "AbortError" ? `Provider "${provider.name}" timed out after ${provider.timeout}ms` : `Provider "${provider.name}" connection failed: ${error.message}`;
93
+ return new Response(
94
+ JSON.stringify({
95
+ type: "error",
96
+ error: { type: "overloaded_error", message }
97
+ }),
98
+ { status: 502, headers: { "content-type": "application/json" } }
99
+ );
100
+ }
101
+ }
102
+ async function forwardWithFallback(providers, chain, ctx, incomingRequest, onAttempt) {
103
+ let lastResponse = null;
104
+ for (let i = 0; i < chain.length; i++) {
105
+ const entry = chain[i];
106
+ const provider = providers.get(entry.provider);
107
+ if (!provider) {
108
+ lastResponse = new Response(
109
+ JSON.stringify({
110
+ type: "error",
111
+ error: { type: "api_error", message: `Unknown provider: ${entry.provider}` }
112
+ }),
113
+ { status: 502, headers: { "content-type": "application/json" } }
114
+ );
115
+ continue;
116
+ }
117
+ onAttempt?.(entry.provider, i);
118
+ const response = await forwardRequest(provider, entry, ctx, incomingRequest);
119
+ lastResponse = response;
120
+ if (response.status >= 200 && response.status < 300) {
121
+ return response;
122
+ }
123
+ if (!isRetriable(response.status)) {
124
+ return response;
125
+ }
126
+ continue;
127
+ }
128
+ return new Response(
129
+ JSON.stringify({
130
+ type: "error",
131
+ error: { type: "overloaded_error", message: "All providers exhausted" }
132
+ }),
133
+ { status: 502, headers: { "content-type": "application/json" } }
134
+ );
135
+ }
136
+
137
+ // src/logger.ts
138
+ function createLogger(level) {
139
+ const levels = { debug: 0, info: 1, error: 2 };
140
+ function log(lvl, message, data) {
141
+ if (levels[lvl] < levels[level]) return;
142
+ const entry = {
143
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
144
+ level: lvl,
145
+ message,
146
+ ...data
147
+ };
148
+ process.stdout.write(JSON.stringify(entry) + "\n");
149
+ }
150
+ return {
151
+ info: (msg, data) => log("info", msg, data),
152
+ debug: (msg, data) => log("debug", msg, data),
153
+ error: (msg, data) => log("error", msg, data)
154
+ };
155
+ }
156
+
157
+ // src/server.ts
158
+ import { randomUUID } from "crypto";
159
+ function anthropicError(type, message, requestId) {
160
+ return new Response(
161
+ JSON.stringify({ type: "error", error: { type, message } }),
162
+ {
163
+ status: 502,
164
+ headers: {
165
+ "content-type": "application/json",
166
+ "x-request-id": requestId
167
+ }
168
+ }
169
+ );
170
+ }
171
+ function createApp(config, logLevel) {
172
+ const logger = createLogger(logLevel);
173
+ const app = new Hono();
174
+ app.post("/v1/messages", async (c) => {
175
+ const requestId = randomUUID();
176
+ let body;
177
+ try {
178
+ body = await c.req.json();
179
+ } catch {
180
+ return anthropicError("invalid_request_error", "Invalid JSON body", requestId);
181
+ }
182
+ const model = body.model;
183
+ if (!model) {
184
+ return anthropicError("invalid_request_error", "Missing 'model' field in request body", requestId);
185
+ }
186
+ const rawBody = JSON.stringify(body);
187
+ const ctx = resolveRequest(model, requestId, config, rawBody);
188
+ if (!ctx) {
189
+ logger.info("No tier match", { requestId, model });
190
+ return anthropicError(
191
+ "invalid_request_error",
192
+ `No routing tier matches model "${model}". Configured tiers: ${[...config.tierPatterns.keys()].join(", ")}`,
193
+ requestId
194
+ );
195
+ }
196
+ logger.info("Routing request", {
197
+ requestId,
198
+ model,
199
+ tier: ctx.tier,
200
+ providers: ctx.providerChain.map((e) => e.provider)
201
+ });
202
+ const response = await forwardWithFallback(
203
+ config.providers,
204
+ ctx.providerChain,
205
+ ctx,
206
+ c.req.raw,
207
+ (provider, index) => {
208
+ logger.info("Attempting provider", { requestId, provider, index, tier: ctx.tier });
209
+ }
210
+ );
211
+ const newHeaders = new Headers(response.headers);
212
+ newHeaders.set("x-request-id", requestId);
213
+ const finalResponse = new Response(response.body, {
214
+ status: response.status,
215
+ statusText: response.statusText,
216
+ headers: newHeaders
217
+ });
218
+ const latency = Date.now() - ctx.startTime;
219
+ logger.info("Request completed", {
220
+ requestId,
221
+ model,
222
+ tier: ctx.tier,
223
+ status: finalResponse.status,
224
+ latencyMs: latency
225
+ });
226
+ return finalResponse;
227
+ });
228
+ return app;
229
+ }
230
+
231
+ // src/config.ts
232
+ import { readFileSync, existsSync, statSync } from "fs";
233
+ import { join } from "path";
234
+ import { parse as parseYaml } from "yaml";
235
+ import { z } from "zod";
236
+ var providerSchema = z.object({
237
+ baseUrl: z.string().url(),
238
+ apiKey: z.string().min(1, "apiKey is required"),
239
+ timeout: z.number().default(3e4)
240
+ });
241
+ var routingEntrySchema = z.object({
242
+ provider: z.string(),
243
+ model: z.string().optional()
244
+ });
245
+ var rawConfigSchema = z.object({
246
+ server: z.object({
247
+ port: z.number().int().min(1).max(65535).default(3456),
248
+ host: z.string().default("localhost")
249
+ }).default({}),
250
+ providers: z.record(z.string(), providerSchema),
251
+ routing: z.record(z.string(), z.array(routingEntrySchema)),
252
+ tierPatterns: z.record(z.string(), z.array(z.string()))
253
+ });
254
+ function resolveEnvVars(value) {
255
+ return value.replace(/\$\{([^}]+)\}/g, (_, varName) => {
256
+ const envValue = process.env[varName];
257
+ if (envValue === void 0 || envValue === "") {
258
+ throw new Error(`Missing environment variable: ${varName}`);
259
+ }
260
+ return envValue;
261
+ });
262
+ }
263
+ function resolveAllEnvStrings(obj) {
264
+ if (typeof obj === "string") return resolveEnvVars(obj);
265
+ if (Array.isArray(obj)) return obj.map(resolveAllEnvStrings);
266
+ if (obj !== null && typeof obj === "object") {
267
+ const result = {};
268
+ for (const [key, val] of Object.entries(obj)) {
269
+ result[key] = resolveAllEnvStrings(val);
270
+ }
271
+ return result;
272
+ }
273
+ return obj;
274
+ }
275
+ function findConfigFile(cwd = process.cwd()) {
276
+ const localPath = join(cwd, "modelweaver.yaml");
277
+ if (existsSync(localPath)) return localPath;
278
+ const globalPath = join(
279
+ process.env.HOME || process.env.USERPROFILE || "",
280
+ ".modelweaver",
281
+ "config.yaml"
282
+ );
283
+ if (existsSync(globalPath)) return globalPath;
284
+ return null;
285
+ }
286
+ function loadConfig(configPath, cwd) {
287
+ let path = null;
288
+ if (configPath) {
289
+ if (existsSync(configPath)) {
290
+ try {
291
+ const stat = statSync(configPath);
292
+ if (stat.isDirectory()) {
293
+ path = findConfigFile(configPath);
294
+ } else {
295
+ path = configPath;
296
+ }
297
+ } catch {
298
+ path = configPath;
299
+ }
300
+ } else {
301
+ path = configPath;
302
+ }
303
+ }
304
+ if (!path) {
305
+ path = findConfigFile(cwd);
306
+ }
307
+ if (!path) {
308
+ throw new Error(
309
+ "No config file found. Create modelweaver.yaml in your project root or ~/.modelweaver/config.yaml"
310
+ );
311
+ }
312
+ const raw = readFileSync(path, "utf-8");
313
+ const parsed = parseYaml(raw);
314
+ const resolved = resolveAllEnvStrings(parsed);
315
+ const validated = rawConfigSchema.parse(resolved);
316
+ const providerNames = new Set(Object.keys(validated.providers));
317
+ for (const [tier, entries] of Object.entries(validated.routing)) {
318
+ for (const entry of entries) {
319
+ if (!providerNames.has(entry.provider)) {
320
+ throw new Error(
321
+ `Routing tier "${tier}" references unknown provider "${entry.provider}". Available: ${[...providerNames].join(", ")}`
322
+ );
323
+ }
324
+ }
325
+ if (!validated.tierPatterns[tier]) {
326
+ throw new Error(
327
+ `Routing tier "${tier}" has no entry in tierPatterns. Add patterns for this tier.`
328
+ );
329
+ }
330
+ }
331
+ const providers = /* @__PURE__ */ new Map();
332
+ for (const [name, p] of Object.entries(validated.providers)) {
333
+ providers.set(name, {
334
+ name,
335
+ baseUrl: p.baseUrl,
336
+ apiKey: p.apiKey,
337
+ timeout: p.timeout
338
+ });
339
+ }
340
+ const routing = /* @__PURE__ */ new Map();
341
+ for (const [tier, entries] of Object.entries(validated.routing)) {
342
+ routing.set(tier, entries);
343
+ }
344
+ const tierPatterns = /* @__PURE__ */ new Map();
345
+ for (const [tier, patterns] of Object.entries(validated.tierPatterns)) {
346
+ tierPatterns.set(tier, patterns);
347
+ }
348
+ const server = {
349
+ port: validated.server.port,
350
+ host: validated.server.host
351
+ };
352
+ const config = { server, providers, routing, tierPatterns };
353
+ return { config, configPath: path };
354
+ }
355
+
356
+ // src/index.ts
357
+ function parseArgs(argv) {
358
+ const args = { verbose: false, help: false };
359
+ for (let i = 2; i < argv.length; i++) {
360
+ switch (argv[i]) {
361
+ case "-p":
362
+ case "--port":
363
+ const portStr = argv[++i];
364
+ if (!portStr || isNaN(parseInt(portStr, 10))) {
365
+ console.error("Error: -p/--port requires a number");
366
+ process.exit(1);
367
+ }
368
+ args.port = parseInt(portStr, 10);
369
+ break;
370
+ case "-c":
371
+ case "--config":
372
+ const configPath = argv[++i];
373
+ if (!configPath) {
374
+ console.error("Error: -c/--config requires a path");
375
+ process.exit(1);
376
+ }
377
+ args.config = configPath;
378
+ break;
379
+ case "-v":
380
+ case "--verbose":
381
+ args.verbose = true;
382
+ break;
383
+ case "-h":
384
+ case "--help":
385
+ args.help = true;
386
+ break;
387
+ }
388
+ }
389
+ return args;
390
+ }
391
+ function printHelp() {
392
+ console.log(`
393
+ ModelWeaver \u2014 Multi-provider model orchestration proxy for Claude Code
394
+
395
+ Usage: modelweaver [command] [options]
396
+
397
+ Commands:
398
+ init Run interactive setup wizard
399
+
400
+ Options:
401
+ -p, --port <number> Server port (default: from config)
402
+ -c, --config <path> Config file path (auto-detected)
403
+ -v, --verbose Enable debug logging (default: off)
404
+ -h, --help Show this help
405
+
406
+ Config locations (first found wins):
407
+ ./modelweaver.yaml
408
+ ~/.modelweaver/config.yaml
409
+ `);
410
+ }
411
+ async function main() {
412
+ const args = parseArgs(process.argv);
413
+ try {
414
+ const dotenv = await import("dotenv");
415
+ dotenv.config();
416
+ } catch {
417
+ }
418
+ if (process.argv[2] === "init") {
419
+ const { runInit } = await import("./init-MY7XTTRV.js");
420
+ await runInit();
421
+ process.exit(0);
422
+ }
423
+ if (args.help) {
424
+ printHelp();
425
+ process.exit(0);
426
+ }
427
+ let config;
428
+ let configPath;
429
+ try {
430
+ const result = loadConfig(args.config);
431
+ config = result.config;
432
+ configPath = result.configPath;
433
+ } catch (error) {
434
+ console.error(`Config error: ${error.message}`);
435
+ process.exit(1);
436
+ }
437
+ const port = args.port || config.server.port;
438
+ const host = config.server.host;
439
+ const logLevel = args.verbose ? "debug" : "info";
440
+ const app = createApp(config, logLevel);
441
+ console.log(`
442
+ ModelWeaver v0.1.0`);
443
+ console.log(` Listening: http://${host}:${port}`);
444
+ console.log(` Config: ${configPath}
445
+ `);
446
+ console.log(" Routes:");
447
+ for (const [tier, entries] of config.routing) {
448
+ const providerList = entries.map((e, i) => `${e.provider}${i === 0 ? " (primary)" : " (fallback)"}`).join(", ");
449
+ console.log(` ${tier.padEnd(8)} \u2192 ${providerList}`);
450
+ }
451
+ console.log();
452
+ serve({ fetch: app.fetch, hostname: host, port });
453
+ const shutdown = () => {
454
+ console.log("\n Shutting down...");
455
+ process.exit(0);
456
+ };
457
+ process.on("SIGTERM", shutdown);
458
+ process.on("SIGINT", shutdown);
459
+ }
460
+ main();
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/init.ts
4
+ import prompts from "prompts";
5
+
6
+ // src/presets.ts
7
+ var PRESETS = [
8
+ {
9
+ id: "anthropic",
10
+ name: "Anthropic",
11
+ baseUrl: "https://api.anthropic.com",
12
+ envKey: "ANTHROPIC_API_KEY",
13
+ authType: "anthropic",
14
+ models: {
15
+ sonnet: "claude-sonnet-4-20250514",
16
+ opus: "claude-opus-4-20250514",
17
+ haiku: "claude-haiku-4-5-20251001"
18
+ }
19
+ },
20
+ {
21
+ id: "openrouter",
22
+ name: "OpenRouter",
23
+ baseUrl: "https://openrouter.ai/api",
24
+ envKey: "OPENROUTER_API_KEY",
25
+ authType: "bearer",
26
+ models: {
27
+ sonnet: "anthropic/claude-sonnet-4",
28
+ opus: "anthropic/claude-opus-4",
29
+ haiku: "anthropic/claude-haiku-4"
30
+ }
31
+ },
32
+ {
33
+ id: "together",
34
+ name: "Together AI",
35
+ baseUrl: "https://api.together.xyz",
36
+ envKey: "TOGETHER_API_KEY",
37
+ authType: "bearer",
38
+ models: {
39
+ sonnet: "meta-llama/Llama-3.3-70B-Instruct-Turbo",
40
+ opus: "meta-llama/Llama-3.3-70B-Instruct-Turbo",
41
+ haiku: "meta-llama/Llama-3.3-70B-Instruct-Turbo"
42
+ }
43
+ },
44
+ {
45
+ id: "vertex",
46
+ name: "Google Vertex",
47
+ baseUrl: "https://aiplatform.googleapis.com",
48
+ envKey: "GOOGLE_APPLICATION_CREDENTIALS",
49
+ authType: "bearer",
50
+ models: {
51
+ sonnet: "claude-sonnet-4@vertex",
52
+ opus: "claude-opus-4@vertex",
53
+ haiku: "claude-haiku-4@vertex"
54
+ }
55
+ },
56
+ {
57
+ id: "fireworks",
58
+ name: "Fireworks",
59
+ baseUrl: "https://api.fireworks.ai/inference/v1",
60
+ envKey: "FIREWORKS_API_KEY",
61
+ authType: "bearer",
62
+ models: {
63
+ sonnet: "accounts/fireworks/models/claude-sonnet-4",
64
+ opus: "accounts/fireworks/models/claude-opus-4",
65
+ haiku: "accounts/fireworks/models/claude-haiku-4"
66
+ }
67
+ }
68
+ ];
69
+ function getPresets() {
70
+ return PRESETS;
71
+ }
72
+ function getPreset(id) {
73
+ return PRESETS.find((p) => p.id === id);
74
+ }
75
+
76
+ // src/init.ts
77
+ import { stringify as stringifyYaml } from "yaml";
78
+ import { writeFileSync, existsSync, readFileSync } from "fs";
79
+ import { join } from "path";
80
+ var CANCEL = { onCancel: () => {
81
+ console.log("\n Setup cancelled. No files were changed.");
82
+ process.exit(0);
83
+ } };
84
+ var GREEN = "\x1B[32m";
85
+ var RED = "\x1B[31m";
86
+ var RESET = "\x1B[0m";
87
+ function check(msg) {
88
+ console.log(` ${GREEN}\u2713${RESET} ${msg}`);
89
+ }
90
+ function fail(msg) {
91
+ console.log(` ${RED}\u2717${RESET} ${msg}`);
92
+ }
93
+ async function testApiKey(baseUrl, apiKey, preset) {
94
+ const controller = new AbortController();
95
+ const timeout = setTimeout(() => controller.abort(), 5e3);
96
+ const headers = preset.authType === "anthropic" ? { "x-api-key": apiKey, "anthropic-version": "2023-06-01", "content-type": "application/json" } : { Authorization: `Bearer ${apiKey}`, "content-type": "application/json" };
97
+ try {
98
+ const res = await fetch(`${baseUrl}/v1/messages`, {
99
+ method: "POST",
100
+ headers,
101
+ body: JSON.stringify({ model: preset.models.sonnet, max_tokens: 1, messages: [{ role: "user", content: "hi" }] }),
102
+ signal: controller.signal
103
+ });
104
+ if (res.status === 401 || res.status === 403) return { ok: false, error: "Invalid API key" };
105
+ if (res.status === 200 || res.status === 400 || res.status === 429) return { ok: true };
106
+ return { ok: false, error: `Unexpected status ${res.status}` };
107
+ } catch (err) {
108
+ if (err.name === "AbortError") return { ok: false, error: "Request timed out" };
109
+ return { ok: false, error: "Network error \u2014 endpoint unreachable" };
110
+ } finally {
111
+ clearTimeout(timeout);
112
+ }
113
+ }
114
+ async function selectProviders() {
115
+ const allPresets = getPresets();
116
+ const { providerIds } = await prompts(
117
+ {
118
+ type: "multiselect",
119
+ name: "providerIds",
120
+ message: "Select providers to configure:",
121
+ choices: allPresets.map((p) => ({ title: p.name, value: p.id, description: p.baseUrl })),
122
+ min: 1
123
+ },
124
+ CANCEL
125
+ );
126
+ return providerIds;
127
+ }
128
+ async function configureProvider(id) {
129
+ const preset = getPreset(id);
130
+ if (!preset) {
131
+ console.error(` Error: Unknown provider "${id}". Skipping.`);
132
+ return null;
133
+ }
134
+ const { baseUrl } = await prompts(
135
+ { type: "text", name: "baseUrl", message: `[${preset.name}] Base URL:`, initial: preset.baseUrl },
136
+ CANCEL
137
+ );
138
+ const { apiKey } = await prompts(
139
+ { type: "password", name: "apiKey", message: `[${preset.name}] API key:` },
140
+ CANCEL
141
+ );
142
+ process.stdout.write(` Testing API key for ${preset.name}...`);
143
+ const result = await testApiKey(baseUrl, apiKey, preset);
144
+ process.stdout.write("\r" + " ".repeat(50) + "\r");
145
+ if (!result.ok) {
146
+ fail(`${preset.name}: ${result.error}`);
147
+ const { retry } = await prompts(
148
+ { type: "confirm", name: "retry", message: "Retry?", initial: true },
149
+ CANCEL
150
+ );
151
+ if (retry) return configureProvider(id);
152
+ console.log(` ${RED}Warning:${RESET} ${preset.name} will be skipped \u2014 incomplete configuration.`);
153
+ return null;
154
+ }
155
+ check(`${preset.name} API key accepted`);
156
+ return { id, name: preset.name, baseUrl, envKey: preset.envKey, apiKey, models: preset.models };
157
+ }
158
+ async function configureRouting(providers) {
159
+ const tiers = ["sonnet", "opus", "haiku"];
160
+ const routing = {};
161
+ for (const tier of tiers) {
162
+ const choices = providers.map((p) => ({ title: p.name, value: p.id }));
163
+ const { primaryId } = await prompts(
164
+ { type: "select", name: "primaryId", message: `[${tier}] Primary provider:`, choices },
165
+ CANCEL
166
+ );
167
+ const primary = providers.find((p) => p.id === primaryId);
168
+ const { modelName } = await prompts(
169
+ { type: "text", name: "modelName", message: `[${tier}] Model name:`, initial: primary.models[tier] },
170
+ CANCEL
171
+ );
172
+ const entries = [{ provider: primary.id, model: modelName }];
173
+ const { addFallbacks } = await prompts(
174
+ { type: "confirm", name: "addFallbacks", message: `Add fallback providers for ${tier}?`, initial: false },
175
+ CANCEL
176
+ );
177
+ if (addFallbacks) {
178
+ const fallbackChoices = providers.filter((p) => p.id !== primary.id).map((p) => ({ title: p.name, value: p.id }));
179
+ const { fallbackIds } = await prompts(
180
+ { type: "multiselect", name: "fallbackIds", message: `[${tier}] Fallback providers:`, choices: fallbackChoices, min: 1 },
181
+ CANCEL
182
+ );
183
+ for (const fid of fallbackIds) {
184
+ const fp = providers.find((p) => p.id === fid);
185
+ const { fallbackModel } = await prompts(
186
+ { type: "text", name: "fallbackModel", message: `[${tier}] Model name for ${fp.name}:`, initial: fp.models[tier] },
187
+ CANCEL
188
+ );
189
+ entries.push({ provider: fid, model: fallbackModel });
190
+ }
191
+ }
192
+ routing[tier] = entries;
193
+ }
194
+ return routing;
195
+ }
196
+ async function configureServer() {
197
+ const { port } = await prompts(
198
+ { type: "number", name: "port", message: "Server port:", initial: 3456 },
199
+ CANCEL
200
+ );
201
+ const { host } = await prompts(
202
+ { type: "text", name: "host", message: "Server host:", initial: "localhost" },
203
+ CANCEL
204
+ );
205
+ return { port, host };
206
+ }
207
+ function buildYamlConfig(providers, routing, server) {
208
+ const configObj = {
209
+ server,
210
+ providers: {},
211
+ routing,
212
+ tierPatterns: {
213
+ sonnet: ["sonnet"],
214
+ opus: ["opus"],
215
+ haiku: ["haiku"]
216
+ }
217
+ };
218
+ for (const p of providers) {
219
+ configObj.providers[p.id] = {
220
+ baseUrl: p.baseUrl,
221
+ apiKey: `\${${p.envKey}}`,
222
+ timeout: 3e4
223
+ };
224
+ }
225
+ return stringifyYaml(configObj);
226
+ }
227
+ function writeEnvFile(entries) {
228
+ const envPath = join(process.cwd(), ".env");
229
+ let existing = "";
230
+ if (existsSync(envPath)) {
231
+ existing = readFileSync(envPath, "utf-8");
232
+ }
233
+ const lines = existing ? [""] : [];
234
+ for (const entry of entries) {
235
+ const regex = new RegExp(`^${entry.envKey}=`, "m");
236
+ if (!regex.test(existing)) {
237
+ lines.push(`${entry.envKey}=${entry.apiKey}`);
238
+ }
239
+ }
240
+ if (lines.length === 0 || lines.length === 1 && lines[0] === "") return;
241
+ writeFileSync(envPath, existing + lines.join("\n") + "\n", { mode: 384 });
242
+ }
243
+ async function runInit() {
244
+ if (!process.stdin.isTTY) {
245
+ console.error("Error: modelweaver init requires an interactive terminal.");
246
+ process.exit(1);
247
+ }
248
+ let configured = [];
249
+ let routing;
250
+ let server;
251
+ let yaml;
252
+ while (true) {
253
+ process.stdout.write("\x1B[2J\x1B[H");
254
+ console.log(`
255
+ \x1B[1m\x1B[36m\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\u2550
256
+ \u2551 Welcome to ModelWeaver! \u2551
257
+ \u2551 \u2551
258
+ \u2551 This wizard will help you configure \u2551
259
+ \u2551 your multi-provider model proxy. \u2551
260
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m
261
+ `);
262
+ const selectedIds = await selectProviders();
263
+ configured = [];
264
+ for (const id of selectedIds) {
265
+ const provider = await configureProvider(id);
266
+ if (provider) configured.push(provider);
267
+ }
268
+ if (configured.length === 0) {
269
+ console.log(`
270
+ ${RED}No providers configured. Exiting.${RESET}
271
+ `);
272
+ process.exit(1);
273
+ }
274
+ console.log();
275
+ routing = await configureRouting(configured);
276
+ console.log();
277
+ server = await configureServer();
278
+ yaml = buildYamlConfig(configured, routing, server);
279
+ console.log(`
280
+ \x1B[1m Generated configuration:\x1B[0m
281
+ `);
282
+ console.log(yaml.split("\n").map((l) => ` ${l}`).join("\n"));
283
+ const { confirm } = await prompts(
284
+ { type: "confirm", name: "confirm", message: "Write this configuration?", initial: true },
285
+ CANCEL
286
+ );
287
+ if (confirm) break;
288
+ console.log("\n Restarting wizard...\n");
289
+ }
290
+ const configPath = join(process.cwd(), "modelweaver.yaml");
291
+ if (existsSync(configPath)) {
292
+ console.log(`
293
+ \u26A0 Warning: ${configPath} already exists and will be overwritten.
294
+ `);
295
+ const { overwrite } = await prompts({
296
+ type: "confirm",
297
+ name: "overwrite",
298
+ message: "Overwrite existing config?",
299
+ initial: false
300
+ }, { onCancel: () => {
301
+ console.log("\n Setup cancelled. No files were changed.");
302
+ process.exit(0);
303
+ } });
304
+ if (!overwrite) {
305
+ console.log("\n Setup cancelled. No files were changed.");
306
+ process.exit(0);
307
+ }
308
+ }
309
+ writeFileSync(configPath, yaml);
310
+ writeEnvFile(configured);
311
+ console.log(`
312
+ \x1B[1m\x1B[36m\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
313
+ \u2551 ModelWeaver is configured! \u2551
314
+ \u2551 \u2551
315
+ \u2551 To use with Claude Code: \u2551
316
+ \u2551 \u2551
317
+ \u2551 Terminal 1: \u2551
318
+ \u2551 modelweaver \u2551
319
+ \u2551 \u2551
320
+ \u2551 Terminal 2: \u2551
321
+ \u2551 export ANTHROPIC_BASE_URL=\\ \u2551
322
+ \u2551 http://localhost:${String(server.port).padEnd(20)}\u2551
323
+ \u2551 claude \u2551
324
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\x1B[0m
325
+ `);
326
+ }
327
+ export {
328
+ runInit,
329
+ testApiKey
330
+ };
@@ -0,0 +1,33 @@
1
+ server:
2
+ port: 3456
3
+ host: localhost
4
+
5
+ providers:
6
+ anthropic:
7
+ baseUrl: https://api.anthropic.com
8
+ apiKey: ${ANTHROPIC_API_KEY}
9
+ openrouter:
10
+ baseUrl: https://openrouter.ai/api
11
+ apiKey: ${OPENROUTER_API_KEY}
12
+
13
+ routing:
14
+ sonnet:
15
+ - provider: anthropic
16
+ model: claude-sonnet-4-20250514
17
+ - provider: openrouter
18
+ model: anthropic/claude-sonnet-4
19
+ opus:
20
+ - provider: anthropic
21
+ model: claude-opus-4-20250514
22
+ - provider: openrouter
23
+ model: anthropic/claude-opus-4
24
+ haiku:
25
+ - provider: anthropic
26
+ model: claude-haiku-4-5-20251001
27
+ - provider: openrouter
28
+ model: anthropic/claude-haiku-4
29
+
30
+ tierPatterns:
31
+ sonnet: ["sonnet", "3-5-sonnet", "3.5-sonnet"]
32
+ opus: ["opus", "3-opus", "3.5-opus"]
33
+ haiku: ["haiku", "3-haiku", "3.5-haiku"]
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "modelweaver",
3
+ "version": "0.1.0",
4
+ "description": "Multi-provider model orchestration proxy for Claude Code",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "bin": {
8
+ "modelweaver": "dist/index.js",
9
+ "mw": "dist/index.js"
10
+ },
11
+ "scripts": {
12
+ "dev": "tsx src/index.ts",
13
+ "build": "tsup",
14
+ "test": "vitest run",
15
+ "test:watch": "vitest"
16
+ },
17
+ "dependencies": {
18
+ "hono": "^4.7.0",
19
+ "@hono/node-server": "^1.13.0",
20
+ "yaml": "^2.7.0",
21
+ "zod": "^3.24.0",
22
+ "dotenv": "^16.4.0",
23
+ "prompts": "^2.4.1"
24
+ },
25
+ "devDependencies": {
26
+ "typescript": "^5.7.0",
27
+ "tsx": "^4.19.0",
28
+ "tsup": "^8.3.0",
29
+ "vitest": "^3.0.0",
30
+ "@types/node": "^22.0.0",
31
+ "@types/prompts": "^2.4.9"
32
+ },
33
+ "engines": {
34
+ "node": ">=18"
35
+ }
36
+ }