@praeviso/code-env-switch 0.1.2 → 0.1.4

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.
@@ -1,390 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildStatuslineResult = buildStatuslineResult;
4
- /**
5
- * Statusline builder
6
- */
7
- const fs = require("fs");
8
- const path = require("path");
9
- const child_process_1 = require("child_process");
10
- const constants_1 = require("../constants");
11
4
  const type_1 = require("../profile/type");
12
5
  const usage_1 = require("../usage");
13
- const COLOR_ENABLED = !process.env.NO_COLOR && process.env.TERM !== "dumb";
14
- const ANSI_RESET = "\x1b[0m";
15
- const ICON_GIT = "";
16
- const ICON_PROFILE = "👤";
17
- const ICON_MODEL = "";
18
- const ICON_USAGE = "";
19
- const ICON_CONTEXT = "🧠";
20
- const ICON_REVIEW = "📝";
21
- const ICON_CWD = "📁";
22
- function colorize(text, colorCode) {
23
- if (!COLOR_ENABLED)
24
- return text;
25
- return `\x1b[${colorCode}m${text}${ANSI_RESET}`;
26
- }
27
- function dim(text) {
28
- return colorize(text, "2");
29
- }
30
- function getCwdSegment(cwd) {
31
- if (!cwd)
32
- return null;
33
- const base = path.basename(cwd) || cwd;
34
- const segment = `${ICON_CWD} ${base}`;
35
- return dim(segment);
36
- }
37
- function isRecord(value) {
38
- return typeof value === "object" && value !== null && !Array.isArray(value);
39
- }
40
- function readStdinJson() {
41
- if (process.stdin.isTTY)
42
- return null;
43
- try {
44
- const raw = fs.readFileSync(0, "utf8");
45
- const trimmed = raw.trim();
46
- if (!trimmed)
47
- return null;
48
- const parsed = JSON.parse(trimmed);
49
- if (!isRecord(parsed))
50
- return null;
51
- return parsed;
52
- }
53
- catch {
54
- return null;
55
- }
56
- }
57
- function firstNonEmpty(...values) {
58
- for (const value of values) {
59
- if (value === null || value === undefined)
60
- continue;
61
- const text = String(value).trim();
62
- if (text)
63
- return text;
64
- }
65
- return null;
66
- }
67
- function coerceNumber(value) {
68
- if (value === null || value === undefined || value === "")
69
- return null;
70
- const num = Number(value);
71
- if (!Number.isFinite(num))
72
- return null;
73
- return num;
74
- }
75
- function firstNumber(...values) {
76
- for (const value of values) {
77
- const num = coerceNumber(value);
78
- if (num !== null)
79
- return num;
80
- }
81
- return null;
82
- }
83
- function normalizeTypeValue(value) {
84
- if (!value)
85
- return null;
86
- const normalized = (0, type_1.normalizeType)(value);
87
- if (normalized)
88
- return normalized;
89
- const trimmed = String(value).trim();
90
- return trimmed ? trimmed : null;
91
- }
92
- function detectTypeFromEnv() {
93
- const matches = constants_1.DEFAULT_PROFILE_TYPES.filter((type) => {
94
- const suffix = type.toUpperCase();
95
- return (process.env[`CODE_ENV_PROFILE_KEY_${suffix}`] ||
96
- process.env[`CODE_ENV_PROFILE_NAME_${suffix}`]);
97
- });
98
- if (matches.length === 1)
99
- return matches[0];
100
- return null;
101
- }
102
- function resolveEnvProfile(type) {
103
- const genericKey = process.env.CODE_ENV_PROFILE_KEY || null;
104
- const genericName = process.env.CODE_ENV_PROFILE_NAME || null;
105
- if (!type) {
106
- return { key: genericKey, name: genericName };
107
- }
108
- const suffix = type.toUpperCase();
109
- const key = process.env[`CODE_ENV_PROFILE_KEY_${suffix}`] || genericKey;
110
- const name = process.env[`CODE_ENV_PROFILE_NAME_${suffix}`] || genericName;
111
- return { key: key || null, name: name || null };
112
- }
113
- function getModelFromInput(input) {
114
- if (!input)
115
- return null;
116
- const raw = input.model;
117
- if (!raw)
118
- return null;
119
- if (typeof raw === "string")
120
- return raw;
121
- if (isRecord(raw)) {
122
- const displayName = raw.displayName || raw.display_name;
123
- if (displayName)
124
- return String(displayName);
125
- if (raw.id)
126
- return String(raw.id);
127
- }
128
- return null;
129
- }
130
- function getModelProviderFromInput(input) {
131
- if (!input || !input.model_provider)
132
- return null;
133
- const provider = String(input.model_provider).trim();
134
- return provider ? provider : null;
135
- }
136
- function getInputProfile(input) {
137
- if (!input || !isRecord(input.profile))
138
- return null;
139
- return input.profile;
140
- }
141
- function getInputUsage(input) {
142
- var _a, _b, _c, _d;
143
- if (!input)
144
- return null;
145
- if (isRecord(input.usage)) {
146
- return input.usage;
147
- }
148
- const tokenUsage = input.token_usage;
149
- if (tokenUsage === null || tokenUsage === undefined)
150
- return null;
151
- if (typeof tokenUsage === "number") {
152
- return {
153
- todayTokens: null,
154
- totalTokens: coerceNumber(tokenUsage),
155
- inputTokens: null,
156
- outputTokens: null,
157
- };
158
- }
159
- if (isRecord(tokenUsage)) {
160
- const record = tokenUsage;
161
- return {
162
- todayTokens: (_a = firstNumber(record.todayTokens, record.today, record.today_tokens, record.daily, record.daily_tokens)) !== null && _a !== void 0 ? _a : null,
163
- totalTokens: (_b = firstNumber(record.totalTokens, record.total, record.total_tokens)) !== null && _b !== void 0 ? _b : null,
164
- inputTokens: (_c = firstNumber(record.inputTokens, record.input, record.input_tokens)) !== null && _c !== void 0 ? _c : null,
165
- outputTokens: (_d = firstNumber(record.outputTokens, record.output, record.output_tokens)) !== null && _d !== void 0 ? _d : null,
166
- };
167
- }
168
- return null;
169
- }
170
- function getContextUsedTokens(input) {
171
- if (!input)
172
- return null;
173
- return coerceNumber(input.context_window_used_tokens);
174
- }
175
- function getContextLeftPercent(input, type) {
176
- if (!input)
177
- return null;
178
- const raw = coerceNumber(input.context_window_percent);
179
- if (raw === null || raw < 0)
180
- return null;
181
- const percent = raw <= 1 ? raw * 100 : raw;
182
- if (percent > 100)
183
- return null;
184
- const usedTokens = getContextUsedTokens(input);
185
- const normalizedType = normalizeTypeValue(type);
186
- // Prefer treating the percent as "remaining" for codex/claude and when usage is absent.
187
- const preferRemaining = normalizedType === "codex" ||
188
- normalizedType === "claude" ||
189
- usedTokens === null ||
190
- (usedTokens <= 0 && percent >= 99);
191
- const left = preferRemaining ? percent : 100 - percent;
192
- return Math.max(0, Math.min(100, left));
193
- }
194
- function getWorkspaceDir(input) {
195
- if (!input || !isRecord(input.workspace))
196
- return null;
197
- const currentDir = input.workspace.current_dir;
198
- if (currentDir) {
199
- const trimmed = String(currentDir).trim();
200
- if (trimmed)
201
- return trimmed;
202
- }
203
- const projectDir = input.workspace.project_dir;
204
- if (!projectDir)
205
- return null;
206
- const trimmed = String(projectDir).trim();
207
- return trimmed ? trimmed : null;
208
- }
209
- function getGitStatusFromInput(input) {
210
- if (!input || !input.git_branch)
211
- return null;
212
- const branch = String(input.git_branch).trim();
213
- if (!branch)
214
- return null;
215
- return {
216
- branch,
217
- ahead: 0,
218
- behind: 0,
219
- staged: 0,
220
- unstaged: 0,
221
- untracked: 0,
222
- conflicted: 0,
223
- };
224
- }
225
- function getGitStatus(cwd) {
226
- if (!cwd)
227
- return null;
228
- const result = (0, child_process_1.spawnSync)("git", ["-C", cwd, "status", "--porcelain=v2", "-b"], {
229
- encoding: "utf8",
230
- stdio: ["ignore", "pipe", "ignore"],
231
- });
232
- if (result.status !== 0 || !result.stdout)
233
- return null;
234
- const status = {
235
- branch: null,
236
- ahead: 0,
237
- behind: 0,
238
- staged: 0,
239
- unstaged: 0,
240
- untracked: 0,
241
- conflicted: 0,
242
- };
243
- const lines = result.stdout.split(/\r?\n/);
244
- for (const line of lines) {
245
- if (!line)
246
- continue;
247
- if (line.startsWith("# branch.head ")) {
248
- status.branch = line.slice("# branch.head ".length).trim();
249
- continue;
250
- }
251
- if (line.startsWith("# branch.ab ")) {
252
- const parts = line
253
- .slice("# branch.ab ".length)
254
- .trim()
255
- .split(/\s+/);
256
- for (const part of parts) {
257
- if (part.startsWith("+"))
258
- status.ahead = Number(part.slice(1)) || 0;
259
- if (part.startsWith("-"))
260
- status.behind = Number(part.slice(1)) || 0;
261
- }
262
- continue;
263
- }
264
- if (line.startsWith("? ")) {
265
- status.untracked += 1;
266
- continue;
267
- }
268
- if (line.startsWith("u ")) {
269
- status.conflicted += 1;
270
- continue;
271
- }
272
- if (line.startsWith("1 ") || line.startsWith("2 ")) {
273
- const parts = line.split(/\s+/);
274
- const xy = parts[1] || "";
275
- const staged = xy[0];
276
- const unstaged = xy[1];
277
- if (staged && staged !== ".")
278
- status.staged += 1;
279
- if (unstaged && unstaged !== ".")
280
- status.unstaged += 1;
281
- continue;
282
- }
283
- }
284
- if (!status.branch) {
285
- status.branch = "HEAD";
286
- }
287
- return status;
288
- }
289
- function formatGitSegment(status) {
290
- if (!status || !status.branch)
291
- return null;
292
- const meta = [];
293
- const dirtyCount = status.staged + status.unstaged + status.untracked;
294
- if (status.ahead > 0)
295
- meta.push(`↑${status.ahead}`);
296
- if (status.behind > 0)
297
- meta.push(`↓${status.behind}`);
298
- if (status.conflicted > 0)
299
- meta.push(`✖${status.conflicted}`);
300
- if (dirtyCount > 0)
301
- meta.push(`+${dirtyCount}`);
302
- const suffix = meta.length > 0 ? ` [${meta.join("")}]` : "";
303
- const text = `${ICON_GIT} ${status.branch}${suffix}`;
304
- const hasConflicts = status.conflicted > 0;
305
- const isDirty = dirtyCount > 0;
306
- if (hasConflicts)
307
- return colorize(text, "31");
308
- if (isDirty)
309
- return colorize(text, "33");
310
- if (status.ahead > 0 || status.behind > 0)
311
- return colorize(text, "36");
312
- return colorize(text, "32");
313
- }
314
- function resolveUsageFromRecords(config, configPath, type, profileKey, profileName, syncUsage) {
315
- try {
316
- const normalized = (0, type_1.normalizeType)(type || "");
317
- if (!normalized || (!profileKey && !profileName))
318
- return null;
319
- const totals = (0, usage_1.readUsageTotalsIndex)(config, configPath, syncUsage);
320
- if (!totals)
321
- return null;
322
- const usage = (0, usage_1.resolveUsageTotalsForProfile)(totals, normalized, profileKey, profileName);
323
- if (!usage)
324
- return null;
325
- return {
326
- todayTokens: usage.today,
327
- totalTokens: usage.total,
328
- inputTokens: null,
329
- outputTokens: null,
330
- };
331
- }
332
- catch {
333
- return null;
334
- }
335
- }
336
- function formatUsageSegment(usage) {
337
- var _a;
338
- if (!usage)
339
- return null;
340
- const today = (_a = usage.todayTokens) !== null && _a !== void 0 ? _a : (usage.inputTokens !== null || usage.outputTokens !== null
341
- ? (usage.inputTokens || 0) + (usage.outputTokens || 0)
342
- : usage.totalTokens);
343
- if (today === null)
344
- return null;
345
- const text = `Today ${(0, usage_1.formatTokenCount)(today)}`;
346
- return colorize(`${ICON_USAGE} ${text}`, "33");
347
- }
348
- function formatModelSegment(model, provider) {
349
- if (!model)
350
- return null;
351
- const providerLabel = provider ? `${provider}:${model}` : model;
352
- return colorize(`${ICON_MODEL} ${providerLabel}`, "35");
353
- }
354
- function formatProfileSegment(type, profileKey, profileName) {
355
- const name = profileName || profileKey;
356
- if (!name)
357
- return null;
358
- const label = type ? `${type}:${name}` : name;
359
- return colorize(`${ICON_PROFILE} ${label}`, "37");
360
- }
361
- function formatContextSegment(contextLeft) {
362
- if (contextLeft === null)
363
- return null;
364
- const left = Math.max(0, Math.min(100, Math.round(contextLeft)));
365
- return colorize(`${ICON_CONTEXT} ${left}% left`, "36");
366
- }
367
- function formatContextUsedSegment(usedTokens) {
368
- if (usedTokens === null)
369
- return null;
370
- return colorize(`${ICON_CONTEXT} ${(0, usage_1.formatTokenCount)(usedTokens)} used`, "36");
371
- }
372
- function formatModeSegment(reviewMode) {
373
- if (!reviewMode)
374
- return null;
375
- return colorize(`${ICON_REVIEW} review`, "34");
376
- }
6
+ const debug_1 = require("./debug");
7
+ const format_1 = require("./format");
8
+ const git_1 = require("./git");
9
+ const input_1 = require("./input");
10
+ const usage_2 = require("./usage");
11
+ const utils_1 = require("./utils");
377
12
  function buildStatuslineResult(args, config, configPath) {
378
- const stdinInput = readStdinJson();
379
- const inputProfile = getInputProfile(stdinInput);
380
- let typeCandidate = firstNonEmpty(args.type, process.env.CODE_ENV_TYPE, inputProfile ? inputProfile.type : null, stdinInput ? stdinInput.type : null);
13
+ const stdinInput = (0, input_1.readStdinJson)();
14
+ const inputProfile = (0, input_1.getInputProfile)(stdinInput);
15
+ let typeCandidate = (0, utils_1.firstNonEmpty)(args.type, process.env.CODE_ENV_TYPE, inputProfile ? inputProfile.type : null, stdinInput ? stdinInput.type : null);
381
16
  if (!typeCandidate) {
382
- typeCandidate = detectTypeFromEnv();
17
+ typeCandidate = (0, input_1.detectTypeFromEnv)();
383
18
  }
384
- let type = normalizeTypeValue(typeCandidate);
385
- const envProfile = resolveEnvProfile(type);
386
- let profileKey = firstNonEmpty(args.profileKey, envProfile.key, inputProfile ? inputProfile.key : null);
387
- let profileName = firstNonEmpty(args.profileName, envProfile.name, inputProfile ? inputProfile.name : null);
19
+ let type = (0, input_1.normalizeTypeValue)(typeCandidate);
20
+ const envProfile = (0, input_1.resolveEnvProfile)(type);
21
+ const profileKey = (0, utils_1.firstNonEmpty)(args.profileKey, envProfile.key, inputProfile ? inputProfile.key : null);
22
+ let profileName = (0, utils_1.firstNonEmpty)(args.profileName, envProfile.name, inputProfile ? inputProfile.name : null);
388
23
  if (profileKey && !profileName && config.profiles && config.profiles[profileKey]) {
389
24
  const profile = config.profiles[profileKey];
390
25
  profileName = (0, type_1.getProfileDisplayName)(profileKey, profile, type || undefined);
@@ -400,43 +35,81 @@ function buildStatuslineResult(args, config, configPath) {
400
35
  if (inferred)
401
36
  type = inferred;
402
37
  }
403
- const cwd = firstNonEmpty(args.cwd, process.env.CODE_ENV_CWD, getWorkspaceDir(stdinInput), stdinInput ? stdinInput.cwd : null, process.cwd());
404
- const model = firstNonEmpty(args.model, process.env.CODE_ENV_MODEL, getModelFromInput(stdinInput));
405
- const modelProvider = firstNonEmpty(process.env.CODE_ENV_MODEL_PROVIDER, getModelProviderFromInput(stdinInput));
38
+ const cwd = (0, utils_1.firstNonEmpty)(args.cwd, process.env.CODE_ENV_CWD, (0, input_1.getWorkspaceDir)(stdinInput), stdinInput ? stdinInput.cwd : null, process.cwd());
39
+ const sessionId = (0, input_1.getSessionId)(stdinInput);
40
+ const stdinUsageTotals = (0, usage_2.getUsageTotalsFromInput)(stdinInput);
41
+ const usageType = (0, type_1.normalizeType)(type || "");
42
+ (0, debug_1.appendStatuslineDebug)(configPath, {
43
+ timestamp: new Date().toISOString(),
44
+ typeCandidate,
45
+ resolvedType: type,
46
+ usageType,
47
+ profile: { key: profileKey, name: profileName },
48
+ sessionId,
49
+ stdinUsageTotals,
50
+ cwd,
51
+ args: {
52
+ type: args.type,
53
+ profileKey: args.profileKey,
54
+ profileName: args.profileName,
55
+ usageToday: args.usageToday,
56
+ usageTotal: args.usageTotal,
57
+ usageInput: args.usageInput,
58
+ usageOutput: args.usageOutput,
59
+ syncUsage: args.syncUsage,
60
+ },
61
+ env: {
62
+ CODE_ENV_TYPE: process.env.CODE_ENV_TYPE,
63
+ CODE_ENV_PROFILE_KEY: process.env.CODE_ENV_PROFILE_KEY,
64
+ CODE_ENV_PROFILE_NAME: process.env.CODE_ENV_PROFILE_NAME,
65
+ CODE_ENV_CWD: process.env.CODE_ENV_CWD,
66
+ CODE_ENV_STATUSLINE: process.env.CODE_ENV_STATUSLINE,
67
+ },
68
+ input: stdinInput,
69
+ });
70
+ if (args.syncUsage && sessionId && stdinUsageTotals) {
71
+ (0, usage_1.syncUsageFromStatuslineInput)(config, configPath, usageType, profileKey, profileName, sessionId, stdinUsageTotals, cwd);
72
+ }
73
+ const model = (0, utils_1.firstNonEmpty)(args.model, process.env.CODE_ENV_MODEL, (0, input_1.getModelFromInput)(stdinInput));
74
+ const modelProvider = (0, utils_1.firstNonEmpty)(process.env.CODE_ENV_MODEL_PROVIDER, (0, input_1.getModelProviderFromInput)(stdinInput));
406
75
  const usage = {
407
- todayTokens: firstNumber(args.usageToday, process.env.CODE_ENV_USAGE_TODAY),
408
- totalTokens: firstNumber(args.usageTotal, process.env.CODE_ENV_USAGE_TOTAL),
409
- inputTokens: firstNumber(args.usageInput, process.env.CODE_ENV_USAGE_INPUT),
410
- outputTokens: firstNumber(args.usageOutput, process.env.CODE_ENV_USAGE_OUTPUT),
76
+ todayTokens: (0, utils_1.firstNumber)(args.usageToday, process.env.CODE_ENV_USAGE_TODAY),
77
+ totalTokens: (0, utils_1.firstNumber)(args.usageTotal, process.env.CODE_ENV_USAGE_TOTAL),
78
+ inputTokens: (0, utils_1.firstNumber)(args.usageInput, process.env.CODE_ENV_USAGE_INPUT),
79
+ outputTokens: (0, utils_1.firstNumber)(args.usageOutput, process.env.CODE_ENV_USAGE_OUTPUT),
411
80
  };
412
81
  const hasExplicitUsage = usage.todayTokens !== null ||
413
82
  usage.totalTokens !== null ||
414
83
  usage.inputTokens !== null ||
415
84
  usage.outputTokens !== null;
85
+ const stdinUsage = (0, usage_2.normalizeInputUsage)((0, input_1.getInputUsage)(stdinInput));
416
86
  let finalUsage = hasExplicitUsage ? usage : null;
417
87
  if (!finalUsage) {
418
- finalUsage = resolveUsageFromRecords(config, configPath, type, profileKey, profileName, args.syncUsage);
88
+ finalUsage = stdinUsage;
89
+ }
90
+ if (!finalUsage) {
91
+ finalUsage = (0, usage_2.resolveUsageFromRecords)(config, configPath, type, profileKey, profileName, args.syncUsage);
419
92
  }
420
- let gitStatus = getGitStatus(cwd);
93
+ let gitStatus = (0, git_1.getGitStatus)(cwd);
421
94
  if (!gitStatus) {
422
- gitStatus = getGitStatusFromInput(stdinInput);
95
+ gitStatus = (0, input_1.getGitStatusFromInput)(stdinInput);
423
96
  }
424
97
  else {
425
- const inputGit = getGitStatusFromInput(stdinInput);
98
+ const inputGit = (0, input_1.getGitStatusFromInput)(stdinInput);
426
99
  if (inputGit && (!gitStatus.branch || gitStatus.branch === "HEAD")) {
427
100
  gitStatus.branch = inputGit.branch;
428
101
  }
429
102
  }
430
- const gitSegment = formatGitSegment(gitStatus);
431
- const profileSegment = formatProfileSegment(type, profileKey, profileName);
432
- const modelSegment = formatModelSegment(model, modelProvider);
433
- const usageSegment = formatUsageSegment(finalUsage);
434
- const contextLeft = getContextLeftPercent(stdinInput, type);
435
- const contextSegment = formatContextSegment(contextLeft);
436
- const contextUsedTokens = getContextUsedTokens(stdinInput);
437
- const contextUsedSegment = contextSegment === null ? formatContextUsedSegment(contextUsedTokens) : null;
438
- const modeSegment = formatModeSegment((stdinInput === null || stdinInput === void 0 ? void 0 : stdinInput.review_mode) === true);
439
- const cwdSegment = getCwdSegment(cwd);
103
+ const gitSegment = (0, git_1.formatGitSegment)(gitStatus);
104
+ const profileSegment = (0, format_1.formatProfileSegment)(type, profileKey, profileName);
105
+ const modelSegment = (0, format_1.formatModelSegment)(model, modelProvider);
106
+ const usageSegment = (0, format_1.formatUsageSegment)(finalUsage);
107
+ const contextLeft = (0, input_1.getContextLeftPercent)(stdinInput, type);
108
+ const contextSegment = (0, format_1.formatContextSegment)(contextLeft);
109
+ const contextUsedTokens = (0, input_1.getContextUsedTokens)(stdinInput);
110
+ const contextUsedSegment = contextSegment === null ? (0, format_1.formatContextUsedSegment)(contextUsedTokens) : null;
111
+ const modeSegment = (0, format_1.formatModeSegment)((stdinInput === null || stdinInput === void 0 ? void 0 : stdinInput.review_mode) === true);
112
+ const cwdSegment = (0, format_1.getCwdSegment)(cwd);
440
113
  const segments = [];
441
114
  if (gitSegment)
442
115
  segments.push(gitSegment);