limitswap 0.0.0-stage → 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.
package/.npmignore ADDED
@@ -0,0 +1,2 @@
1
+ /node_modules
2
+
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 limitswap contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,158 @@
1
- # Temporary Holding Version
1
+ # limitswap
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ limitswap moves new Claude Code work to another of your accounts before the current account hits its usage limit. If no account has room, it tells the agent to stop at a safe point and names the reset time.
4
+
5
+ It is for people with more than one Claude subscription, for example a work account and a personal account. Each account is logged in under its own configuration folder (`CLAUDE_CONFIG_DIR`).
6
+
7
+ ## What it does
8
+
9
+ limitswap has three layers. Each layer talks to the next through a file or a command, so you can use one layer without the others.
10
+
11
+ | Layer | What it does | Interface |
12
+ |---|---|---|
13
+ | Reader | Reads each account's usage from the endpoint that Claude Code's `/usage` uses. One call per account at most every 2 minutes, shared by all readers. | `limitswap status` |
14
+ | Policy | Decides `stay`, `switch` (to another account) or `nap` (no account has room). | `limitswap pick` |
15
+ | Adapters | Act on the decision in one agent tool. | Claude Code hooks, `--print-dir` for wrappers |
16
+
17
+ The adapters in this repository:
18
+
19
+ - Claude Code under T3 Code: a hook blocks native subagents on a full account and tells the agent to start the work with T3's `delegate_task` on the other account's provider. A `delegate_task` aimed at a full account gets the same redirect.
20
+ - Plain Claude Code: no other account is reachable from inside a session, so the hook only warns.
21
+ - Any agent tool that starts `claude` as a command: `examples/claude-wrapper.sh` starts each new conversation on the account that `limitswap pick` names.
22
+
23
+ ## Install
24
+
25
+ limitswap is a single binary named `limitswap`, with no runtime dependencies. It has its own TLS, so it does not depend on the system's OpenSSL. Release builds exist for macOS (Apple silicon and Intel) and Linux (x86-64 and ARM64). Windows is not supported.
26
+
27
+ Choose one way to install it:
28
+
29
+ | Method | Command | Notes |
30
+ |---|---|---|
31
+ | Homebrew | `brew install wporoslo/tap/limitswap` | Updates with `brew upgrade`. |
32
+ | npm | `npm install -g limitswap` | Downloads the binary for your platform. Needs Node 14.18 or later. |
33
+ | Shell script | `curl --proto '=https' --tlsv1.2 -LsSf https://github.com/wporoslo/limitswap/releases/latest/download/limitswap-installer.sh \| sh` | Installs to `$XDG_BIN_HOME` or `~/.local/bin`. |
34
+ | Cargo | `cargo install --git https://github.com/wporoslo/limitswap --root ~/.local` | Builds on your machine. Needs Rust 1.89 or later. |
35
+ | From source | `git clone https://github.com/wporoslo/limitswap && cd limitswap && cargo build --release` | Then copy `target/release/limitswap` to a folder on your `PATH`. |
36
+
37
+ You can try commands with `npx limitswap status` before you install. Do not install the hooks from npx: npx runs a temporary copy, and the hooks need a binary that stays. `limitswap install-hooks` refuses a temporary copy and tells you what to do.
38
+
39
+ Then set it up:
40
+
41
+ ```sh
42
+ limitswap init # shows the accounts it found
43
+ limitswap init --write --failover # saves them and lets each account hand work to the others
44
+ limitswap status # reads real usage for every account
45
+ limitswap install-hooks # adds the hooks to every configured account's settings.json
46
+ ```
47
+
48
+ `limitswap init` looks for `~/.claude` and `~/.claude-*` configuration folders that hold a login. If two configuration folders hold the same login, it keeps one. Under T3 Code, it keeps the folder that a T3 provider uses.
49
+
50
+ `install-hooks` writes a backup of each `settings.json` before it changes it. To remove the hooks, run `limitswap install-hooks --uninstall`.
51
+
52
+ ## How it decides
53
+
54
+ If the 5-hour use of an account is at least `threshold_pct` (default 85), the account is hot. If its weekly use is at least `weekly_threshold_pct` (default 95), it is also hot.
55
+
56
+ A reading older than 10 minutes counts as hot from 10 points below the threshold. A reading older than one hour counts as unknown. A reading is never trusted to say "less used" just because it is old.
57
+
58
+ When the current account is hot, `pick` chooses among the accounts in its `failover` list. It prefers the account with the lowest known use, then an account with no reading. It never picks a hot account, or a configuration folder that holds the same login as the current one.
59
+
60
+ Failover is off until you turn it on. `limitswap init --write --failover` allows every direction. To allow one direction only, edit the configuration:
61
+
62
+ ```json
63
+ { "failover": { "work": ["personal"] } }
64
+ ```
65
+
66
+ Before you allow work to fail over to a personal account, make sure that your employer permits work code on that account.
67
+
68
+ ## Naps
69
+
70
+ If the current account is hot and no failover account has room, a nap starts. If another account has room, the session keeps working and sends new work there.
71
+
72
+ In a nap, the hook gives the agent a pause protocol once:
73
+
74
+ 1. Finish or safely stop the current step.
75
+ 2. Write a checkpoint file with the work done, the current state and the next steps.
76
+ 3. Schedule a resume.
77
+ 4. Tell the user the resume time and end the turn.
78
+
79
+ The resume time is the first reset of the current account or of a hot failover account, plus 3 minutes. If no reset time is known, the resume time is one hour after the nap starts.
80
+
81
+ Under T3 Code, the agent schedules the resume with T3's `schedule_task`. That task runs in the same thread even after the session ends. In plain Claude Code, the agent uses `CronCreate`. If the session ends, that wake-up stops too. `limitswap naps` lists every paused session with its checkpoint and a `claude --resume` command.
82
+
83
+ After the first notice, the agent gets short reminders only. When the account has room again, limitswap deletes the nap record.
84
+
85
+ ## Configuration
86
+
87
+ The file is `~/.config/limitswap/config.json` (or `$LIMITSWAP_CONFIG`).
88
+
89
+ | Key | Default | Meaning |
90
+ |---|---|---|
91
+ | `accounts` | from `limitswap init` | name to its configuration folder, `{"config_dir": ...}` |
92
+ | `failover` | `{}` | name to the list of names that can receive its work |
93
+ | `t3_providers` | read from T3 | name to T3 `providerInstanceId`. limitswap reads it from the T3 configuration file. Set it to override that file. |
94
+ | `threshold_pct` | 85 | 5-hour use that makes an account hot |
95
+ | `weekly_threshold_pct` | 95 | weekly use that makes an account hot |
96
+ | `poll_interval_s` | 120 | minimum seconds between endpoint calls per account |
97
+
98
+ Readings are stored in `~/.cache/limitswap/usage/` (or `$LIMITSWAP_STATE_DIR`).
99
+
100
+ ## Commands
101
+
102
+ ```sh
103
+ limitswap status [--json] [--refresh] # every account: state, 5h %, weekly %
104
+ limitswap pick --account work # JSON decision
105
+ limitswap pick --config-dir ~/.claude-work --print-dir # the folder to use, for wrappers
106
+ limitswap set work --pct 100 --minutes 30 # treat an account as full (testing, or by hand)
107
+ limitswap set work --clear
108
+ limitswap naps [--json] [--clear-due] # paused sessions; --clear-due deletes old records
109
+ ```
110
+
111
+ `limitswap set` changes the reading for the whole account. Every session on that account follows it, including sessions in other projects.
112
+
113
+ ## Limits
114
+
115
+ - The usage endpoint is not documented by Anthropic. It can change without notice. If it fails, limitswap keeps the last reading and then treats the account as unknown.
116
+ - limitswap reads access tokens and never refreshes them. A refresh rotates a token that a running Claude Code session owns. An account that sat idle until its token expired shows as unknown until you use it again.
117
+ - A running session keeps its account. Only new subagents, delegated tasks and new conversations move.
118
+ - On macOS, tokens are read from the login keychain. On other systems they come from `<config_dir>/.credentials.json`.
119
+ - The PostToolUse hook runs after every tool call. Each run takes about 10 ms on macOS. About 8 ms of that is the cost of starting any process.
120
+ - If the hook fails for any reason, it lets the call through and writes the error to `~/.cache/limitswap/hook.log`.
121
+
122
+ ## Develop
123
+
124
+ ```sh
125
+ cargo test # unit tests, each in its own temporary home
126
+ cargo build --release # target/release/limitswap
127
+ tests/parity.sh # compare with the Python version from git history
128
+ ```
129
+
130
+ ### Release
131
+
132
+ [dist](https://github.com/axodotdev/cargo-dist) builds and publishes releases. The configuration is in `dist-workspace.toml`, and the workflow is in `.github/workflows/release.yml`.
133
+
134
+ Before the first release, set up these things once:
135
+
136
+ 1. Create the GitHub repository `wporoslo/limitswap` and push this repository to it.
137
+ 2. Create the tap repository `wporoslo/homebrew-tap`.
138
+ 3. Add two repository secrets. `HOMEBREW_TAP_TOKEN` is a GitHub token that can push to the tap. `NPM_TOKEN` is an npm automation token that can publish the `limitswap` package.
139
+
140
+ To release a version, set it in `Cargo.toml`, commit, and push a tag:
141
+
142
+ ```sh
143
+ git tag v0.2.0 && git push origin v0.2.0
144
+ ```
145
+
146
+ The workflow then builds the four binaries and creates the GitHub release. It also updates the Homebrew formula and publishes the npm package.
147
+
148
+ To see the artifacts without publishing, run `dist build --artifacts=all`. The files go to `target/distrib/`.
149
+
150
+ ### History
151
+
152
+ Before version 0.3, the tool was called claude-baton and the command was `baton`. Version 0.1 was written in Python. It is in the git history at commit `7fb8b48`. The Rust version keeps its commands, file formats and hook output.
153
+
154
+ If you used claude-baton, install limitswap and run `limitswap install-hooks` once. It removes the old `baton` hooks. On its first run, limitswap moves `~/.config/claude-baton` and `~/.cache/claude-baton` to the new folder names, if the new folders do not exist yet. The environment variables now start with `LIMITSWAP_` instead of `BATON_`.
155
+
156
+ ## Credits
157
+
158
+ The usage endpoint request and the parsing of its response come from [claude-powernap](https://github.com/asiagenawi/claude-powernap) by asiagenawi, under the MIT license. The full notice is in `THIRD-PARTY-NOTICES`.
@@ -0,0 +1,27 @@
1
+ This project contains code adapted from claude-powernap
2
+ (https://github.com/asiagenawi/claude-powernap): the usage endpoint
3
+ request and the parsing of its response in src/usage.rs.
4
+
5
+ claude-powernap is distributed under the following license:
6
+
7
+ MIT License
8
+
9
+ Copyright (c) 2026 asiagenawi
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
@@ -0,0 +1,348 @@
1
+ const {
2
+ createWriteStream,
3
+ existsSync,
4
+ mkdirSync,
5
+ mkdtemp,
6
+ rmSync,
7
+ } = require("fs");
8
+ const { join, sep } = require("path");
9
+ const { spawnSync } = require("child_process");
10
+ const { tmpdir } = require("os");
11
+
12
+ const https = require("node:https");
13
+ const http = require("node:http");
14
+
15
+ const tmpDir = tmpdir();
16
+
17
+ const error = (msg) => {
18
+ console.error(msg);
19
+ process.exit(1);
20
+ };
21
+
22
+ function getProxyForUrl(urlString) {
23
+ const url = new URL(urlString);
24
+ const isHttps = url.protocol === "https:";
25
+
26
+ const noProxy = process.env.NO_PROXY || process.env.no_proxy || "";
27
+ if (noProxy === "*") return null;
28
+ if (noProxy) {
29
+ const hostname = url.hostname.toLowerCase();
30
+ const noProxyList = noProxy.split(",").map((s) => s.trim().toLowerCase());
31
+ for (const entry of noProxyList) {
32
+ if (hostname === entry || hostname.endsWith("." + entry)) {
33
+ return null;
34
+ }
35
+ }
36
+ }
37
+
38
+ const proxyEnv = isHttps
39
+ ? process.env.HTTPS_PROXY || process.env.https_proxy
40
+ : process.env.HTTP_PROXY || process.env.http_proxy;
41
+
42
+ if (!proxyEnv) return null;
43
+
44
+ const proxyUrl = new URL(proxyEnv);
45
+
46
+ let auth = null;
47
+ if (proxyUrl.username || proxyUrl.password) {
48
+ auth = `${proxyUrl.username}:${proxyUrl.password}`;
49
+ }
50
+
51
+ return {
52
+ hostname: proxyUrl.hostname,
53
+ port: proxyUrl.port || (proxyUrl.protocol === "https:" ? 443 : 80),
54
+ auth: auth,
55
+ };
56
+ }
57
+
58
+ function connectThroughProxy(proxy, target) {
59
+ return new Promise((resolve, reject) => {
60
+ const headers = {};
61
+ if (proxy.auth) {
62
+ headers["Proxy-Authorization"] =
63
+ "Basic " + Buffer.from(proxy.auth).toString("base64");
64
+ }
65
+
66
+ const connectReq = http.request({
67
+ hostname: proxy.hostname,
68
+ port: proxy.port,
69
+ method: "CONNECT",
70
+ path: `${target.hostname}:${target.port || 443}`,
71
+ headers,
72
+ });
73
+ connectReq.on("connect", (res, socket) => {
74
+ if (res.statusCode === 200) {
75
+ resolve(socket);
76
+ } else {
77
+ reject(new Error(`Proxy CONNECT failed with status ${res.statusCode}`));
78
+ }
79
+ });
80
+ connectReq.on("error", reject);
81
+ connectReq.end();
82
+ });
83
+ }
84
+
85
+ function download(urlString, maxRedirects) {
86
+ if (maxRedirects === undefined) maxRedirects = 5;
87
+ return new Promise((resolve, reject) => {
88
+ if (maxRedirects < 0) {
89
+ return reject(new Error("Too many redirects"));
90
+ }
91
+
92
+ const parsed = new URL(urlString);
93
+ const isHttps = parsed.protocol === "https:";
94
+ const mod = isHttps ? https : http;
95
+ const proxy = getProxyForUrl(urlString);
96
+
97
+ const doRequest = (extraOptions) => {
98
+ const options = Object.assign(
99
+ {
100
+ hostname: parsed.hostname,
101
+ port: parsed.port || (isHttps ? 443 : 80),
102
+ path: parsed.pathname + parsed.search,
103
+ method: "GET",
104
+ headers: { "User-Agent": "cargo-dist-npm-installer" },
105
+ },
106
+ extraOptions || {},
107
+ );
108
+
109
+ if (proxy && !isHttps) {
110
+ // HTTP through HTTP proxy: request the full URL via the proxy
111
+ options.hostname = proxy.hostname;
112
+ options.port = proxy.port;
113
+ options.path = urlString;
114
+ if (proxy.auth) {
115
+ options.headers["Proxy-Authorization"] =
116
+ "Basic " + Buffer.from(proxy.auth).toString("base64");
117
+ }
118
+ }
119
+
120
+ const req = mod.request(options, (res) => {
121
+ if (
122
+ res.statusCode >= 300 &&
123
+ res.statusCode < 400 &&
124
+ res.headers.location
125
+ ) {
126
+ res.resume();
127
+ const nextUrl = new URL(res.headers.location, urlString).toString();
128
+ return download(nextUrl, maxRedirects - 1).then(resolve, reject);
129
+ }
130
+ if (res.statusCode < 200 || res.statusCode >= 300) {
131
+ res.resume();
132
+ return reject(new Error(`HTTP ${res.statusCode} from ${urlString}`));
133
+ }
134
+ resolve(res);
135
+ });
136
+ req.on("error", reject);
137
+ req.end();
138
+ };
139
+
140
+ if (proxy && isHttps) {
141
+ connectThroughProxy(proxy, parsed).then(
142
+ (socket) => doRequest({ socket, agent: false }),
143
+ reject,
144
+ );
145
+ } else {
146
+ doRequest();
147
+ }
148
+ });
149
+ }
150
+
151
+ class Package {
152
+ constructor(platform, name, url, filename, zipExt, binaries) {
153
+ let errors = [];
154
+ if (typeof url !== "string") {
155
+ errors.push("url must be a string");
156
+ } else {
157
+ try {
158
+ new URL(url);
159
+ } catch (e) {
160
+ errors.push(e);
161
+ }
162
+ }
163
+ if (name && typeof name !== "string") {
164
+ errors.push("package name must be a string");
165
+ }
166
+ if (!name) {
167
+ errors.push("You must specify the name of your package");
168
+ }
169
+ if (binaries && typeof binaries !== "object") {
170
+ errors.push("binaries must be a string => string map");
171
+ }
172
+ if (!binaries) {
173
+ errors.push("You must specify the binaries in the package");
174
+ }
175
+
176
+ if (errors.length > 0) {
177
+ let errorMsg =
178
+ "One or more of the parameters you passed to the Binary constructor are invalid:\n";
179
+ errors.forEach((error) => {
180
+ errorMsg += error;
181
+ });
182
+ errorMsg +=
183
+ '\n\nCorrect usage: new Package("my-binary", "https://example.com/binary/download.tar.gz", {"my-binary": "my-binary"})';
184
+ error(errorMsg);
185
+ }
186
+
187
+ this.platform = platform;
188
+ this.url = url;
189
+ this.name = name;
190
+ this.filename = filename;
191
+ this.zipExt = zipExt;
192
+ this.installDirectory = join(__dirname, "node_modules", ".bin_real");
193
+ this.binaries = binaries;
194
+
195
+ if (!existsSync(this.installDirectory)) {
196
+ mkdirSync(this.installDirectory, { recursive: true });
197
+ }
198
+ }
199
+
200
+ exists() {
201
+ for (const binaryName in this.binaries) {
202
+ const binRelPath = this.binaries[binaryName];
203
+ const binPath = join(this.installDirectory, binRelPath);
204
+ if (!existsSync(binPath)) {
205
+ return false;
206
+ }
207
+ }
208
+ return true;
209
+ }
210
+
211
+ install(suppressLogs = false) {
212
+ if (this.exists()) {
213
+ if (!suppressLogs) {
214
+ console.error(
215
+ `${this.name} is already installed, skipping installation.`,
216
+ );
217
+ }
218
+ return Promise.resolve();
219
+ }
220
+
221
+ try {
222
+ rmSync(this.installDirectory, { recursive: true, force: true });
223
+ } catch {
224
+ // ignore - directory may not exist
225
+ }
226
+
227
+ mkdirSync(this.installDirectory, { recursive: true });
228
+
229
+ if (!suppressLogs) {
230
+ console.error(`Downloading release from ${this.url}`);
231
+ }
232
+
233
+ return download(this.url)
234
+ .then((res) => {
235
+ return new Promise((resolve, reject) => {
236
+ mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
237
+ if (err) return reject(err);
238
+ let tempFile = join(directory, this.filename);
239
+ const sink = res.pipe(createWriteStream(tempFile));
240
+ sink.on("error", (err) => reject(err));
241
+ sink.on("close", () => {
242
+ if (/\.tar\.*/.test(this.zipExt)) {
243
+ const result = spawnSync("tar", [
244
+ "xf",
245
+ tempFile,
246
+ // The tarballs are stored with a leading directory
247
+ // component; we strip one component in the
248
+ // shell installers too.
249
+ "--strip-components",
250
+ "1",
251
+ "-C",
252
+ this.installDirectory,
253
+ ]);
254
+ if (result.status == 0) {
255
+ resolve();
256
+ } else if (result.error) {
257
+ reject(result.error);
258
+ } else {
259
+ reject(
260
+ new Error(
261
+ `An error occurred untarring the artifact: stdout: ${result.stdout}; stderr: ${result.stderr}`,
262
+ ),
263
+ );
264
+ }
265
+ } else if (this.zipExt == ".zip") {
266
+ let result;
267
+ if (this.platform.artifactName.includes("windows")) {
268
+ // Windows does not have "unzip" by default on many installations, instead
269
+ // we use Expand-Archive from powershell
270
+ result = spawnSync("powershell.exe", [
271
+ "-NoProfile",
272
+ "-NonInteractive",
273
+ "-Command",
274
+ `& {
275
+ param([string]$LiteralPath, [string]$DestinationPath)
276
+ Expand-Archive -LiteralPath $LiteralPath -DestinationPath $DestinationPath -Force
277
+ }`,
278
+ tempFile,
279
+ this.installDirectory,
280
+ ]);
281
+ } else {
282
+ result = spawnSync("unzip", [
283
+ "-q",
284
+ tempFile,
285
+ "-d",
286
+ this.installDirectory,
287
+ ]);
288
+ }
289
+
290
+ if (result.status == 0) {
291
+ resolve();
292
+ } else if (result.error) {
293
+ reject(result.error);
294
+ } else {
295
+ reject(
296
+ new Error(
297
+ `An error occurred unzipping the artifact: stdout: ${result.stdout}; stderr: ${result.stderr}`,
298
+ ),
299
+ );
300
+ }
301
+ } else {
302
+ reject(
303
+ new Error(`Unrecognized file extension: ${this.zipExt}`),
304
+ );
305
+ }
306
+ });
307
+ });
308
+ });
309
+ })
310
+ .then(() => {
311
+ if (!suppressLogs) {
312
+ console.error(`${this.name} has been installed!`);
313
+ }
314
+ })
315
+ .catch((e) => {
316
+ error(`Error fetching release: ${e.message}`);
317
+ });
318
+ }
319
+
320
+ run(binaryName) {
321
+ const promise = !this.exists() ? this.install(true) : Promise.resolve();
322
+
323
+ promise
324
+ .then(() => {
325
+ const [, , ...args] = process.argv;
326
+
327
+ const options = { cwd: process.cwd(), stdio: "inherit" };
328
+
329
+ const binRelPath = this.binaries[binaryName];
330
+ if (!binRelPath) {
331
+ error(`${binaryName} is not a known binary in ${this.name}`);
332
+ }
333
+ const binPath = join(this.installDirectory, binRelPath);
334
+ const result = spawnSync(binPath, args, options);
335
+
336
+ if (result.error) {
337
+ error(result.error);
338
+ }
339
+
340
+ process.exit(result.status);
341
+ })
342
+ .catch((e) => {
343
+ error(e.message);
344
+ });
345
+ }
346
+ }
347
+
348
+ module.exports.Package = Package;
package/binary.js ADDED
@@ -0,0 +1,124 @@
1
+ const { Package } = require("./binary-install");
2
+ const os = require("os");
3
+ const libc = require("detect-libc");
4
+
5
+ const error = (msg) => {
6
+ console.error(msg);
7
+ process.exit(1);
8
+ };
9
+
10
+ const {
11
+ name,
12
+ artifactDownloadUrls,
13
+ supportedPlatforms,
14
+ glibcMinimum,
15
+ } = require("./package.json");
16
+
17
+ // FIXME: implement NPM installer handling of fallback download URLs
18
+ const artifactDownloadUrl = artifactDownloadUrls[0];
19
+ const builderGlibcMajorVersion = glibcMinimum.major;
20
+ const builderGlibcMinorVersion = glibcMinimum.series;
21
+
22
+ const getPlatform = () => {
23
+ const rawOsType = os.type();
24
+ const rawArchitecture = os.arch();
25
+
26
+ // We want to use rust-style target triples as the canonical key
27
+ // for a platform, so translate the "os" library's concepts into rust ones
28
+ let osType = "";
29
+ switch (rawOsType) {
30
+ case "Windows_NT":
31
+ osType = "pc-windows-msvc";
32
+ break;
33
+ case "Darwin":
34
+ osType = "apple-darwin";
35
+ break;
36
+ case "Linux":
37
+ osType = "unknown-linux-gnu";
38
+ break;
39
+ }
40
+
41
+ let arch = "";
42
+ switch (rawArchitecture) {
43
+ case "x64":
44
+ arch = "x86_64";
45
+ break;
46
+ case "arm64":
47
+ arch = "aarch64";
48
+ break;
49
+ }
50
+
51
+ if (rawOsType === "Linux") {
52
+ if (libc.familySync() == "musl") {
53
+ osType = "unknown-linux-musl-dynamic";
54
+ } else if (libc.isNonGlibcLinuxSync()) {
55
+ console.warn(
56
+ "Your libc is neither glibc nor musl; trying static musl binary instead",
57
+ );
58
+ osType = "unknown-linux-musl-static";
59
+ } else {
60
+ let libcVersion = libc.versionSync();
61
+ let splitLibcVersion = libcVersion.split(".");
62
+ let libcMajorVersion = splitLibcVersion[0];
63
+ let libcMinorVersion = splitLibcVersion[1];
64
+ if (
65
+ libcMajorVersion != builderGlibcMajorVersion ||
66
+ libcMinorVersion < builderGlibcMinorVersion
67
+ ) {
68
+ // We can't run the glibc binaries, but we can run the static musl ones
69
+ // if they exist
70
+ console.warn(
71
+ "Your glibc isn't compatible; trying static musl binary instead",
72
+ );
73
+ osType = "unknown-linux-musl-static";
74
+ }
75
+ }
76
+ }
77
+
78
+ // Assume the above succeeded and build a target triple to look things up with.
79
+ // If any of it failed, this lookup will fail and we'll handle it like normal.
80
+ let targetTriple = `${arch}-${osType}`;
81
+ let platform = supportedPlatforms[targetTriple];
82
+
83
+ if (!platform) {
84
+ error(
85
+ `Platform with type "${rawOsType}" and architecture "${rawArchitecture}" is not supported by ${name}.\nYour system must be one of the following:\n\n${Object.keys(
86
+ supportedPlatforms,
87
+ ).join(",")}`,
88
+ );
89
+ }
90
+
91
+ return platform;
92
+ };
93
+
94
+ const getPackage = () => {
95
+ const platform = getPlatform();
96
+ const url = `${artifactDownloadUrl}/${platform.artifactName}`;
97
+ let filename = platform.artifactName;
98
+ let ext = platform.zipExt;
99
+ let binary = new Package(platform, name, url, filename, ext, platform.bins);
100
+
101
+ return binary;
102
+ };
103
+
104
+ const install = (suppressLogs) => {
105
+ if (!artifactDownloadUrl || artifactDownloadUrl.length === 0) {
106
+ console.warn("in demo mode, not installing binaries");
107
+ return;
108
+ }
109
+ const pkg = getPackage();
110
+
111
+ return pkg.install(suppressLogs);
112
+ };
113
+
114
+ const run = (binaryName) => {
115
+ const pkg = getPackage();
116
+
117
+ pkg.run(binaryName);
118
+ };
119
+
120
+ module.exports = {
121
+ install,
122
+ run,
123
+ getPackage,
124
+ };
package/install.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { install } = require("./binary");
4
+ install(false);
@@ -0,0 +1,52 @@
1
+ {
2
+ "lockfileVersion": 3,
3
+ "name": "limitswap",
4
+ "packages": {
5
+ "": {
6
+ "bin": {
7
+ "limitswap": "run-limitswap.js"
8
+ },
9
+ "dependencies": {
10
+ "detect-libc": "^2.1.2"
11
+ },
12
+ "devDependencies": {
13
+ "prettier": "^3.9.10"
14
+ },
15
+ "engines": {
16
+ "node": ">=14.18",
17
+ "npm": ">=6"
18
+ },
19
+ "hasInstallScript": true,
20
+ "license": "MIT",
21
+ "name": "limitswap",
22
+ "version": "0.3.0"
23
+ },
24
+ "node_modules/detect-libc": {
25
+ "engines": {
26
+ "node": ">=8"
27
+ },
28
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
29
+ "license": "Apache-2.0",
30
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
31
+ "version": "2.1.2"
32
+ },
33
+ "node_modules/prettier": {
34
+ "bin": {
35
+ "prettier": "bin/prettier.cjs"
36
+ },
37
+ "dev": true,
38
+ "engines": {
39
+ "node": ">=14"
40
+ },
41
+ "funding": {
42
+ "url": "https://github.com/prettier/prettier?sponsor=1"
43
+ },
44
+ "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==",
45
+ "license": "MIT",
46
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz",
47
+ "version": "3.9.10"
48
+ }
49
+ },
50
+ "requires": true,
51
+ "version": "0.3.0"
52
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
+ "artifactDownloadUrls": [
3
+ "https://github.com/wporoslo/limitswap/releases/download/v0.3.0"
4
+ ],
5
+ "bin": {
6
+ "limitswap": "run-limitswap.js"
7
+ },
8
+ "dependencies": {
9
+ "detect-libc": "^2.1.2"
10
+ },
11
+ "description": "Hand Claude Code work to another account before one hits its usage limit",
12
+ "devDependencies": {
13
+ "prettier": "^3.9.10"
14
+ },
15
+ "engines": {
16
+ "node": ">=14.18",
17
+ "npm": ">=6"
18
+ },
19
+ "glibcMinimum": {
20
+ "major": 2,
21
+ "series": 35
22
+ },
23
+ "homepage": "https://github.com/wporoslo/limitswap",
24
+ "keywords": [
25
+ "command-line-utilities",
26
+ "claude",
27
+ "claude-code",
28
+ "cli",
29
+ "usage-limits"
30
+ ],
31
+ "license": "MIT",
2
32
  "name": "limitswap",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
33
+ "preferUnplugged": true,
34
+ "repository": "https://github.com/wporoslo/limitswap",
35
+ "scripts": {
36
+ "fmt": "prettier --write **/*.js",
37
+ "fmt:check": "prettier --check **/*.js",
38
+ "postinstall": "node ./install.js"
39
+ },
40
+ "supportedPlatforms": {
41
+ "aarch64-apple-darwin": {
42
+ "artifactName": "limitswap-aarch64-apple-darwin.tar.xz",
43
+ "bins": {
44
+ "limitswap": "limitswap"
45
+ },
46
+ "zipExt": ".tar.xz"
47
+ },
48
+ "aarch64-unknown-linux-gnu": {
49
+ "artifactName": "limitswap-aarch64-unknown-linux-gnu.tar.xz",
50
+ "bins": {
51
+ "limitswap": "limitswap"
52
+ },
53
+ "zipExt": ".tar.xz"
54
+ },
55
+ "x86_64-apple-darwin": {
56
+ "artifactName": "limitswap-x86_64-apple-darwin.tar.xz",
57
+ "bins": {
58
+ "limitswap": "limitswap"
59
+ },
60
+ "zipExt": ".tar.xz"
61
+ },
62
+ "x86_64-unknown-linux-gnu": {
63
+ "artifactName": "limitswap-x86_64-unknown-linux-gnu.tar.xz",
64
+ "bins": {
65
+ "limitswap": "limitswap"
66
+ },
67
+ "zipExt": ".tar.xz"
68
+ }
69
+ },
70
+ "version": "0.3.0",
71
+ "volta": {
72
+ "node": "18.14.1",
73
+ "npm": "9.5.0"
74
+ }
6
75
  }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { run } = require("./binary");
4
+ run("limitswap");