chompyy 0.5.0 → 0.6.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/README.md +11 -0
- package/dist/agentlimits.js +77 -0
- package/dist/agentusage.js +96 -0
- package/dist/appstate.js +63 -3
- package/dist/away.js +44 -5
- package/dist/blueprint.js +3 -7
- package/dist/board.js +1 -0
- package/dist/cli.js +263 -5
- package/dist/codexquota.js +106 -0
- package/dist/codexusage.js +10 -0
- package/dist/config.js +2 -0
- package/dist/context.js +30 -0
- package/dist/costs.js +1 -0
- package/dist/demon.js +20 -0
- package/dist/label.js +33 -0
- package/dist/menu.js +17 -0
- package/dist/nightcap.js +60 -0
- package/dist/nudge.js +47 -18
- package/dist/pacing.js +16 -1
- package/dist/questions.js +71 -0
- package/dist/recap.js +74 -0
- package/dist/receipt.js +48 -0
- package/dist/recipe.js +79 -0
- package/dist/stamps.js +14 -0
- package/dist/triggers.js +5 -0
- package/dist/usage.js +21 -1
- package/dist/vendor/codeburn/antigravity.js +309 -0
- package/dist/vendor/codeburn/codex.js +429 -0
- package/dist/vendor/codeburn/copilot.js +292 -0
- package/dist/vendor/codeburn/gemini.js +195 -0
- package/dist/vendor/codeburn/grokbot.js +182 -0
- package/dist/vendor/codeburn/kimi.js +178 -0
- package/dist/vendor/codeburn/shims/chalk.js +14 -0
- package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
- package/dist/vendor/codeburn/src/act/backup.js +83 -0
- package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
- package/dist/vendor/codeburn/src/act/types.js +37 -0
- package/dist/vendor/codeburn/src/bash-utils.js +204 -0
- package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
- package/dist/vendor/codeburn/src/cache-dir.js +26 -0
- package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
- package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
- package/dist/vendor/codeburn/src/classifier.js +209 -0
- package/dist/vendor/codeburn/src/claude-identity.js +223 -0
- package/dist/vendor/codeburn/src/codex-cache.js +377 -0
- package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
- package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
- package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
- package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
- package/dist/vendor/codeburn/src/compare-stats.js +405 -0
- package/dist/vendor/codeburn/src/config.js +145 -0
- package/dist/vendor/codeburn/src/content-utils.js +56 -0
- package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
- package/dist/vendor/codeburn/src/context-tree.js +664 -0
- package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
- package/dist/vendor/codeburn/src/currency.js +189 -0
- package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
- package/dist/vendor/codeburn/src/cursor-import.js +402 -0
- package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
- package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
- package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
- package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
- package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
- package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
- package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
- package/dist/vendor/codeburn/src/format.js +118 -0
- package/dist/vendor/codeburn/src/fs-utils.js +270 -0
- package/dist/vendor/codeburn/src/git-origin.js +334 -0
- package/dist/vendor/codeburn/src/granular-history.js +328 -0
- package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
- package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
- package/dist/vendor/codeburn/src/live-sessions.js +358 -0
- package/dist/vendor/codeburn/src/math-utils.js +8 -0
- package/dist/vendor/codeburn/src/menubar-json.js +294 -0
- package/dist/vendor/codeburn/src/models.js +1879 -0
- package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
- package/dist/vendor/codeburn/src/optimize.js +4110 -0
- package/dist/vendor/codeburn/src/parse-workers.js +219 -0
- package/dist/vendor/codeburn/src/parser.js +6953 -0
- package/dist/vendor/codeburn/src/path-privacy.js +26 -0
- package/dist/vendor/codeburn/src/plans.js +135 -0
- package/dist/vendor/codeburn/src/pr-signals.js +132 -0
- package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
- package/dist/vendor/codeburn/src/provider-issues.js +30 -0
- package/dist/vendor/codeburn/src/providers/amp.js +286 -0
- package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
- package/dist/vendor/codeburn/src/providers/claude.js +551 -0
- package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
- package/dist/vendor/codeburn/src/providers/cline.js +63 -0
- package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
- package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
- package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
- package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
- package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
- package/dist/vendor/codeburn/src/providers/crush.js +226 -0
- package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
- package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
- package/dist/vendor/codeburn/src/providers/devin.js +569 -0
- package/dist/vendor/codeburn/src/providers/droid.js +324 -0
- package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
- package/dist/vendor/codeburn/src/providers/forge.js +245 -0
- package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
- package/dist/vendor/codeburn/src/providers/goose.js +252 -0
- package/dist/vendor/codeburn/src/providers/grok.js +581 -0
- package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
- package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
- package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
- package/dist/vendor/codeburn/src/providers/index.js +360 -0
- package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
- package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
- package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
- package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
- package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
- package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
- package/dist/vendor/codeburn/src/providers/mux.js +242 -0
- package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
- package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
- package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
- package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
- package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
- package/dist/vendor/codeburn/src/providers/pi.js +429 -0
- package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
- package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
- package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
- package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
- package/dist/vendor/codeburn/src/providers/types.js +5 -0
- package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
- package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
- package/dist/vendor/codeburn/src/providers/warp.js +575 -0
- package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
- package/dist/vendor/codeburn/src/providers/zed.js +187 -0
- package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
- package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
- package/dist/vendor/codeburn/src/quota/claude.js +244 -0
- package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
- package/dist/vendor/codeburn/src/quota/security.js +299 -0
- package/dist/vendor/codeburn/src/quota/types.js +1 -0
- package/dist/vendor/codeburn/src/scan-facts.js +99 -0
- package/dist/vendor/codeburn/src/session-cache.js +3040 -0
- package/dist/vendor/codeburn/src/session-count-label.js +14 -0
- package/dist/vendor/codeburn/src/session-output.js +139 -0
- package/dist/vendor/codeburn/src/session-population.js +30 -0
- package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
- package/dist/vendor/codeburn/src/sqlite.js +528 -0
- package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
- package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
- package/dist/vendor/codeburn/src/token-estimate.js +5 -0
- package/dist/vendor/codeburn/src/types.js +16 -0
- package/dist/vendor/codeburn/src/work-units.js +126 -0
- package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
- package/dist/vendor/codeburn/src/wsl.js +198 -0
- package/dist/vendor/codeburn/src/yield.js +666 -0
- package/package.json +1 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Live Kimi Code quota via the CLI's own usage endpoint (ported from the
|
|
2
|
+
// menubar's KimiSubscriptionService.swift):
|
|
3
|
+
//
|
|
4
|
+
// - GET https://api.kimi.com/coding/v1/usages
|
|
5
|
+
// Headers mirror observed Kimi Code client responses (X-Msh-Platform /
|
|
6
|
+
// X-Msh-Device-Id). Numeric fields have shipped as both JSON numbers and
|
|
7
|
+
// strings, and the reset stamp under several spellings, so decode leniently.
|
|
8
|
+
//
|
|
9
|
+
// Credential: the Kimi CLI's own ~/.kimi-code/credentials/kimi-code.json,
|
|
10
|
+
// read-only. Access tokens live ~15 minutes and ONLY the Kimi CLI refreshes
|
|
11
|
+
// them — we never refresh and never write, so an expired or rejected token is a
|
|
12
|
+
// terminal state whose footer tells the user to run the Kimi CLI once.
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { fraction, quotaRequestSignal, readSecureFile, sanitizeError } from './security.js';
|
|
16
|
+
const USAGE_ENDPOINT = 'https://api.kimi.com/coding/v1/usages';
|
|
17
|
+
const EXPIRED_FOOTER = ['Login expired. Run the Kimi CLI once, then refresh.'];
|
|
18
|
+
const kimiHome = process.env['KIMI_CODE_HOME'] ?? path.join(os.homedir(), '.kimi-code');
|
|
19
|
+
const defaults = {
|
|
20
|
+
fetch: globalThis.fetch,
|
|
21
|
+
credentialPath: path.join(kimiHome, 'credentials', 'kimi-code.json'),
|
|
22
|
+
deviceIdPath: path.join(kimiHome, 'device_id'),
|
|
23
|
+
readFile: readSecureFile,
|
|
24
|
+
now: Date.now,
|
|
25
|
+
};
|
|
26
|
+
function empty(connection, footerLines = []) {
|
|
27
|
+
return { provider: 'kimi', connection, primary: null, details: [], planLabel: null, footerLines };
|
|
28
|
+
}
|
|
29
|
+
function num(value) {
|
|
30
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
31
|
+
return value;
|
|
32
|
+
if (typeof value === 'string' && value.trim()) {
|
|
33
|
+
const parsed = Number(value);
|
|
34
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
/** `null` = no usable credential; `'expired'` = present but past its life. */
|
|
39
|
+
async function freshToken(deps) {
|
|
40
|
+
const raw = await deps.readFile(deps.credentialPath, 64 * 1024);
|
|
41
|
+
if (!raw)
|
|
42
|
+
return null;
|
|
43
|
+
const parsed = JSON.parse(raw);
|
|
44
|
+
const token = parsed.access_token;
|
|
45
|
+
if (typeof token !== 'string' || !token)
|
|
46
|
+
return null;
|
|
47
|
+
const expiresAt = num(parsed.expires_at);
|
|
48
|
+
// 60s skew, matching the menubar: a token about to die is already useless.
|
|
49
|
+
if (expiresAt === null || expiresAt <= deps.now() / 1000 + 60)
|
|
50
|
+
return 'expired';
|
|
51
|
+
return token;
|
|
52
|
+
}
|
|
53
|
+
async function deviceId(deps) {
|
|
54
|
+
try {
|
|
55
|
+
const raw = await deps.readFile(deps.deviceIdPath, 4 * 1024);
|
|
56
|
+
return raw?.trim() || null;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Reset stamps arrive as ISO-8601 or as epoch seconds (string or number). */
|
|
63
|
+
function resetsAt(value) {
|
|
64
|
+
const raw = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : null;
|
|
65
|
+
if (!raw)
|
|
66
|
+
return null;
|
|
67
|
+
// Bare digits are epoch seconds; Date.parse would misread them as a year.
|
|
68
|
+
if (/^\d+(\.\d+)?$/.test(raw))
|
|
69
|
+
return new Date(Number(raw) * 1000).toISOString();
|
|
70
|
+
const iso = Date.parse(raw);
|
|
71
|
+
return Number.isFinite(iso) ? new Date(iso).toISOString() : null;
|
|
72
|
+
}
|
|
73
|
+
function windowOf(label, detail) {
|
|
74
|
+
if (!detail || typeof detail !== 'object')
|
|
75
|
+
return null;
|
|
76
|
+
const row = detail;
|
|
77
|
+
const limit = num(row.limit);
|
|
78
|
+
if (limit === null || limit <= 0)
|
|
79
|
+
return null;
|
|
80
|
+
const remaining = num(row.remaining);
|
|
81
|
+
// Rate-limit windows report only limit + remaining — derive used.
|
|
82
|
+
const used = num(row.used) ?? Math.max(0, limit - (remaining ?? limit));
|
|
83
|
+
return {
|
|
84
|
+
label,
|
|
85
|
+
// Over-limit usage clamps to 100% rather than overflowing the bar.
|
|
86
|
+
percent: fraction(used / limit * 100),
|
|
87
|
+
resetsAt: resetsAt(row.resetTime ?? row.resetAt ?? row.reset_time ?? row.reset_at),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Window size → human label. The API sends enum-style units
|
|
91
|
+
* ("TIME_UNIT_MINUTE", duration 300) as well as plain ones ("hour"), so
|
|
92
|
+
* normalize first; exact sub-day durations roll up (300 minutes → 5-hour). */
|
|
93
|
+
function windowLabel(duration, timeUnit) {
|
|
94
|
+
let value = num(duration);
|
|
95
|
+
if (value === null || typeof timeUnit !== 'string' || !timeUnit)
|
|
96
|
+
return 'Rate Limit';
|
|
97
|
+
let unit = timeUnit.toLowerCase().replace(/^time_unit_/, '').replace(/s$/, '');
|
|
98
|
+
if (unit === 'minute' && value >= 60 && value % 60 === 0) {
|
|
99
|
+
value /= 60;
|
|
100
|
+
unit = 'hour';
|
|
101
|
+
}
|
|
102
|
+
const count = Math.trunc(value);
|
|
103
|
+
switch (unit) {
|
|
104
|
+
case 'minute': return count === 1 ? 'Minutely' : `${count}-min`;
|
|
105
|
+
case 'hour': return count === 1 ? 'Hourly' : `${count}-hour`;
|
|
106
|
+
case 'day': return count === 1 ? 'Daily' : count === 7 ? 'Weekly' : `${count}-day`;
|
|
107
|
+
case 'week': return count === 1 ? 'Weekly' : `${count}-week`;
|
|
108
|
+
case 'month': return count === 1 ? 'Monthly' : `${count}-month`;
|
|
109
|
+
default: return `${count} ${unit}`;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** "LEVEL_INTERMEDIATE" → "Intermediate"; unknown/missing → null so the UI
|
|
113
|
+
* falls back to the plain "Kimi Code" title. */
|
|
114
|
+
function planLabel(level) {
|
|
115
|
+
if (typeof level !== 'string' || !level.trim())
|
|
116
|
+
return null;
|
|
117
|
+
return level.trim().replace(/^LEVEL_/i, '').replace(/_/g, ' ').toLowerCase()
|
|
118
|
+
.replace(/(^|\s)\w/g, match => match.toUpperCase());
|
|
119
|
+
}
|
|
120
|
+
/** `null` when the payload carries no usable window at all. */
|
|
121
|
+
export function decodeKimiUsage(body) {
|
|
122
|
+
const data = body && typeof body === 'object' ? body : {};
|
|
123
|
+
// The top-level usage envelope is the account's weekly quota (its reset lands
|
|
124
|
+
// ~7 days out), so label it the way the menubar does.
|
|
125
|
+
const primary = windowOf('Weekly', data.usage);
|
|
126
|
+
const rest = (Array.isArray(data.limits) ? data.limits : [])
|
|
127
|
+
.map((limit) => windowOf(windowLabel(limit?.window?.duration, limit?.window?.timeUnit), limit?.detail))
|
|
128
|
+
.filter((window) => window !== null);
|
|
129
|
+
const details = primary ? [primary, ...rest] : rest;
|
|
130
|
+
if (details.length === 0)
|
|
131
|
+
return null;
|
|
132
|
+
const parallel = num(data.parallel?.limit);
|
|
133
|
+
return {
|
|
134
|
+
provider: 'kimi', connection: 'connected',
|
|
135
|
+
primary: primary ?? details[0],
|
|
136
|
+
details,
|
|
137
|
+
planLabel: planLabel(data.user?.membership?.level),
|
|
138
|
+
footerLines: parallel !== null && parallel > 0 ? [`Parallel sessions: ${Math.trunc(parallel)}`] : [],
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export async function fetchKimiQuota(options = {}) {
|
|
142
|
+
const deps = { ...defaults, ...options };
|
|
143
|
+
try {
|
|
144
|
+
const token = await freshToken(deps);
|
|
145
|
+
if (token === null)
|
|
146
|
+
return { quota: empty('disconnected') };
|
|
147
|
+
if (token === 'expired')
|
|
148
|
+
return { quota: { ...empty('terminalFailure', EXPIRED_FOOTER), connectable: true } };
|
|
149
|
+
const device = await deviceId(deps);
|
|
150
|
+
const response = await deps.fetch(USAGE_ENDPOINT, {
|
|
151
|
+
method: 'GET', signal: quotaRequestSignal(options.signal),
|
|
152
|
+
headers: {
|
|
153
|
+
Authorization: `Bearer ${token}`,
|
|
154
|
+
Accept: 'application/json',
|
|
155
|
+
'User-Agent': 'chompyy/0.1 (+https://github.com/BranchWork-HQ/Chompyy)',
|
|
156
|
+
'X-Msh-Platform': 'kimi_code_cli',
|
|
157
|
+
...(device ? { 'X-Msh-Device-Id': device } : {}),
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
// We never self-refresh, so a rejected token is terminal until the CLI runs.
|
|
161
|
+
if (response.status === 401 || response.status === 403)
|
|
162
|
+
return { quota: { ...empty('terminalFailure', EXPIRED_FOOTER), connectable: true } };
|
|
163
|
+
if (response.status === 429) {
|
|
164
|
+
const raw = response.headers.get('Retry-After');
|
|
165
|
+
const seconds = raw === null ? NaN : Number(raw);
|
|
166
|
+
return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60) };
|
|
167
|
+
}
|
|
168
|
+
if (!response.ok)
|
|
169
|
+
return { quota: empty(response.status >= 400 && response.status < 500 ? 'terminalFailure' : 'transientFailure') };
|
|
170
|
+
// Never log the body — it carries account data.
|
|
171
|
+
const quota = decodeKimiUsage(await response.json());
|
|
172
|
+
return { quota: quota ?? empty('transientFailure') };
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
console.warn(`Kimi quota unavailable: ${sanitizeError(error)}`);
|
|
176
|
+
return { quota: empty('transientFailure') };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
function style() {
|
|
2
|
+
const fn = ((text) => String(text));
|
|
3
|
+
return new Proxy(fn, {
|
|
4
|
+
get(target, prop) {
|
|
5
|
+
if (prop === 'hex' || prop === 'rgb' || prop === 'bgHex')
|
|
6
|
+
return () => style();
|
|
7
|
+
if (typeof prop === 'string' && !(prop in target))
|
|
8
|
+
return style();
|
|
9
|
+
return target[prop];
|
|
10
|
+
},
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
const chalk = style();
|
|
14
|
+
export default chalk;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Stand-in for the `strip-ansi` package (MIT, Sindre Sorhus): the same regex as ansi-regex, so codeburn's files need
|
|
2
|
+
// no npm dependency in Chompyy.
|
|
3
|
+
const ANSI = /[\u001B\u009B][[\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*|[a-zA-Z\d]+(?:;[-a-zA-Z\d/#&.:=?%@~_]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;
|
|
4
|
+
export default function stripAnsi(text) {
|
|
5
|
+
return typeof text === 'string' ? text.replace(ANSI, '') : text;
|
|
6
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import { copyFile, cp, lstat, mkdir, readFile, rename, rm } from 'fs/promises';
|
|
3
|
+
import { createHash } from 'crypto';
|
|
4
|
+
import { dirname, join } from 'path';
|
|
5
|
+
export function backupDirFor(actionsDir, id) {
|
|
6
|
+
return join(actionsDir, 'backups', id);
|
|
7
|
+
}
|
|
8
|
+
export function relBackupPath(id, index) {
|
|
9
|
+
return `backups/${id}/${index}.bak`;
|
|
10
|
+
}
|
|
11
|
+
// Snapshot src (file or directory tree) to dest if it exists; return whether
|
|
12
|
+
// it existed so the caller can record backup: null for a create.
|
|
13
|
+
export async function snapshotFile(src, dest) {
|
|
14
|
+
try {
|
|
15
|
+
const st = await lstat(src);
|
|
16
|
+
if (st.isDirectory())
|
|
17
|
+
await cp(src, dest, { recursive: true });
|
|
18
|
+
else
|
|
19
|
+
await copyFile(src, dest);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
if (err.code === 'ENOENT')
|
|
24
|
+
return false;
|
|
25
|
+
throw err;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function sha256(buf) {
|
|
29
|
+
return createHash('sha256').update(buf).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
export async function sha256File(path) {
|
|
32
|
+
try {
|
|
33
|
+
return sha256(await readFile(path));
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
if (err.code === 'ENOENT')
|
|
37
|
+
return null;
|
|
38
|
+
throw err;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function pathExists(path) {
|
|
42
|
+
try {
|
|
43
|
+
await lstat(path);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Reverse a single applied change. Shared by mid-apply rollback and undo.
|
|
51
|
+
// Non-move reverts key on backup presence, not the op label, so a create that
|
|
52
|
+
// overwrote an existing file and an edit of a missing file restore correctly.
|
|
53
|
+
export async function revertChange(actionsDir, change) {
|
|
54
|
+
const restore = async (backup, to) => {
|
|
55
|
+
const src = join(actionsDir, backup);
|
|
56
|
+
await mkdir(dirname(to), { recursive: true });
|
|
57
|
+
if ((await lstat(src)).isDirectory()) {
|
|
58
|
+
await rm(to, { recursive: true, force: true });
|
|
59
|
+
await cp(src, to, { recursive: true });
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
await copyFile(src, to);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
if (change.op === 'move') {
|
|
66
|
+
if (await pathExists(change.movedTo)) {
|
|
67
|
+
await rm(change.path, { recursive: true, force: true });
|
|
68
|
+
await mkdir(dirname(change.path), { recursive: true });
|
|
69
|
+
await rename(change.movedTo, change.path);
|
|
70
|
+
if (change.destBackup)
|
|
71
|
+
await restore(change.destBackup, change.movedTo);
|
|
72
|
+
}
|
|
73
|
+
else if (change.backup) {
|
|
74
|
+
// The moved file is gone; fall back to the source snapshot.
|
|
75
|
+
await restore(change.backup, change.path);
|
|
76
|
+
}
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (change.backup)
|
|
80
|
+
await restore(change.backup, change.path);
|
|
81
|
+
else
|
|
82
|
+
await rm(change.path, { recursive: true, force: true });
|
|
83
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { aggregateModelStats } from '../compare-stats.js';
|
|
5
|
+
import { withUserStartedSessions } from '../session-population.js';
|
|
6
|
+
import { sha256File } from './backup.js';
|
|
7
|
+
const MIN_EDIT_TURNS = 30;
|
|
8
|
+
const MAX_COST_RATIO = 0.6;
|
|
9
|
+
const ONE_SHOT_TOLERANCE = 0.03;
|
|
10
|
+
const DEBUGGING_HEAVY_THRESHOLD = 0.4;
|
|
11
|
+
const RECENCY_DAYS = 14;
|
|
12
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
|
13
|
+
function oneShotRate(s) {
|
|
14
|
+
return s.editTurns > 0 ? s.oneShotTurns / s.editTurns : 0;
|
|
15
|
+
}
|
|
16
|
+
function costPerEdit(s) {
|
|
17
|
+
return s.editTurns > 0 ? s.editCost / s.editTurns : Number.POSITIVE_INFINITY;
|
|
18
|
+
}
|
|
19
|
+
function isRecent(lastSeen, now) {
|
|
20
|
+
if (!lastSeen)
|
|
21
|
+
return false;
|
|
22
|
+
const seen = new Date(lastSeen);
|
|
23
|
+
if (Number.isNaN(seen.getTime()))
|
|
24
|
+
return false;
|
|
25
|
+
return now.getTime() - seen.getTime() <= RECENCY_DAYS * MS_PER_DAY;
|
|
26
|
+
}
|
|
27
|
+
function providerByModel(project) {
|
|
28
|
+
const providers = new Map();
|
|
29
|
+
for (const session of project.sessions) {
|
|
30
|
+
for (const turn of session.turns) {
|
|
31
|
+
const primary = turn.assistantCalls[0];
|
|
32
|
+
if (!primary || primary.model === '<synthetic>')
|
|
33
|
+
continue;
|
|
34
|
+
if (!providers.has(primary.model))
|
|
35
|
+
providers.set(primary.model, primary.provider);
|
|
36
|
+
for (const call of turn.assistantCalls) {
|
|
37
|
+
if (call.model === '<synthetic>')
|
|
38
|
+
continue;
|
|
39
|
+
if (!providers.has(call.model))
|
|
40
|
+
providers.set(call.model, call.provider);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return providers;
|
|
45
|
+
}
|
|
46
|
+
function isDebuggingHeavy(project) {
|
|
47
|
+
let debuggingEditTurns = 0;
|
|
48
|
+
let totalEditTurns = 0;
|
|
49
|
+
for (const session of project.sessions) {
|
|
50
|
+
for (const breakdown of Object.values(session.categoryBreakdown)) {
|
|
51
|
+
totalEditTurns += breakdown.editTurns;
|
|
52
|
+
}
|
|
53
|
+
debuggingEditTurns += session.categoryBreakdown.debugging?.editTurns ?? 0;
|
|
54
|
+
}
|
|
55
|
+
return totalEditTurns > 0 && debuggingEditTurns / totalEditTurns > DEBUGGING_HEAVY_THRESHOLD;
|
|
56
|
+
}
|
|
57
|
+
export function recommendModelDefault(project, opts = {}) {
|
|
58
|
+
const behavioralProject = withUserStartedSessions(project);
|
|
59
|
+
const now = opts.now ?? new Date();
|
|
60
|
+
const stats = aggregateModelStats([behavioralProject])
|
|
61
|
+
.filter(s => s.model !== '<synthetic>' && s.editTurns >= MIN_EDIT_TURNS)
|
|
62
|
+
.sort((a, b) => b.editTurns - a.editTurns || b.editCost - a.editCost);
|
|
63
|
+
const current = stats[0];
|
|
64
|
+
if (!current)
|
|
65
|
+
return null;
|
|
66
|
+
const providers = providerByModel(behavioralProject);
|
|
67
|
+
const provider = providers.get(current.model);
|
|
68
|
+
// The plan writes .claude/settings.json, which only Claude Code reads.
|
|
69
|
+
if (provider !== 'claude' || !isRecent(current.lastSeen, now))
|
|
70
|
+
return null;
|
|
71
|
+
const currentRate = oneShotRate(current);
|
|
72
|
+
const currentCost = costPerEdit(current);
|
|
73
|
+
if (!Number.isFinite(currentCost) || currentCost <= 0)
|
|
74
|
+
return null;
|
|
75
|
+
const debuggingHeavy = isDebuggingHeavy(behavioralProject);
|
|
76
|
+
const tolerance = debuggingHeavy ? 0 : ONE_SHOT_TOLERANCE;
|
|
77
|
+
const candidates = stats
|
|
78
|
+
.slice(1)
|
|
79
|
+
.filter(candidate => providers.get(candidate.model) === provider)
|
|
80
|
+
.filter(candidate => isRecent(candidate.lastSeen, now))
|
|
81
|
+
.map(candidate => ({
|
|
82
|
+
candidate,
|
|
83
|
+
candidateRate: oneShotRate(candidate),
|
|
84
|
+
candidateCost: costPerEdit(candidate),
|
|
85
|
+
}))
|
|
86
|
+
.filter(({ candidateRate }) => candidateRate >= currentRate - tolerance)
|
|
87
|
+
.filter(({ candidateCost }) => candidateCost <= currentCost * MAX_COST_RATIO)
|
|
88
|
+
.sort((a, b) => {
|
|
89
|
+
const savingsA = 1 - a.candidateCost / currentCost;
|
|
90
|
+
const savingsB = 1 - b.candidateCost / currentCost;
|
|
91
|
+
return savingsB - savingsA || b.candidateRate - a.candidateRate;
|
|
92
|
+
});
|
|
93
|
+
const best = candidates[0];
|
|
94
|
+
if (!best)
|
|
95
|
+
return null;
|
|
96
|
+
return {
|
|
97
|
+
project: project.project,
|
|
98
|
+
projectPath: project.projectPath,
|
|
99
|
+
currentModel: current.model,
|
|
100
|
+
candidateModel: best.candidate.model,
|
|
101
|
+
provider,
|
|
102
|
+
currentEditTurns: current.editTurns,
|
|
103
|
+
candidateEditTurns: best.candidate.editTurns,
|
|
104
|
+
currentOneShotRate: currentRate,
|
|
105
|
+
candidateOneShotRate: best.candidateRate,
|
|
106
|
+
currentCostPerEdit: currentCost,
|
|
107
|
+
candidateCostPerEdit: best.candidateCost,
|
|
108
|
+
savingsPct: (1 - best.candidateCost / currentCost) * 100,
|
|
109
|
+
debuggingHeavy,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export async function buildApplyModelDefaultPlan(recommendation) {
|
|
113
|
+
const settingsPath = join(recommendation.projectPath, '.claude', 'settings.json');
|
|
114
|
+
let settings = {};
|
|
115
|
+
let expectedHash = null;
|
|
116
|
+
try {
|
|
117
|
+
const raw = await readFile(settingsPath, 'utf-8');
|
|
118
|
+
expectedHash = await sha256File(settingsPath);
|
|
119
|
+
settings = JSON.parse(raw);
|
|
120
|
+
if (!settings || Array.isArray(settings) || typeof settings !== 'object')
|
|
121
|
+
settings = {};
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
const code = err.code;
|
|
125
|
+
if (code !== 'ENOENT')
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
settings.model = recommendation.candidateModel;
|
|
129
|
+
return {
|
|
130
|
+
kind: 'model-default',
|
|
131
|
+
findingId: `model-default:${recommendation.project}`,
|
|
132
|
+
description: `Set Claude Code default model to ${recommendation.candidateModel} for ${recommendation.project}`,
|
|
133
|
+
changes: [{
|
|
134
|
+
op: 'edit',
|
|
135
|
+
path: settingsPath,
|
|
136
|
+
content: JSON.stringify(settings, null, 2) + '\n',
|
|
137
|
+
expectedHash,
|
|
138
|
+
}],
|
|
139
|
+
baseline: {
|
|
140
|
+
windowDays: 30,
|
|
141
|
+
capturedAt: new Date().toISOString(),
|
|
142
|
+
estimatedTokens: 0,
|
|
143
|
+
sessions: recommendation.currentEditTurns + recommendation.candidateEditTurns,
|
|
144
|
+
candidateModel: recommendation.candidateModel,
|
|
145
|
+
metrics: {
|
|
146
|
+
[recommendation.candidateModel]: recommendation.candidateOneShotRate,
|
|
147
|
+
[recommendation.currentModel]: recommendation.currentOneShotRate,
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import { formatTokens } from '../format.js';
|
|
3
|
+
// Applied actions are re-measured on every `codeburn optimize` run: only fixes
|
|
4
|
+
// at least this old have a post-apply window to measure against.
|
|
5
|
+
export const REPORT_MIN_AGE_DAYS = 3;
|
|
6
|
+
// A fix counts as having worked once it realizes this share of its
|
|
7
|
+
// window-scaled estimate; anything above zero but below it is partial.
|
|
8
|
+
export const VERDICT_WORKED_RATIO = 0.7;
|
|
9
|
+
const VERDICT_GLYPH = {
|
|
10
|
+
worked: '\u2713',
|
|
11
|
+
partial: '~',
|
|
12
|
+
'no-effect': '\u2717',
|
|
13
|
+
pending: '\u2026',
|
|
14
|
+
};
|
|
15
|
+
export function appliedFixGlyph(fix) {
|
|
16
|
+
return VERDICT_GLYPH[fix.verdict];
|
|
17
|
+
}
|
|
18
|
+
// One plain line per applied fix: what it estimated, what it measured, and for
|
|
19
|
+
// a fix that did nothing, how to put it back.
|
|
20
|
+
export function formatAppliedFix(fix) {
|
|
21
|
+
const age = Math.max(0, Math.floor(fix.ageDays));
|
|
22
|
+
const head = `${fix.findingId ?? fix.kind} (${age}d ago)`;
|
|
23
|
+
if (fix.verdict === 'pending') {
|
|
24
|
+
const why = fix.note || (age <= REPORT_MIN_AGE_DAYS
|
|
25
|
+
? `measuring, check back after ${REPORT_MIN_AGE_DAYS} days`
|
|
26
|
+
: 'measuring');
|
|
27
|
+
return `${head}: ${why}`;
|
|
28
|
+
}
|
|
29
|
+
const pair = `est. ${formatTokens(fix.estimatedTokens)} -> measured ${formatTokens(fix.realizedTokens)}`;
|
|
30
|
+
if (fix.verdict === 'worked')
|
|
31
|
+
return `${head}: ${pair}`;
|
|
32
|
+
if (fix.verdict === 'partial') {
|
|
33
|
+
const under = Math.round((1 - fix.realizedTokens / fix.estimatedTokens) * 100);
|
|
34
|
+
return `${head}: ${pair} (-${under}% vs estimate)`;
|
|
35
|
+
}
|
|
36
|
+
return `${head}: ${pair} - did not help. Revert: ${fix.undoCommand}`;
|
|
37
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
|
|
2
|
+
import { basename } from 'path';
|
|
3
|
+
import stripAnsi from '../shims/strip-ansi.js';
|
|
4
|
+
const WHITESPACE = /\s/;
|
|
5
|
+
function stripQuotedStrings(command) {
|
|
6
|
+
return command.replace(/"[^"]*"|'[^']*'/g, match => ' '.repeat(match.length));
|
|
7
|
+
}
|
|
8
|
+
const HEREDOC_START = /<<(?!<)-?[ \t]*(?:'([^'\n]+)'|"([^"\n]+)"|\\?(\w+))/y;
|
|
9
|
+
// A newline separates commands like ';' does. A command with more than one line
|
|
10
|
+
// is scanned once: quoted text, comments and heredoc bodies are blanked, and an
|
|
11
|
+
// unquoted newline becomes ';' unless an odd run of backslashes continues the
|
|
12
|
+
// line. The result keeps the input's length, because callers slice the original
|
|
13
|
+
// string with indices taken from it. A single-line command is masked as before.
|
|
14
|
+
function maskForSplitting(command) {
|
|
15
|
+
if (!command.includes('\n'))
|
|
16
|
+
return stripQuotedStrings(command);
|
|
17
|
+
let out = '';
|
|
18
|
+
const delimiters = [];
|
|
19
|
+
let i = 0;
|
|
20
|
+
while (i < command.length) {
|
|
21
|
+
const ch = command[i];
|
|
22
|
+
if (ch === '"' || ch === "'") {
|
|
23
|
+
const close = command.indexOf(ch, i + 1);
|
|
24
|
+
if (close !== -1) {
|
|
25
|
+
out += ' '.repeat(close + 1 - i);
|
|
26
|
+
i = close + 1;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
else if (ch === '#' && (i === 0 || /[\s;&|()]/.test(command[i - 1]))) {
|
|
31
|
+
let lineEnd = command.indexOf('\n', i);
|
|
32
|
+
if (lineEnd === -1)
|
|
33
|
+
lineEnd = command.length;
|
|
34
|
+
out += ' '.repeat(lineEnd - i);
|
|
35
|
+
i = lineEnd;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
else if (ch === '<' && command[i - 1] !== '<') {
|
|
39
|
+
HEREDOC_START.lastIndex = i;
|
|
40
|
+
const match = HEREDOC_START.exec(command);
|
|
41
|
+
if (match)
|
|
42
|
+
delimiters.push(match[1] ?? match[2] ?? match[3]);
|
|
43
|
+
}
|
|
44
|
+
else if (ch === '\n') {
|
|
45
|
+
let backslashes = 0;
|
|
46
|
+
let j = command[i - 1] === '\r' ? i - 2 : i - 1;
|
|
47
|
+
while (j >= 0 && command[j] === '\\') {
|
|
48
|
+
backslashes++;
|
|
49
|
+
j--;
|
|
50
|
+
}
|
|
51
|
+
if (backslashes % 2 === 1) {
|
|
52
|
+
out += ch;
|
|
53
|
+
i++;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
out += ';';
|
|
57
|
+
i++;
|
|
58
|
+
// Heredoc bodies start on the next line, one after another, each up to
|
|
59
|
+
// its closing delimiter line. An unclosed body runs to the end.
|
|
60
|
+
let end = i;
|
|
61
|
+
for (let d = 0; d < delimiters.length && end < command.length; d++) {
|
|
62
|
+
let lineStart = d === 0 ? end : end + 1;
|
|
63
|
+
end = command.length;
|
|
64
|
+
while (lineStart < command.length) {
|
|
65
|
+
let lineEnd = command.indexOf('\n', lineStart);
|
|
66
|
+
if (lineEnd === -1)
|
|
67
|
+
lineEnd = command.length;
|
|
68
|
+
if (command.slice(lineStart, lineEnd).trim() === delimiters[d]) {
|
|
69
|
+
end = lineEnd;
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
lineStart = lineEnd + 1;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
delimiters.length = 0;
|
|
76
|
+
out += ' '.repeat(end - i);
|
|
77
|
+
i = end;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
out += ch;
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
const COMMAND_PREFIXES = new Set([
|
|
86
|
+
'sudo', 'doas',
|
|
87
|
+
'npx', 'bunx',
|
|
88
|
+
'time',
|
|
89
|
+
'nice', 'nohup', 'stdbuf',
|
|
90
|
+
'rtk',
|
|
91
|
+
]);
|
|
92
|
+
export function extractBashCommands(rawCommand) {
|
|
93
|
+
if (!rawCommand || !rawCommand.trim())
|
|
94
|
+
return [];
|
|
95
|
+
const command = stripAnsi(rawCommand);
|
|
96
|
+
const stripped = maskForSplitting(command);
|
|
97
|
+
// Match the separator alone, then widen over surrounding whitespace by hand.
|
|
98
|
+
// /\s*(?:&&|;|\|)\s*/ retried its leading \s* from every offset, quadratic on
|
|
99
|
+
// long whitespace-heavy commands. Widening is required (not cosmetic): stripQuotedStrings
|
|
100
|
+
// blanks quoted text, and segments are sliced from the original string.
|
|
101
|
+
const separatorRegex = /(?:&&|;|\|)/g;
|
|
102
|
+
const separators = [];
|
|
103
|
+
let match;
|
|
104
|
+
while ((match = separatorRegex.exec(stripped)) !== null) {
|
|
105
|
+
let start = match.index;
|
|
106
|
+
while (start > 0 && WHITESPACE.test(stripped[start - 1]))
|
|
107
|
+
start--;
|
|
108
|
+
let end = match.index + match[0].length;
|
|
109
|
+
while (end < stripped.length && WHITESPACE.test(stripped[end]))
|
|
110
|
+
end++;
|
|
111
|
+
const prevEnd = separators[separators.length - 1]?.end ?? 0;
|
|
112
|
+
separators.push({ start: Math.max(start, prevEnd), end });
|
|
113
|
+
separatorRegex.lastIndex = end;
|
|
114
|
+
}
|
|
115
|
+
const ranges = [];
|
|
116
|
+
let cursor = 0;
|
|
117
|
+
for (const sep of separators) {
|
|
118
|
+
ranges.push([cursor, sep.start]);
|
|
119
|
+
cursor = sep.end;
|
|
120
|
+
}
|
|
121
|
+
ranges.push([cursor, command.length]);
|
|
122
|
+
const commands = [];
|
|
123
|
+
for (const [start, end] of ranges) {
|
|
124
|
+
const segment = command.slice(start, end).trim();
|
|
125
|
+
if (!segment)
|
|
126
|
+
continue;
|
|
127
|
+
const tokens = segment.split(/\s+/);
|
|
128
|
+
let i = 0;
|
|
129
|
+
while (i < tokens.length) {
|
|
130
|
+
if (/^\w+=/.test(tokens[i])) {
|
|
131
|
+
i++;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const next = tokens[i + 1];
|
|
135
|
+
if (next !== undefined &&
|
|
136
|
+
COMMAND_PREFIXES.has(basename(tokens[i])) &&
|
|
137
|
+
!next.startsWith('-') &&
|
|
138
|
+
!/["']/.test(next)) {
|
|
139
|
+
i++;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
const base = i < tokens.length ? basename(tokens[i]) : '';
|
|
145
|
+
if (base && base !== 'cd' && base !== 'true' && base !== 'false') {
|
|
146
|
+
commands.push(base);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return commands;
|
|
150
|
+
}
|
|
151
|
+
// Read-shaped shell commands: they inspect state and cannot modify the
|
|
152
|
+
// worktree, so (1) the read-edit-ratio detector counts them as reads and
|
|
153
|
+
// (2) retry detection does NOT treat them as a verification step between two
|
|
154
|
+
// edits of the same file (#941 — both detectors previously disagreed about
|
|
155
|
+
// the same Bash call, scoring rg-first workflows as reckless AND reworked).
|
|
156
|
+
const READ_ONLY_BASH = new Set([
|
|
157
|
+
'rg', 'grep', 'egrep', 'fgrep', 'ag',
|
|
158
|
+
'cat', 'head', 'tail', 'less', 'more',
|
|
159
|
+
'ls', 'find', 'fd', 'tree',
|
|
160
|
+
'wc', 'stat', 'file', 'du', 'df',
|
|
161
|
+
'which', 'type', 'pwd', 'printenv', 'env',
|
|
162
|
+
'readlink', 'realpath', 'basename', 'dirname',
|
|
163
|
+
'jq', 'diff',
|
|
164
|
+
]);
|
|
165
|
+
// git subcommands that only inspect history/state. Deliberately excludes
|
|
166
|
+
// anything that can create or mutate under any flag (branch, tag, stash,
|
|
167
|
+
// remote), so a mutation is never misread as a read.
|
|
168
|
+
const GIT_READ_SUBCOMMANDS = new Set([
|
|
169
|
+
'log', 'diff', 'status', 'show', 'blame', 'grep',
|
|
170
|
+
'shortlog', 'describe', 'rev-parse', 'ls-files',
|
|
171
|
+
]);
|
|
172
|
+
/// True when EVERY segment of the raw command line (split on &&, ;, |) is a
|
|
173
|
+
/// read-only inspection command. A single mutating segment makes the whole
|
|
174
|
+
/// call non-read (`cat x && sed -i ...` edits). Unknown commands are
|
|
175
|
+
/// non-read: the conservative default both call sites want.
|
|
176
|
+
export function isReadShapedBashCommand(rawCommand) {
|
|
177
|
+
if (!rawCommand || !rawCommand.trim())
|
|
178
|
+
return false;
|
|
179
|
+
const stripped = maskForSplitting(stripAnsi(rawCommand));
|
|
180
|
+
const segments = stripped.split(/(?:&&|;|\|)/);
|
|
181
|
+
let sawCommand = false;
|
|
182
|
+
for (const segment of segments) {
|
|
183
|
+
const trimmed = segment.trim();
|
|
184
|
+
if (!trimmed)
|
|
185
|
+
continue;
|
|
186
|
+
const tokens = trimmed.split(/\s+/);
|
|
187
|
+
let i = 0;
|
|
188
|
+
while (i < tokens.length && (/^\w+=/.test(tokens[i]) || COMMAND_PREFIXES.has(basename(tokens[i]))))
|
|
189
|
+
i++;
|
|
190
|
+
const base = i < tokens.length ? basename(tokens[i]) : '';
|
|
191
|
+
if (!base)
|
|
192
|
+
continue;
|
|
193
|
+
sawCommand = true;
|
|
194
|
+
if (base === 'git') {
|
|
195
|
+
const sub = tokens[i + 1];
|
|
196
|
+
if (!sub || !GIT_READ_SUBCOMMANDS.has(sub))
|
|
197
|
+
return false;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (!READ_ONLY_BASH.has(base))
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
return sawCommand;
|
|
204
|
+
}
|