autolimit 0.2.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/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "autolimit",
3
+ "version": "0.2.0",
4
+ "description": "Terminal-agnostic PTY wrapper that resumes CLI runners after reset-time usage limits.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/betive37/autolimit"
8
+ },
9
+ "bin": {
10
+ "autolimit": "bin/autolimit.js"
11
+ },
12
+ "scripts": {
13
+ "postinstall": "node scripts/postinstall.js",
14
+ "prepublishOnly": "npm test",
15
+ "test": "python3 tests/test_autolimit.py && node tests/test_postinstall_star.js && node bin/autolimit.js --test-parser && node bin/autolimit.js --dry-run --cc --example"
16
+ },
17
+ "keywords": [
18
+ "terminal",
19
+ "pty",
20
+ "automation",
21
+ "claude-code",
22
+ "wrapper"
23
+ ],
24
+ "author": "Jae Hyun <betive37@gmail.com>",
25
+ "license": "MIT",
26
+ "engines": {
27
+ "node": ">=16"
28
+ },
29
+ "os": [
30
+ "darwin",
31
+ "linux"
32
+ ],
33
+ "files": [
34
+ "bin/autolimit.js",
35
+ "lib/autolimit.py",
36
+ "scripts/github-star.js",
37
+ "scripts/postinstall.js"
38
+ ]
39
+ }
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const https = require('https');
6
+ const path = require('path');
7
+ const readline = require('readline');
8
+ const { spawnSync } = require('child_process');
9
+
10
+ function readRepositoryUrl(packageFile) {
11
+ try {
12
+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
13
+ if (typeof pkg.repository === 'string') return pkg.repository;
14
+ if (pkg.repository && typeof pkg.repository.url === 'string') return pkg.repository.url;
15
+ } catch (_) {
16
+ }
17
+ return 'https://github.com/betive37/autolimit';
18
+ }
19
+
20
+ function stripGitSuffix(value) {
21
+ return value.endsWith('.git') ? value.slice(0, -4) : value;
22
+ }
23
+
24
+ function parseGitHubRepo(repositoryUrl) {
25
+ const normalized = stripGitSuffix(repositoryUrl.replace(/^git\+/, ''));
26
+
27
+ const sshMatch = normalized.match(/^git@github\.com:([^/]+)\/(.+)$/);
28
+ if (sshMatch) {
29
+ return { owner: sshMatch[1], repo: stripGitSuffix(sshMatch[2]) };
30
+ }
31
+
32
+ const shortcutMatch = normalized.match(/^github:([^/]+)\/(.+)$/);
33
+ if (shortcutMatch) {
34
+ return { owner: shortcutMatch[1], repo: stripGitSuffix(shortcutMatch[2]) };
35
+ }
36
+
37
+ try {
38
+ const url = new URL(normalized);
39
+ if (url.hostname.toLowerCase() !== 'github.com') return null;
40
+ const parts = url.pathname.split('/').filter(Boolean);
41
+ if (parts.length < 2) return null;
42
+ return { owner: parts[0], repo: stripGitSuffix(parts[1]) };
43
+ } catch (_) {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ function repoSlug(repo) {
49
+ return `${repo.owner}/${repo.repo}`;
50
+ }
51
+
52
+ function envFlag(name) {
53
+ const value = process.env[name];
54
+ if (!value) return null;
55
+ if (/^(0|false|no|off)$/i.test(value)) return false;
56
+ if (/^(1|true|yes|on|force)$/i.test(value)) return true;
57
+ return null;
58
+ }
59
+
60
+ function hasAnsweredStarPrompt(stateFile, slug) {
61
+ try {
62
+ const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
63
+ return state.repo === slug && (state.status === 'declined' || state.status === 'starred');
64
+ } catch (_) {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ function writeStarPromptState(configDir, stateFile, slug, status) {
70
+ fs.mkdirSync(configDir, { recursive: true });
71
+ const state = {
72
+ repo: slug,
73
+ status,
74
+ answered_at: new Date().toISOString()
75
+ };
76
+ fs.writeFileSync(stateFile, JSON.stringify(state, null, 2) + '\n', 'utf8');
77
+ }
78
+
79
+ function shouldAskForStar(stateFile, slug) {
80
+ const forcedPrompt = envFlag('AUTOLIMIT_GITHUB_STAR_PROMPT');
81
+ if (forcedPrompt === false) return false;
82
+ if (forcedPrompt === true) return true;
83
+ if (process.env.CI) return false;
84
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
85
+ return !hasAnsweredStarPrompt(stateFile, slug);
86
+ }
87
+
88
+ function promptYesNo(question) {
89
+ return new Promise((resolve) => {
90
+ const rl = readline.createInterface({
91
+ input: process.stdin,
92
+ output: process.stdout
93
+ });
94
+
95
+ rl.question(`${question} [y/N] `, (answer) => {
96
+ rl.close();
97
+ resolve(/^(y|yes)$/i.test(answer.trim()));
98
+ });
99
+ });
100
+ }
101
+
102
+ function starWithGh(slug) {
103
+ const result = spawnSync('gh', ['api', '--method', 'PUT', `/user/starred/${slug}`, '--silent'], {
104
+ env: {
105
+ ...process.env,
106
+ GH_PROMPT_DISABLED: '1'
107
+ },
108
+ stdio: 'ignore'
109
+ });
110
+ if (result.error) return false;
111
+ return result.status === 0;
112
+ }
113
+
114
+ function authToken() {
115
+ return process.env.GH_TOKEN || process.env.GITHUB_TOKEN || '';
116
+ }
117
+
118
+ function starWithToken(slug, token) {
119
+ return new Promise((resolve) => {
120
+ const req = https.request(
121
+ {
122
+ hostname: 'api.github.com',
123
+ method: 'PUT',
124
+ path: `/user/starred/${slug}`,
125
+ headers: {
126
+ Accept: 'application/vnd.github+json',
127
+ Authorization: `Bearer ${token}`,
128
+ 'Content-Length': '0',
129
+ 'User-Agent': 'autolimit-postinstall',
130
+ 'X-GitHub-Api-Version': '2026-03-10'
131
+ }
132
+ },
133
+ (res) => {
134
+ res.resume();
135
+ resolve(res.statusCode === 204 || res.statusCode === 304);
136
+ }
137
+ );
138
+ req.on('error', () => resolve(false));
139
+ req.end();
140
+ });
141
+ }
142
+
143
+ async function starGitHubRepository(slug) {
144
+ if (starWithGh(slug)) return true;
145
+
146
+ const token = authToken();
147
+ if (!token) return false;
148
+
149
+ return starWithToken(slug, token);
150
+ }
151
+
152
+ async function maybeAskForGitHubStar(options) {
153
+ const repo = parseGitHubRepo(readRepositoryUrl(options.packageFile));
154
+ if (!repo) return;
155
+
156
+ const slug = repoSlug(repo);
157
+ const stateFile = path.join(options.configDir, 'github-star.json');
158
+ if (!shouldAskForStar(stateFile, slug)) return;
159
+
160
+ const accepted = await promptYesNo(`[autolimit] Star https://github.com/${slug} on GitHub?`);
161
+ if (!accepted) {
162
+ writeStarPromptState(options.configDir, stateFile, slug, 'declined');
163
+ return;
164
+ }
165
+
166
+ const starred = await starGitHubRepository(slug);
167
+ if (starred) {
168
+ writeStarPromptState(options.configDir, stateFile, slug, 'starred');
169
+ console.log(`[autolimit] Starred https://github.com/${slug}`);
170
+ return;
171
+ }
172
+
173
+ console.warn('[autolimit] Could not star automatically. Run `gh auth login` or set GH_TOKEN, then try again.');
174
+ }
175
+
176
+ module.exports = {
177
+ maybeAskForGitHubStar,
178
+ parseGitHubRepo
179
+ };
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { maybeAskForGitHubStar } = require('./github-star');
8
+
9
+ const root = path.resolve(__dirname, '..');
10
+ const binFile = path.join(root, 'bin', 'autolimit.js');
11
+ const pyFile = path.join(root, 'lib', 'autolimit.py');
12
+ const packageFile = path.join(root, 'package.json');
13
+ const home = os.homedir();
14
+ const configDir = path.join(home, '.config', 'autolimit');
15
+ const legacyMessage = path.join(home, '.config', 'claude-auto', 'message.txt');
16
+ const messageFile = path.join(configDir, 'message.txt');
17
+ const configFile = path.join(configDir, 'config.json');
18
+ const localBin = path.join(home, '.local', 'bin');
19
+ const symlink = path.join(localBin, 'autolimit');
20
+
21
+ const defaultMessage = '이어서 계속 진행해줘.\n';
22
+ // Keep in sync with DEFAULT_PATTERN / DEFAULT_PATTERN_DATED in lib/autolimit.py.
23
+ const defaultPatternTime = "You[\\u2019']?ve\\s+hit\\s+your(?:\\s+[\\w-]+)?\\s+limit.{0,120}?resets\\s+(?P<hour>\\d{1,2})(?::(?P<minute>\\d{2}))?\\s*(?P<ampm>[aApP]\\.?[mM]\\.?)?\\s*\\((?P<tzname>[^)]{1,64})\\)";
24
+ const defaultPatternDated = "You[\\u2019']?ve\\s+hit\\s+your(?:\\s+[\\w-]+)?\\s+limit.{0,120}?resets\\s+(?P<month>[A-Za-z]{3,9})\\.?\\s+(?P<day>\\d{1,2})(?:st|nd|rd|th)?,?\\s*(?:at\\s+)?(?P<hour>\\d{1,2})(?::(?P<minute>\\d{2}))?\\s*(?P<ampm>[aApP]\\.?[mM]\\.?)?\\s*\\((?P<tzname>[^)]{1,64})\\)";
25
+
26
+ function chmodX(file) {
27
+ try {
28
+ fs.chmodSync(file, 0o755);
29
+ } catch (error) {
30
+ console.warn(`[autolimit] Could not chmod +x ${file}: ${error.message}`);
31
+ }
32
+ }
33
+
34
+ function ensureDir(dir) {
35
+ fs.mkdirSync(dir, { recursive: true });
36
+ }
37
+
38
+ function ensureMessageFile() {
39
+ ensureDir(configDir);
40
+ if (fs.existsSync(messageFile)) return;
41
+ if (fs.existsSync(legacyMessage)) {
42
+ try {
43
+ fs.copyFileSync(legacyMessage, messageFile);
44
+ return;
45
+ } catch (_) {
46
+ // fall through
47
+ }
48
+ }
49
+ fs.writeFileSync(messageFile, defaultMessage, 'utf8');
50
+ }
51
+
52
+ function ensureConfigFile() {
53
+ ensureDir(configDir);
54
+ if (fs.existsSync(configFile)) return;
55
+ const config = {
56
+ version: 1,
57
+ message_file: messageFile,
58
+ log_file: path.join(configDir, 'limit-watch.log'),
59
+ default_timezone: 'Asia/Seoul',
60
+ send_grace_seconds: 5,
61
+ max_schedule_ahead_hours: 12,
62
+ max_fallback_wait_hours: 26,
63
+ patterns: [
64
+ {
65
+ name: 'Claude-style session limit',
66
+ regex: defaultPatternTime
67
+ },
68
+ {
69
+ name: 'Claude-style dated limit',
70
+ regex: defaultPatternDated
71
+ }
72
+ ],
73
+ runners: {
74
+ claude: {
75
+ fallback: ['{runner}', '{args}', '-c', '-p', '{message}']
76
+ },
77
+ cc: {
78
+ fallback: ['{runner}', '{args}', '-c', '-p', '{message}']
79
+ }
80
+ }
81
+ };
82
+ fs.writeFileSync(configFile, JSON.stringify(config, null, 2) + '\n', 'utf8');
83
+ }
84
+
85
+ function ensureSymlink() {
86
+ ensureDir(localBin);
87
+ try {
88
+ if (fs.existsSync(symlink) || fs.lstatSync(symlink).isSymbolicLink()) {
89
+ const stat = fs.lstatSync(symlink);
90
+ if (stat.isSymbolicLink()) {
91
+ const current = fs.readlinkSync(symlink);
92
+ if (path.resolve(path.dirname(symlink), current) === binFile) return;
93
+ fs.unlinkSync(symlink);
94
+ } else {
95
+ console.warn(`[autolimit] ${symlink} exists and is not a symlink; leaving it unchanged.`);
96
+ return;
97
+ }
98
+ }
99
+ } catch (_) {
100
+ // lstat can fail when the link does not exist. Continue.
101
+ }
102
+
103
+ try {
104
+ fs.symlinkSync(binFile, symlink);
105
+ } catch (error) {
106
+ console.warn(`[autolimit] Could not create symlink ${symlink}: ${error.message}`);
107
+ console.warn('[autolimit] You can still run ./bin/autolimit.js or npx autolimit from this package.');
108
+ }
109
+ }
110
+
111
+ async function main() {
112
+ chmodX(binFile);
113
+ chmodX(pyFile);
114
+ ensureMessageFile();
115
+ ensureConfigFile();
116
+ ensureSymlink();
117
+
118
+ console.log('[autolimit] Installed. Try: autolimit --cc');
119
+ console.log(`[autolimit] Message file: ${messageFile}`);
120
+ console.log(`[autolimit] Config file: ${configFile}`);
121
+ console.log(`[autolimit] PATH helper: ${symlink}`);
122
+ console.log('[autolimit] If `autolimit` is not found, add ~/.local/bin to PATH.');
123
+
124
+ try {
125
+ await maybeAskForGitHubStar({ configDir, packageFile });
126
+ } catch (error) {
127
+ console.warn(`[autolimit] GitHub star prompt warning: ${error.message}`);
128
+ }
129
+ }
130
+
131
+ main().catch((error) => {
132
+ console.error(`[autolimit] Postinstall failed: ${error.message}`);
133
+ process.exitCode = 1;
134
+ });