@prestyj/core 4.10.1

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/dist/index.cjs ADDED
@@ -0,0 +1,2333 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AuthStorage: () => AuthStorage,
34
+ DEFAULT_MAX_VIDEO_BYTES: () => DEFAULT_MAX_VIDEO_BYTES,
35
+ MODELS: () => MODELS,
36
+ MOONSHOT_OAUTH_KEY: () => MOONSHOT_OAUTH_KEY,
37
+ NotLoggedInError: () => NotLoggedInError,
38
+ TelegramBot: () => TelegramBot,
39
+ closeLogger: () => closeLogger,
40
+ createAutoUpdater: () => createAutoUpdater,
41
+ decodeOggOpus: () => decodeOggOpus,
42
+ downmixToMono: () => downmixToMono,
43
+ generatePKCE: () => generatePKCE,
44
+ getAppPaths: () => getAppPaths,
45
+ getClaudeCliUserAgent: () => getClaudeCliUserAgent,
46
+ getClaudeCodeVersion: () => getClaudeCodeVersion,
47
+ getContextWindow: () => getContextWindow,
48
+ getDefaultModel: () => getDefaultModel,
49
+ getMaxThinkingLevel: () => getMaxThinkingLevel,
50
+ getModel: () => getModel,
51
+ getModelsForProvider: () => getModelsForProvider,
52
+ getNextThinkingLevel: () => getNextThinkingLevel,
53
+ getSessionId: () => getSessionId,
54
+ getSummaryModel: () => getSummaryModel,
55
+ getSupportedThinkingLevels: () => getSupportedThinkingLevels,
56
+ getVideoByteLimit: () => getVideoByteLimit,
57
+ isKimiCodingEndpoint: () => isKimiCodingEndpoint,
58
+ isLoggerOpen: () => isLoggerOpen,
59
+ isModelLoaded: () => isModelLoaded,
60
+ isThinkingLevelSupported: () => isThinkingLevelSupported,
61
+ kimiCodeBaseUrl: () => kimiCodeBaseUrl,
62
+ kimiCodingHeaders: () => kimiCodingHeaders,
63
+ log: () => log,
64
+ loginAnthropic: () => loginAnthropic,
65
+ loginGemini: () => loginGemini,
66
+ loginKimi: () => loginKimi,
67
+ loginOpenAI: () => loginOpenAI,
68
+ openLog: () => openLog,
69
+ refreshAnthropicToken: () => refreshAnthropicToken,
70
+ refreshGeminiToken: () => refreshGeminiToken,
71
+ refreshKimiToken: () => refreshKimiToken,
72
+ refreshOpenAIToken: () => refreshOpenAIToken,
73
+ registerLogCleanup: () => registerLogCleanup,
74
+ resample: () => resample,
75
+ setProgressCallback: () => setProgressCallback,
76
+ transcribeVoice: () => transcribeVoice,
77
+ usesOpenAICodexTransport: () => usesOpenAICodexTransport,
78
+ withFileLock: () => withFileLock
79
+ });
80
+ module.exports = __toCommonJS(index_exports);
81
+
82
+ // src/model-registry.ts
83
+ var MODELS = [
84
+ // ── Anthropic ──────────────────────────────────────────
85
+ // NOTE: Claude Fable 5 (`claude-fable-5`) and Claude Mythos 5
86
+ // (`claude-mythos-5`) are temporarily unavailable, so they're commented out
87
+ // here to keep them out of the /model selector and avoid user confusion.
88
+ // Re-enable once they're generally available again.
89
+ // {
90
+ // id: "claude-fable-5",
91
+ // name: "Claude Fable 5",
92
+ // provider: "anthropic",
93
+ // contextWindow: 1_000_000,
94
+ // maxOutputTokens: 128_000,
95
+ // supportsThinking: true,
96
+ // supportsImages: true,
97
+ // supportsVideo: false,
98
+ // costTier: "high",
99
+ // maxThinkingLevel: "max",
100
+ // },
101
+ // {
102
+ // // Mythos-class model offered through Project Glasswing (limited
103
+ // // availability, invitation-only). Same underlying model as Fable 5 with
104
+ // // some safeguards lifted; kept here so approved accounts can select it.
105
+ // id: "claude-mythos-5",
106
+ // name: "Claude Mythos 5",
107
+ // provider: "anthropic",
108
+ // contextWindow: 1_000_000,
109
+ // maxOutputTokens: 128_000,
110
+ // supportsThinking: true,
111
+ // supportsImages: true,
112
+ // supportsVideo: false,
113
+ // costTier: "high",
114
+ // maxThinkingLevel: "max",
115
+ // },
116
+ {
117
+ id: "claude-opus-4-8",
118
+ name: "Claude Opus 4.8",
119
+ provider: "anthropic",
120
+ contextWindow: 1e6,
121
+ maxOutputTokens: 128e3,
122
+ supportsThinking: true,
123
+ supportsImages: true,
124
+ supportsVideo: false,
125
+ costTier: "high",
126
+ maxThinkingLevel: "max"
127
+ },
128
+ {
129
+ id: "claude-sonnet-4-6",
130
+ name: "Claude Sonnet 4.6",
131
+ provider: "anthropic",
132
+ contextWindow: 1e6,
133
+ maxOutputTokens: 64e3,
134
+ supportsThinking: true,
135
+ supportsImages: true,
136
+ supportsVideo: false,
137
+ costTier: "medium",
138
+ maxThinkingLevel: "max"
139
+ },
140
+ {
141
+ id: "claude-haiku-4-5-20251001",
142
+ name: "Claude Haiku 4.5",
143
+ provider: "anthropic",
144
+ contextWindow: 2e5,
145
+ maxOutputTokens: 64e3,
146
+ supportsThinking: true,
147
+ supportsImages: true,
148
+ supportsVideo: false,
149
+ costTier: "low",
150
+ maxThinkingLevel: "high"
151
+ },
152
+ // ── OpenAI (Codex) ─────────────────────────────────────
153
+ {
154
+ id: "gpt-5.5",
155
+ name: "GPT-5.5",
156
+ provider: "openai",
157
+ contextWindow: 105e4,
158
+ codexContextWindow: 272e3,
159
+ maxOutputTokens: 128e3,
160
+ supportsThinking: true,
161
+ supportsImages: true,
162
+ supportsVideo: false,
163
+ costTier: "high",
164
+ maxThinkingLevel: "xhigh"
165
+ },
166
+ {
167
+ id: "gpt-5.4",
168
+ name: "GPT-5.4",
169
+ provider: "openai",
170
+ contextWindow: 105e4,
171
+ codexContextWindow: 272e3,
172
+ maxOutputTokens: 128e3,
173
+ supportsThinking: true,
174
+ supportsImages: true,
175
+ supportsVideo: false,
176
+ costTier: "high",
177
+ maxThinkingLevel: "xhigh"
178
+ },
179
+ {
180
+ id: "gpt-5.4-mini",
181
+ name: "GPT-5.4 Mini",
182
+ provider: "openai",
183
+ contextWindow: 4e5,
184
+ maxOutputTokens: 128e3,
185
+ supportsThinking: true,
186
+ supportsImages: true,
187
+ supportsVideo: false,
188
+ costTier: "low",
189
+ maxThinkingLevel: "xhigh"
190
+ },
191
+ {
192
+ id: "gpt-5.3-codex",
193
+ name: "GPT-5.3 Codex",
194
+ provider: "openai",
195
+ contextWindow: 4e5,
196
+ maxOutputTokens: 128e3,
197
+ supportsThinking: true,
198
+ supportsImages: true,
199
+ supportsVideo: false,
200
+ costTier: "high",
201
+ maxThinkingLevel: "xhigh"
202
+ },
203
+ // ── Gemini ─────────────────────────────────────────────
204
+ {
205
+ id: "gemini-3.1-flash-lite-preview",
206
+ name: "Gemini 3.1 Flash Lite Preview",
207
+ provider: "gemini",
208
+ contextWindow: 1048576,
209
+ maxOutputTokens: 65536,
210
+ supportsThinking: true,
211
+ supportsImages: true,
212
+ supportsVideo: true,
213
+ maxVideoBytes: 20 * 1024 * 1024,
214
+ costTier: "low",
215
+ maxThinkingLevel: "high"
216
+ },
217
+ {
218
+ id: "gemini-3.5-flash",
219
+ name: "Gemini 3.5 Flash",
220
+ provider: "gemini",
221
+ contextWindow: 1048576,
222
+ maxOutputTokens: 65536,
223
+ supportsThinking: true,
224
+ supportsImages: true,
225
+ supportsVideo: true,
226
+ maxVideoBytes: 20 * 1024 * 1024,
227
+ costTier: "low",
228
+ maxThinkingLevel: "high"
229
+ },
230
+ // ── Moonshot (Kimi) ────────────────────────────────────
231
+ {
232
+ id: "kimi-k2.7-code",
233
+ name: "Kimi K2.7",
234
+ provider: "moonshot",
235
+ contextWindow: 262144,
236
+ maxOutputTokens: 262144,
237
+ supportsThinking: true,
238
+ supportsImages: true,
239
+ supportsVideo: true,
240
+ maxVideoBytes: 100 * 1024 * 1024,
241
+ costTier: "medium",
242
+ maxThinkingLevel: "high"
243
+ },
244
+ // ── Z.AI (GLM) ─────────────────────────────────────────
245
+ {
246
+ id: "glm-5.1",
247
+ name: "GLM-5.1",
248
+ provider: "glm",
249
+ contextWindow: 204800,
250
+ maxOutputTokens: 131072,
251
+ supportsThinking: true,
252
+ supportsImages: false,
253
+ supportsVideo: false,
254
+ costTier: "medium",
255
+ maxThinkingLevel: "high"
256
+ },
257
+ {
258
+ id: "glm-4.7",
259
+ name: "GLM-4.7",
260
+ provider: "glm",
261
+ contextWindow: 2e5,
262
+ maxOutputTokens: 131072,
263
+ supportsThinking: true,
264
+ supportsImages: false,
265
+ supportsVideo: false,
266
+ costTier: "low",
267
+ maxThinkingLevel: "high"
268
+ },
269
+ {
270
+ id: "glm-4.7-flash",
271
+ name: "GLM-4.7 Flash",
272
+ provider: "glm",
273
+ contextWindow: 2e5,
274
+ maxOutputTokens: 131072,
275
+ supportsThinking: true,
276
+ supportsImages: false,
277
+ supportsVideo: false,
278
+ costTier: "low",
279
+ maxThinkingLevel: "high"
280
+ },
281
+ // ── MiniMax ────────────────────────────────────────────
282
+ {
283
+ id: "MiniMax-M3",
284
+ name: "MiniMax M3",
285
+ provider: "minimax",
286
+ contextWindow: 1e6,
287
+ maxOutputTokens: 131072,
288
+ supportsThinking: true,
289
+ supportsImages: true,
290
+ supportsVideo: true,
291
+ maxVideoBytes: 50 * 1024 * 1024,
292
+ costTier: "medium",
293
+ maxThinkingLevel: "high"
294
+ },
295
+ // ── Xiaomi (MiMo) ──────────────────────────────────────
296
+ // Pro series: text-only coding/agentic flagship. The legacy mimo-v2-pro
297
+ // auto-routes to v2.5 on 2026-06-01 and is fully deprecated by 2026-06-30.
298
+ {
299
+ id: "mimo-v2.5-pro",
300
+ name: "MiMo-V2.5-Pro",
301
+ provider: "xiaomi",
302
+ contextWindow: 1e6,
303
+ maxOutputTokens: 131072,
304
+ supportsThinking: true,
305
+ supportsImages: false,
306
+ supportsVideo: false,
307
+ costTier: "medium",
308
+ maxThinkingLevel: "high"
309
+ },
310
+ // Omni series: native full-modal understanding (image + audio + video).
311
+ // Video/image ride the OpenAI-compatible transport as base64 data URLs
312
+ // (`video_url`/`image_url`), which the shared transform already emits.
313
+ {
314
+ id: "mimo-v2.5",
315
+ name: "MiMo-V2.5",
316
+ provider: "xiaomi",
317
+ contextWindow: 1e6,
318
+ maxOutputTokens: 131072,
319
+ supportsThinking: true,
320
+ supportsImages: true,
321
+ supportsVideo: true,
322
+ maxVideoBytes: 36 * 1024 * 1024,
323
+ costTier: "medium",
324
+ maxThinkingLevel: "high"
325
+ },
326
+ // ── DeepSeek ───────────────────────────────────────────
327
+ {
328
+ id: "deepseek-v4-pro",
329
+ name: "DeepSeek V4 Pro",
330
+ provider: "deepseek",
331
+ contextWindow: 1048576,
332
+ maxOutputTokens: 384e3,
333
+ supportsThinking: true,
334
+ supportsImages: false,
335
+ supportsVideo: false,
336
+ costTier: "high",
337
+ // DeepSeek V4 maps `xhigh` → its internal `max` tier.
338
+ maxThinkingLevel: "xhigh"
339
+ },
340
+ {
341
+ id: "deepseek-v4-flash",
342
+ name: "DeepSeek V4 Flash",
343
+ provider: "deepseek",
344
+ contextWindow: 1048576,
345
+ maxOutputTokens: 384e3,
346
+ supportsThinking: true,
347
+ supportsImages: false,
348
+ supportsVideo: false,
349
+ costTier: "low",
350
+ maxThinkingLevel: "xhigh"
351
+ },
352
+ // ── OpenRouter ─────────────────────────────────────────
353
+ {
354
+ id: "qwen/qwen3.6-plus",
355
+ name: "Qwen3.6-Plus",
356
+ provider: "openrouter",
357
+ contextWindow: 1e6,
358
+ maxOutputTokens: 65536,
359
+ supportsThinking: true,
360
+ supportsImages: false,
361
+ supportsVideo: false,
362
+ costTier: "medium",
363
+ maxThinkingLevel: "high"
364
+ }
365
+ ];
366
+ function getModel(id) {
367
+ return MODELS.find((m) => m.id === id);
368
+ }
369
+ function getModelsForProvider(provider) {
370
+ return MODELS.filter((m) => m.provider === provider);
371
+ }
372
+ var DEFAULT_MAX_VIDEO_BYTES = 20 * 1024 * 1024;
373
+ function getVideoByteLimit(modelId) {
374
+ const model = getModel(modelId);
375
+ if (!model?.supportsVideo) return void 0;
376
+ return model.maxVideoBytes ?? DEFAULT_MAX_VIDEO_BYTES;
377
+ }
378
+ function getDefaultModel(provider) {
379
+ if (provider === "xiaomi") return MODELS.find((m) => m.id === "mimo-v2.5-pro");
380
+ if (provider === "openai") return MODELS.find((m) => m.id === "gpt-5.5");
381
+ if (provider === "gemini") return MODELS.find((m) => m.id === "gemini-3.1-flash-lite-preview");
382
+ if (provider === "glm") return MODELS.find((m) => m.id === "glm-5.1");
383
+ if (provider === "moonshot") return MODELS.find((m) => m.id === "kimi-k2.7-code");
384
+ if (provider === "minimax") return MODELS.find((m) => m.id === "MiniMax-M3");
385
+ if (provider === "deepseek") return MODELS.find((m) => m.id === "deepseek-v4-pro");
386
+ if (provider === "openrouter") return MODELS.find((m) => m.id === "qwen/qwen3.6-plus");
387
+ return MODELS.find((m) => m.id === "claude-sonnet-4-6");
388
+ }
389
+ function usesOpenAICodexTransport(options) {
390
+ return options?.provider === "openai" && Boolean(options.accountId);
391
+ }
392
+ function getContextWindow(modelId, options) {
393
+ const model = getModel(modelId);
394
+ if (!model) return 2e5;
395
+ if (usesOpenAICodexTransport(options) && model.codexContextWindow) {
396
+ return model.codexContextWindow;
397
+ }
398
+ return model.contextWindow;
399
+ }
400
+ function getMaxThinkingLevel(modelId) {
401
+ return getModel(modelId)?.maxThinkingLevel ?? "high";
402
+ }
403
+ function getSummaryModel(provider, currentModelId) {
404
+ if (provider === "anthropic") {
405
+ return MODELS.find((m) => m.id === "claude-sonnet-4-6");
406
+ }
407
+ if (provider === "openai" || provider === "glm" || provider === "deepseek") {
408
+ const low = getModelsForProvider(provider).find((m) => m.costTier === "low");
409
+ if (low) return low;
410
+ }
411
+ return getModel(currentModelId) ?? getDefaultModel(provider);
412
+ }
413
+
414
+ // src/thinking-level.ts
415
+ var OPENAI_GPT_THINKING_LEVELS = ["medium", "high", "xhigh"];
416
+ var ANTHROPIC_OPUS_48_47_THINKING_LEVELS = [
417
+ "low",
418
+ "medium",
419
+ "high",
420
+ "xhigh",
421
+ "max"
422
+ ];
423
+ var ANTHROPIC_ADAPTIVE_THINKING_LEVELS = [
424
+ "low",
425
+ "medium",
426
+ "high",
427
+ "max"
428
+ ];
429
+ function isOpenAIGptModel(provider, model) {
430
+ return provider === "openai" && model.startsWith("gpt-");
431
+ }
432
+ function isAnthropicOpus48Or47Model(provider, model) {
433
+ return provider === "anthropic" && /opus-4-8|opus-4-7/.test(model);
434
+ }
435
+ function isAnthropicAdaptiveModel(provider, model) {
436
+ return provider === "anthropic" && /opus-4-8|opus-4-7|opus-4-6|sonnet-4-6|fable-5|mythos-5/.test(model);
437
+ }
438
+ function getSupportedThinkingLevels(provider, model) {
439
+ const maxLevel = getMaxThinkingLevel(model);
440
+ if (isAnthropicAdaptiveModel(provider, model)) {
441
+ const levels = isAnthropicOpus48Or47Model(provider, model) ? ANTHROPIC_OPUS_48_47_THINKING_LEVELS : ANTHROPIC_ADAPTIVE_THINKING_LEVELS;
442
+ const maxIndex2 = levels.indexOf(maxLevel);
443
+ if (maxIndex2 === -1) return ["low", "medium", "high"];
444
+ return levels.slice(0, maxIndex2 + 1);
445
+ }
446
+ if (!isOpenAIGptModel(provider, model)) return [maxLevel];
447
+ const maxIndex = OPENAI_GPT_THINKING_LEVELS.indexOf(maxLevel);
448
+ if (maxIndex === -1) return ["medium"];
449
+ return OPENAI_GPT_THINKING_LEVELS.slice(0, maxIndex + 1);
450
+ }
451
+ function isThinkingLevelSupported(provider, model, level) {
452
+ return getSupportedThinkingLevels(provider, model).includes(level);
453
+ }
454
+ function getNextThinkingLevel(provider, model, current) {
455
+ const supportedLevels = getSupportedThinkingLevels(provider, model);
456
+ const shouldCycleLevels = isOpenAIGptModel(provider, model) || isAnthropicAdaptiveModel(provider, model);
457
+ if (!shouldCycleLevels) {
458
+ return current ? void 0 : supportedLevels[0];
459
+ }
460
+ if (!current) return supportedLevels[0];
461
+ const index = supportedLevels.indexOf(current);
462
+ if (index === -1) return supportedLevels[0];
463
+ return supportedLevels[index + 1];
464
+ }
465
+
466
+ // src/paths.ts
467
+ var import_node_path = __toESM(require("path"), 1);
468
+ var import_node_os = __toESM(require("os"), 1);
469
+ function getAppPaths() {
470
+ const agentDir = import_node_path.default.join(import_node_os.default.homedir(), ".ezcoder");
471
+ return {
472
+ agentDir,
473
+ sessionsDir: import_node_path.default.join(agentDir, "sessions"),
474
+ settingsFile: import_node_path.default.join(agentDir, "settings.json"),
475
+ authFile: import_node_path.default.join(agentDir, "auth.json"),
476
+ telegramFile: import_node_path.default.join(agentDir, "telegram.json"),
477
+ agentHomeFile: import_node_path.default.join(agentDir, "agent-home.json"),
478
+ mcpFile: import_node_path.default.join(agentDir, "mcp.json"),
479
+ logFile: import_node_path.default.join(agentDir, "debug.log"),
480
+ skillsDir: import_node_path.default.join(agentDir, "skills"),
481
+ extensionsDir: import_node_path.default.join(agentDir, "extensions"),
482
+ agentsDir: import_node_path.default.join(agentDir, "agents")
483
+ };
484
+ }
485
+
486
+ // src/logger.ts
487
+ var import_node_fs = __toESM(require("fs"), 1);
488
+ var import_node_path2 = __toESM(require("path"), 1);
489
+ var import_node_crypto = require("crypto");
490
+ var MAX_BYTES = 10 * 1024 * 1024;
491
+ var fd = null;
492
+ var sessionId = "";
493
+ var appName = "app";
494
+ var cleanups = [];
495
+ function rotateIfNeeded(filePath) {
496
+ try {
497
+ const st = import_node_fs.default.statSync(filePath);
498
+ if (st.size < MAX_BYTES) return;
499
+ const rotated = `${filePath}.1`;
500
+ try {
501
+ import_node_fs.default.unlinkSync(rotated);
502
+ } catch {
503
+ }
504
+ import_node_fs.default.renameSync(filePath, rotated);
505
+ } catch {
506
+ }
507
+ }
508
+ function openLog(filePath, name) {
509
+ if (fd !== null) return false;
510
+ appName = name;
511
+ try {
512
+ import_node_fs.default.mkdirSync(import_node_path2.default.dirname(filePath), { recursive: true, mode: 448 });
513
+ } catch {
514
+ }
515
+ rotateIfNeeded(filePath);
516
+ try {
517
+ fd = import_node_fs.default.openSync(filePath, "a");
518
+ } catch {
519
+ return false;
520
+ }
521
+ sessionId = (0, import_node_crypto.randomBytes)(4).toString("hex");
522
+ try {
523
+ import_node_fs.default.writeSync(fd, "\n");
524
+ } catch {
525
+ }
526
+ return true;
527
+ }
528
+ function getSessionId() {
529
+ return sessionId;
530
+ }
531
+ function isLoggerOpen() {
532
+ return fd !== null;
533
+ }
534
+ function log(level, category, message, data) {
535
+ if (fd === null) return;
536
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
537
+ let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${message}`;
538
+ if (data) {
539
+ const pairs = Object.entries(data).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
540
+ if (pairs) line += ` ${pairs}`;
541
+ }
542
+ line += "\n";
543
+ try {
544
+ import_node_fs.default.writeSync(fd, line);
545
+ } catch {
546
+ }
547
+ }
548
+ function registerLogCleanup(fn) {
549
+ cleanups.push(fn);
550
+ }
551
+ function closeLogger(opts) {
552
+ if (fd === null) return;
553
+ if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
554
+ try {
555
+ import_node_fs.default.closeSync(fd);
556
+ } catch {
557
+ }
558
+ fd = null;
559
+ for (const unsub of cleanups) unsub();
560
+ cleanups = [];
561
+ }
562
+
563
+ // src/file-lock.ts
564
+ var import_promises = __toESM(require("fs/promises"), 1);
565
+ var import_promises2 = require("timers/promises");
566
+ var STALE_TIMEOUT_MS = 1e4;
567
+ var RETRY_INTERVAL_MS = 50;
568
+ var MAX_WAIT_MS = 5e3;
569
+ async function withFileLock(filePath, fn) {
570
+ const lockPath = filePath + ".lock";
571
+ await acquireLock(lockPath);
572
+ try {
573
+ return await fn();
574
+ } finally {
575
+ await releaseLock(lockPath);
576
+ }
577
+ }
578
+ async function acquireLock(lockPath) {
579
+ const startTime = Date.now();
580
+ while (true) {
581
+ try {
582
+ const info = { pid: process.pid, timestamp: Date.now() };
583
+ await import_promises.default.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
584
+ return;
585
+ } catch (err) {
586
+ if (err.code !== "EEXIST") throw err;
587
+ try {
588
+ const content = await import_promises.default.readFile(lockPath, "utf-8");
589
+ const info = JSON.parse(content);
590
+ const isProcessAlive = isAlive(info.pid);
591
+ const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
592
+ if (!isProcessAlive || isStale) {
593
+ await import_promises.default.unlink(lockPath).catch(() => {
594
+ });
595
+ continue;
596
+ }
597
+ } catch {
598
+ await import_promises.default.unlink(lockPath).catch(() => {
599
+ });
600
+ continue;
601
+ }
602
+ if (Date.now() - startTime > MAX_WAIT_MS) {
603
+ await import_promises.default.unlink(lockPath).catch(() => {
604
+ });
605
+ continue;
606
+ }
607
+ await (0, import_promises2.setTimeout)(RETRY_INTERVAL_MS);
608
+ }
609
+ }
610
+ }
611
+ async function releaseLock(lockPath) {
612
+ await import_promises.default.unlink(lockPath).catch(() => {
613
+ });
614
+ }
615
+ function isAlive(pid) {
616
+ try {
617
+ process.kill(pid, 0);
618
+ return true;
619
+ } catch (err) {
620
+ if (err.code === "EPERM") return true;
621
+ return false;
622
+ }
623
+ }
624
+
625
+ // src/claude-code-version.ts
626
+ var import_promises3 = __toESM(require("fs/promises"), 1);
627
+ var import_node_path3 = __toESM(require("path"), 1);
628
+ var NPM_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
629
+ var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
630
+ var FETCH_TIMEOUT_MS = 3e3;
631
+ var FALLBACK_VERSION = "2.1.88";
632
+ var memoryCache = null;
633
+ var inflight = null;
634
+ function cachePath() {
635
+ return import_node_path3.default.join(getAppPaths().agentDir, "claude-code-version.json");
636
+ }
637
+ async function readDiskCache() {
638
+ try {
639
+ const raw = await import_promises3.default.readFile(cachePath(), "utf-8");
640
+ const parsed = JSON.parse(raw);
641
+ if (typeof parsed.version === "string" && typeof parsed.fetchedAt === "number") {
642
+ return parsed;
643
+ }
644
+ return null;
645
+ } catch {
646
+ return null;
647
+ }
648
+ }
649
+ async function writeDiskCache(data) {
650
+ try {
651
+ await import_promises3.default.mkdir(getAppPaths().agentDir, { recursive: true, mode: 448 });
652
+ await import_promises3.default.writeFile(cachePath(), JSON.stringify(data), { mode: 384 });
653
+ } catch (err) {
654
+ log(
655
+ "WARN",
656
+ "claude-code-version",
657
+ `Failed to write cache: ${err instanceof Error ? err.message : String(err)}`
658
+ );
659
+ }
660
+ }
661
+ async function fetchLatest() {
662
+ const controller = new AbortController();
663
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
664
+ try {
665
+ const response = await fetch(NPM_LATEST_URL, { signal: controller.signal });
666
+ if (!response.ok) return null;
667
+ const data = await response.json();
668
+ if (typeof data.version === "string" && /^\d/.test(data.version)) {
669
+ return data.version;
670
+ }
671
+ return null;
672
+ } catch {
673
+ return null;
674
+ } finally {
675
+ clearTimeout(timer);
676
+ }
677
+ }
678
+ async function getClaudeCodeVersion() {
679
+ if (memoryCache && Date.now() < memoryCache.expiresAt) {
680
+ return memoryCache.version;
681
+ }
682
+ if (inflight) return inflight;
683
+ inflight = (async () => {
684
+ const disk = await readDiskCache();
685
+ const diskFresh = disk && Date.now() - disk.fetchedAt < CACHE_TTL_MS;
686
+ if (disk && diskFresh) {
687
+ memoryCache = { version: disk.version, expiresAt: Date.now() + CACHE_TTL_MS };
688
+ return disk.version;
689
+ }
690
+ const fetched = await fetchLatest();
691
+ if (fetched) {
692
+ await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
693
+ memoryCache = { version: fetched, expiresAt: Date.now() + CACHE_TTL_MS };
694
+ return fetched;
695
+ }
696
+ const resolved = disk?.version ?? FALLBACK_VERSION;
697
+ memoryCache = { version: resolved, expiresAt: Date.now() + 5 * 60 * 1e3 };
698
+ log(
699
+ "WARN",
700
+ "claude-code-version",
701
+ `Failed to fetch latest Claude Code version; using ${resolved}`
702
+ );
703
+ return resolved;
704
+ })();
705
+ try {
706
+ return await inflight;
707
+ } finally {
708
+ inflight = null;
709
+ }
710
+ }
711
+ async function getClaudeCliUserAgent() {
712
+ const version = await getClaudeCodeVersion();
713
+ return `claude-cli/${version} (external, cli)`;
714
+ }
715
+
716
+ // src/auth-storage.ts
717
+ var import_promises4 = __toESM(require("fs/promises"), 1);
718
+ var import_node_crypto6 = __toESM(require("crypto"), 1);
719
+
720
+ // src/oauth/anthropic.ts
721
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
722
+
723
+ // src/oauth/pkce.ts
724
+ function base64urlEncode(bytes) {
725
+ let binary = "";
726
+ for (const byte of bytes) {
727
+ binary += String.fromCharCode(byte);
728
+ }
729
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
730
+ }
731
+ async function generatePKCE() {
732
+ const verifierBytes = new Uint8Array(32);
733
+ crypto.getRandomValues(verifierBytes);
734
+ const verifier = base64urlEncode(verifierBytes);
735
+ const data = new TextEncoder().encode(verifier);
736
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
737
+ const challenge = base64urlEncode(new Uint8Array(hashBuffer));
738
+ return { verifier, challenge };
739
+ }
740
+
741
+ // src/oauth/anthropic.ts
742
+ var CLIENT_ID = atob("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
743
+ var AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
744
+ var TOKEN_URLS = [
745
+ "https://platform.claude.com/v1/oauth/token",
746
+ "https://console.anthropic.com/v1/oauth/token"
747
+ ];
748
+ var REDIRECT_URI = "https://platform.claude.com/oauth/code/callback";
749
+ var SCOPES = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
750
+ async function postTokenRequest(body, label) {
751
+ const encoded = JSON.stringify(body);
752
+ const headers = {
753
+ "Content-Type": "application/json",
754
+ "User-Agent": await getClaudeCliUserAgent(),
755
+ "anthropic-beta": "oauth-2025-04-20"
756
+ };
757
+ let lastError = null;
758
+ for (const url of TOKEN_URLS) {
759
+ let response;
760
+ try {
761
+ response = await fetch(url, { method: "POST", headers, body: encoded });
762
+ } catch (err) {
763
+ lastError = err instanceof Error ? err : new Error(String(err));
764
+ continue;
765
+ }
766
+ if (response.ok) {
767
+ return await response.json();
768
+ }
769
+ const text = await response.text();
770
+ if (response.status >= 400 && response.status < 500) {
771
+ throw new Error(`Anthropic ${label} failed (${response.status}): ${text}`);
772
+ }
773
+ lastError = new Error(`Anthropic ${label} failed (${response.status}): ${text}`);
774
+ }
775
+ throw lastError ?? new Error(`Anthropic ${label} failed: all endpoints unreachable`);
776
+ }
777
+ function toCredentials(data) {
778
+ return {
779
+ accessToken: data.access_token,
780
+ refreshToken: data.refresh_token,
781
+ expiresAt: Date.now() + data.expires_in * 1e3 - 5 * 60 * 1e3
782
+ };
783
+ }
784
+ async function loginAnthropic(callbacks) {
785
+ const { verifier, challenge } = await generatePKCE();
786
+ const state = import_node_crypto2.default.randomBytes(16).toString("hex");
787
+ const params = new URLSearchParams({
788
+ code: "true",
789
+ client_id: CLIENT_ID,
790
+ response_type: "code",
791
+ redirect_uri: REDIRECT_URI,
792
+ scope: SCOPES,
793
+ code_challenge: challenge,
794
+ code_challenge_method: "S256",
795
+ state
796
+ });
797
+ const authUrl = `${AUTHORIZE_URL}?${params}`;
798
+ callbacks.onOpenUrl(authUrl);
799
+ const raw = await callbacks.onPromptCode("Paste the code from the browser (format: code#state):");
800
+ const parts = raw.trim().split("#");
801
+ if (parts.length !== 2 || !parts[0] || parts[1] !== state) {
802
+ throw new Error("Invalid code or state mismatch. Please try again.");
803
+ }
804
+ return exchangeAnthropicCode(parts[0], parts[1], verifier);
805
+ }
806
+ async function exchangeAnthropicCode(code, state, verifier) {
807
+ const data = await postTokenRequest(
808
+ {
809
+ grant_type: "authorization_code",
810
+ client_id: CLIENT_ID,
811
+ code,
812
+ state,
813
+ redirect_uri: REDIRECT_URI,
814
+ code_verifier: verifier
815
+ },
816
+ "token exchange"
817
+ );
818
+ return toCredentials(data);
819
+ }
820
+ async function refreshAnthropicToken(refreshToken) {
821
+ const data = await postTokenRequest(
822
+ {
823
+ grant_type: "refresh_token",
824
+ client_id: CLIENT_ID,
825
+ refresh_token: refreshToken
826
+ },
827
+ "token refresh"
828
+ );
829
+ return toCredentials(data);
830
+ }
831
+
832
+ // src/oauth/openai.ts
833
+ var import_node_http = __toESM(require("http"), 1);
834
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
835
+ var CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
836
+ var AUTHORIZE_URL2 = "https://auth.openai.com/oauth/authorize";
837
+ var TOKEN_URL = "https://auth.openai.com/oauth/token";
838
+ var REDIRECT_URI2 = "http://localhost:1455/auth/callback";
839
+ var SCOPE = "openid profile email offline_access api.connectors.read api.connectors.invoke";
840
+ var JWT_CLAIM_PATH = "https://api.openai.com/auth";
841
+ async function loginOpenAI(callbacks) {
842
+ const { verifier, challenge } = await generatePKCE();
843
+ const state = import_node_crypto3.default.randomBytes(16).toString("hex");
844
+ const url = new URL(AUTHORIZE_URL2);
845
+ url.searchParams.set("response_type", "code");
846
+ url.searchParams.set("client_id", CLIENT_ID2);
847
+ url.searchParams.set("redirect_uri", REDIRECT_URI2);
848
+ url.searchParams.set("scope", SCOPE);
849
+ url.searchParams.set("code_challenge", challenge);
850
+ url.searchParams.set("code_challenge_method", "S256");
851
+ url.searchParams.set("state", state);
852
+ url.searchParams.set("prompt", "login");
853
+ url.searchParams.set("id_token_add_organizations", "true");
854
+ url.searchParams.set("codex_cli_simplified_flow", "true");
855
+ url.searchParams.set("originator", "ezcoder");
856
+ let code;
857
+ try {
858
+ code = await loginWithServer(url.toString(), state, callbacks);
859
+ } catch {
860
+ callbacks.onOpenUrl(url.toString());
861
+ const raw = await callbacks.onPromptCode(
862
+ "Could not start local server. Paste the callback URL or code from the browser:"
863
+ );
864
+ const parsed = parseAuthorizationInput(raw);
865
+ if (!parsed.code) {
866
+ throw new Error("No authorization code found in input.");
867
+ }
868
+ code = parsed.code;
869
+ }
870
+ const creds = await exchangeOpenAICode(code, verifier);
871
+ const accountId = getAccountId(creds.accessToken);
872
+ if (!accountId) {
873
+ throw new Error("Failed to extract accountId from OpenAI token.");
874
+ }
875
+ creds.accountId = accountId;
876
+ return creds;
877
+ }
878
+ function parseAuthorizationInput(input) {
879
+ const value = input.trim();
880
+ if (!value) return {};
881
+ try {
882
+ const url = new URL(value);
883
+ return {
884
+ code: url.searchParams.get("code") ?? void 0,
885
+ state: url.searchParams.get("state") ?? void 0
886
+ };
887
+ } catch {
888
+ }
889
+ if (value.includes("#")) {
890
+ const [code, state] = value.split("#", 2);
891
+ return { code, state };
892
+ }
893
+ if (value.includes("code=")) {
894
+ const params = new URLSearchParams(value);
895
+ return {
896
+ code: params.get("code") ?? void 0,
897
+ state: params.get("state") ?? void 0
898
+ };
899
+ }
900
+ return { code: value };
901
+ }
902
+ function decodeJwt(token) {
903
+ try {
904
+ const parts = token.split(".");
905
+ if (parts.length !== 3) return null;
906
+ const decoded = atob(parts[1]);
907
+ return JSON.parse(decoded);
908
+ } catch {
909
+ return null;
910
+ }
911
+ }
912
+ function getAccountId(accessToken) {
913
+ const payload = decodeJwt(accessToken);
914
+ const auth = payload?.[JWT_CLAIM_PATH];
915
+ const accountId = auth?.chatgpt_account_id;
916
+ return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
917
+ }
918
+ async function loginWithServer(authUrl, expectedState, callbacks) {
919
+ return new Promise((resolve, reject) => {
920
+ let receivedCode = null;
921
+ const server = import_node_http.default.createServer((req, res) => {
922
+ const url = new URL(req.url || "", "http://localhost");
923
+ if (url.pathname !== "/auth/callback") {
924
+ res.statusCode = 404;
925
+ res.end("Not found");
926
+ return;
927
+ }
928
+ if (url.searchParams.get("state") !== expectedState) {
929
+ res.statusCode = 400;
930
+ res.end("State mismatch");
931
+ return;
932
+ }
933
+ receivedCode = url.searchParams.get("code");
934
+ res.writeHead(200, { "Content-Type": "text/html" });
935
+ res.end("<html><body><h1>Login successful!</h1><p>You can close this tab.</p></body></html>");
936
+ server.close();
937
+ });
938
+ server.on("error", (err) => {
939
+ reject(err);
940
+ });
941
+ server.listen(1455, "127.0.0.1", () => {
942
+ callbacks.onOpenUrl(authUrl);
943
+ callbacks.onStatus("Waiting for browser callback...");
944
+ });
945
+ const timeout = setTimeout(() => {
946
+ if (!receivedCode) {
947
+ server.close();
948
+ }
949
+ }, 12e4);
950
+ timeout.unref();
951
+ server.on("close", () => {
952
+ clearTimeout(timeout);
953
+ if (receivedCode) {
954
+ resolve(receivedCode);
955
+ } else {
956
+ reject(new Error("Server closed without receiving code"));
957
+ }
958
+ });
959
+ });
960
+ }
961
+ async function exchangeOpenAICode(code, verifier) {
962
+ const response = await fetch(TOKEN_URL, {
963
+ method: "POST",
964
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
965
+ body: new URLSearchParams({
966
+ grant_type: "authorization_code",
967
+ client_id: CLIENT_ID2,
968
+ code,
969
+ redirect_uri: REDIRECT_URI2,
970
+ code_verifier: verifier
971
+ })
972
+ });
973
+ if (!response.ok) {
974
+ const text = await response.text();
975
+ throw new Error(`OpenAI token exchange failed (${response.status}): ${text}`);
976
+ }
977
+ const data = await response.json();
978
+ return {
979
+ accessToken: data.access_token,
980
+ refreshToken: data.refresh_token,
981
+ expiresAt: Date.now() + data.expires_in * 1e3
982
+ };
983
+ }
984
+ async function refreshOpenAIToken(refreshToken) {
985
+ const response = await fetch(TOKEN_URL, {
986
+ method: "POST",
987
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
988
+ body: new URLSearchParams({
989
+ grant_type: "refresh_token",
990
+ refresh_token: refreshToken,
991
+ client_id: CLIENT_ID2
992
+ })
993
+ });
994
+ if (!response.ok) {
995
+ const text = await response.text();
996
+ throw new Error(`OpenAI token refresh failed (${response.status}): ${text}`);
997
+ }
998
+ const data = await response.json();
999
+ const creds = {
1000
+ accessToken: data.access_token,
1001
+ refreshToken: data.refresh_token,
1002
+ expiresAt: Date.now() + data.expires_in * 1e3
1003
+ };
1004
+ const accountId = getAccountId(creds.accessToken);
1005
+ if (accountId) {
1006
+ creds.accountId = accountId;
1007
+ }
1008
+ return creds;
1009
+ }
1010
+
1011
+ // src/oauth/gemini.ts
1012
+ var import_node_http2 = __toESM(require("http"), 1);
1013
+ var import_node_crypto4 = __toESM(require("crypto"), 1);
1014
+ var CLIENT_ID_ENV = "GGCODER_GEMINI_OAUTH_CLIENT_ID";
1015
+ var CLIENT_SECRET_ENV = "GGCODER_GEMINI_OAUTH_CLIENT_SECRET";
1016
+ var DEFAULT_CLIENT_ID = "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
1017
+ var DEFAULT_CLIENT_SECRET = "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";
1018
+ var AUTHORIZE_URL3 = "https://accounts.google.com/o/oauth2/v2/auth";
1019
+ var TOKEN_URL2 = "https://oauth2.googleapis.com/token";
1020
+ var CODE_ASSIST_BASE_URL = "https://cloudcode-pa.googleapis.com";
1021
+ var CODE_ASSIST_API_VERSION = "v1internal";
1022
+ var CODE_ASSIST_POST_RETRIES = 3;
1023
+ var CODE_ASSIST_POST_RETRY_DELAY_MS = 100;
1024
+ var SCOPE2 = [
1025
+ "https://www.googleapis.com/auth/cloud-platform",
1026
+ "https://www.googleapis.com/auth/userinfo.email",
1027
+ "https://www.googleapis.com/auth/userinfo.profile"
1028
+ ].join(" ");
1029
+ var USER_TIER_FREE = "free-tier";
1030
+ var USER_TIER_LEGACY = "legacy-tier";
1031
+ var USER_TIER_STANDARD = "standard-tier";
1032
+ var VALIDATION_REQUIRED_REASON = "VALIDATION_REQUIRED";
1033
+ var VPC_SC_REASON = "SECURITY_POLICY_VIOLATED";
1034
+ var CodeAssistHttpError = class extends Error {
1035
+ status;
1036
+ body;
1037
+ constructor(label, status, body) {
1038
+ super(`Gemini Code Assist ${label} failed (${status}): ${body}`);
1039
+ this.name = "CodeAssistHttpError";
1040
+ this.status = status;
1041
+ this.body = body;
1042
+ }
1043
+ };
1044
+ async function loginGemini(callbacks) {
1045
+ const { clientId, clientSecret } = getGeminiOAuthClientCredentials();
1046
+ const { verifier, challenge } = await generatePKCE();
1047
+ const state = import_node_crypto4.default.randomBytes(32).toString("hex");
1048
+ const redirectUri = await getLoopbackRedirectUri();
1049
+ const url = new URL(AUTHORIZE_URL3);
1050
+ url.searchParams.set("response_type", "code");
1051
+ url.searchParams.set("client_id", clientId);
1052
+ url.searchParams.set("redirect_uri", redirectUri);
1053
+ url.searchParams.set("scope", SCOPE2);
1054
+ url.searchParams.set("access_type", "offline");
1055
+ url.searchParams.set("prompt", "consent");
1056
+ url.searchParams.set("code_challenge", challenge);
1057
+ url.searchParams.set("code_challenge_method", "S256");
1058
+ url.searchParams.set("state", state);
1059
+ let code;
1060
+ try {
1061
+ code = await loginWithServer2(url.toString(), redirectUri, state, callbacks);
1062
+ } catch {
1063
+ callbacks.onOpenUrl(url.toString());
1064
+ const raw = await callbacks.onPromptCode(
1065
+ "Could not start local server. Paste the callback URL or code from the browser:"
1066
+ );
1067
+ const parsed = parseAuthorizationInput2(raw);
1068
+ if (!parsed.code) {
1069
+ throw new Error("No authorization code found in input.");
1070
+ }
1071
+ if (parsed.state && parsed.state !== state) {
1072
+ throw new Error("Invalid state. Please try again.");
1073
+ }
1074
+ code = parsed.code;
1075
+ }
1076
+ const creds = await exchangeGeminiCode(code, verifier, redirectUri, clientId, clientSecret);
1077
+ callbacks.onStatus("Setting up Gemini Code Assist access...");
1078
+ const projectId = await setupCodeAssistProject(creds.accessToken, callbacks);
1079
+ return {
1080
+ ...creds,
1081
+ projectId
1082
+ };
1083
+ }
1084
+ async function refreshGeminiToken(refreshToken) {
1085
+ const { clientId, clientSecret } = getGeminiOAuthClientCredentials();
1086
+ const data = await postTokenRequest2({
1087
+ grant_type: "refresh_token",
1088
+ refresh_token: refreshToken,
1089
+ client_id: clientId,
1090
+ client_secret: clientSecret
1091
+ });
1092
+ return {
1093
+ accessToken: data.access_token,
1094
+ refreshToken: data.refresh_token ?? refreshToken,
1095
+ expiresAt: Date.now() + data.expires_in * 1e3 - 5 * 60 * 1e3
1096
+ };
1097
+ }
1098
+ function getGeminiOAuthClientCredentials() {
1099
+ const clientId = process.env[CLIENT_ID_ENV]?.trim() || DEFAULT_CLIENT_ID;
1100
+ const clientSecret = process.env[CLIENT_SECRET_ENV]?.trim() || DEFAULT_CLIENT_SECRET;
1101
+ return { clientId, clientSecret };
1102
+ }
1103
+ async function getLoopbackRedirectUri() {
1104
+ return new Promise((resolve, reject) => {
1105
+ const server = import_node_http2.default.createServer();
1106
+ server.listen(0, "127.0.0.1", () => {
1107
+ const addr = server.address();
1108
+ server.close(() => {
1109
+ if (addr && typeof addr === "object") {
1110
+ resolve(`http://127.0.0.1:${addr.port}/oauth2callback`);
1111
+ } else {
1112
+ reject(new Error("Failed to allocate OAuth callback port."));
1113
+ }
1114
+ });
1115
+ });
1116
+ server.on("error", reject);
1117
+ });
1118
+ }
1119
+ function parseAuthorizationInput2(input) {
1120
+ const value = input.trim();
1121
+ if (!value) return {};
1122
+ try {
1123
+ const url = new URL(value);
1124
+ return {
1125
+ code: url.searchParams.get("code") ?? void 0,
1126
+ state: url.searchParams.get("state") ?? void 0
1127
+ };
1128
+ } catch {
1129
+ }
1130
+ if (value.includes("code=")) {
1131
+ const params = new URLSearchParams(value);
1132
+ return {
1133
+ code: params.get("code") ?? void 0,
1134
+ state: params.get("state") ?? void 0
1135
+ };
1136
+ }
1137
+ return { code: value };
1138
+ }
1139
+ async function loginWithServer2(authUrl, redirectUri, expectedState, callbacks) {
1140
+ const redirect = new URL(redirectUri);
1141
+ const port = Number(redirect.port);
1142
+ return new Promise((resolve, reject) => {
1143
+ let receivedCode = null;
1144
+ const server = import_node_http2.default.createServer((req, res) => {
1145
+ const url = new URL(req.url || "", redirect.origin);
1146
+ if (url.pathname !== redirect.pathname) {
1147
+ res.statusCode = 404;
1148
+ res.end("Not found");
1149
+ return;
1150
+ }
1151
+ if (url.searchParams.get("state") !== expectedState) {
1152
+ res.statusCode = 400;
1153
+ res.end("State mismatch");
1154
+ return;
1155
+ }
1156
+ receivedCode = url.searchParams.get("code");
1157
+ res.writeHead(200, { "Content-Type": "text/html", Connection: "close" });
1158
+ res.end("<html><body><h1>Login successful!</h1><p>You can close this tab.</p></body></html>");
1159
+ server.close();
1160
+ });
1161
+ server.on("error", (err) => reject(err));
1162
+ server.listen(port, "127.0.0.1", () => {
1163
+ callbacks.onOpenUrl(authUrl);
1164
+ callbacks.onStatus("Waiting for browser callback...");
1165
+ });
1166
+ const timeout = setTimeout(() => {
1167
+ if (!receivedCode) server.close();
1168
+ }, 12e4);
1169
+ timeout.unref();
1170
+ server.on("close", () => {
1171
+ clearTimeout(timeout);
1172
+ if (receivedCode) {
1173
+ resolve(receivedCode);
1174
+ } else {
1175
+ reject(new Error("Server closed without receiving code."));
1176
+ }
1177
+ });
1178
+ });
1179
+ }
1180
+ async function exchangeGeminiCode(code, verifier, redirectUri, clientId, clientSecret) {
1181
+ const data = await postTokenRequest2({
1182
+ grant_type: "authorization_code",
1183
+ client_id: clientId,
1184
+ client_secret: clientSecret,
1185
+ code,
1186
+ redirect_uri: redirectUri,
1187
+ code_verifier: verifier
1188
+ });
1189
+ if (!data.refresh_token) {
1190
+ throw new Error("Gemini OAuth did not return a refresh token. Please try login again.");
1191
+ }
1192
+ return {
1193
+ accessToken: data.access_token,
1194
+ refreshToken: data.refresh_token,
1195
+ expiresAt: Date.now() + data.expires_in * 1e3 - 5 * 60 * 1e3
1196
+ };
1197
+ }
1198
+ async function postTokenRequest2(body) {
1199
+ const response = await fetch(TOKEN_URL2, {
1200
+ method: "POST",
1201
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1202
+ body: new URLSearchParams(body)
1203
+ });
1204
+ if (!response.ok) {
1205
+ const text = await response.text();
1206
+ throw new Error(`Gemini token request failed (${response.status}): ${text}`);
1207
+ }
1208
+ return await response.json();
1209
+ }
1210
+ async function setupCodeAssistProject(accessToken, callbacks) {
1211
+ const envProject = process.env.GOOGLE_CLOUD_PROJECT ?? process.env.GOOGLE_CLOUD_PROJECT_ID;
1212
+ if (envProject && /^\d+$/.test(envProject)) {
1213
+ throw new Error("GOOGLE_CLOUD_PROJECT must be a project ID, not a numeric project number.");
1214
+ }
1215
+ const coreMetadata = {
1216
+ ideType: "IDE_UNSPECIFIED",
1217
+ platform: "PLATFORM_UNSPECIFIED",
1218
+ pluginType: "GEMINI"
1219
+ };
1220
+ const projectMetadata = {
1221
+ ...coreMetadata,
1222
+ ...envProject ? { duetProject: envProject } : {}
1223
+ };
1224
+ let loadRes;
1225
+ while (true) {
1226
+ loadRes = await loadCodeAssist(accessToken, envProject, projectMetadata);
1227
+ const validation = getValidationRequiredTier(loadRes);
1228
+ if (!validation) break;
1229
+ callbacks.onStatus(
1230
+ `Gemini Code Assist requires account validation${validation.reasonMessage ? `: ${validation.reasonMessage}` : ""}`
1231
+ );
1232
+ callbacks.onOpenUrl(validation.validationUrl);
1233
+ const answer = await callbacks.onPromptCode(
1234
+ "Complete validation in the browser, then press Enter to retry (or type cancel):"
1235
+ );
1236
+ if (answer.trim().toLowerCase() === "cancel") {
1237
+ throw new Error("Gemini Code Assist account validation was cancelled.");
1238
+ }
1239
+ }
1240
+ if (loadRes.currentTier) {
1241
+ const project2 = loadRes.cloudaicompanionProject ?? envProject;
1242
+ if (!project2) throwProjectError(loadRes);
1243
+ return project2;
1244
+ }
1245
+ const tier = getOnboardTier(loadRes);
1246
+ const onboardReq = tier.id === USER_TIER_FREE ? {
1247
+ tierId: tier.id,
1248
+ cloudaicompanionProject: void 0,
1249
+ metadata: coreMetadata
1250
+ } : {
1251
+ tierId: tier.id,
1252
+ cloudaicompanionProject: envProject,
1253
+ metadata: projectMetadata
1254
+ };
1255
+ let operation = await codeAssistPost(
1256
+ accessToken,
1257
+ "onboardUser",
1258
+ onboardReq
1259
+ );
1260
+ while (!operation.done && operation.name) {
1261
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
1262
+ operation = await codeAssistGet(accessToken, operation.name);
1263
+ }
1264
+ const project = operation.response?.cloudaicompanionProject?.id ?? envProject;
1265
+ if (!project) throwProjectError(loadRes);
1266
+ return project;
1267
+ }
1268
+ async function loadCodeAssist(accessToken, envProject, metadata) {
1269
+ try {
1270
+ return await codeAssistPost(accessToken, "loadCodeAssist", {
1271
+ ...envProject ? { cloudaicompanionProject: envProject } : {},
1272
+ metadata
1273
+ });
1274
+ } catch (err) {
1275
+ if (err instanceof CodeAssistHttpError && isVpcScAffectedError(err)) {
1276
+ return { currentTier: { id: USER_TIER_STANDARD } };
1277
+ }
1278
+ if (err instanceof CodeAssistHttpError && err.status === 403 && envProject === "cloudshell-gca") {
1279
+ throw new Error(
1280
+ "Access to the default Cloud Shell Gemini project was denied.\nPlease set your own Google Cloud project by running:\ngcloud config set project [PROJECT_ID]\nor setting export GOOGLE_CLOUD_PROJECT=...",
1281
+ { cause: err }
1282
+ );
1283
+ }
1284
+ throw err;
1285
+ }
1286
+ }
1287
+ function getValidationRequiredTier(response) {
1288
+ return response.ineligibleTiers?.find(
1289
+ (tier) => tier.reasonCode === VALIDATION_REQUIRED_REASON && typeof tier.validationUrl === "string"
1290
+ );
1291
+ }
1292
+ function getOnboardTier(response) {
1293
+ const defaultTier = response.allowedTiers?.find((tier) => tier.isDefault);
1294
+ return defaultTier ?? { id: USER_TIER_LEGACY, name: "" };
1295
+ }
1296
+ function throwProjectError(response) {
1297
+ const reasons = response.ineligibleTiers?.map((tier) => tier.reasonMessage ?? tier.tierName).filter((reason) => Boolean(reason));
1298
+ if (reasons && reasons.length > 0) {
1299
+ throw new Error(`Gemini Code Assist setup failed: ${reasons.join(", ")}`);
1300
+ }
1301
+ throw new Error(
1302
+ "Gemini requires a Google Cloud project for this account. Set GOOGLE_CLOUD_PROJECT and try again."
1303
+ );
1304
+ }
1305
+ async function codeAssistPost(accessToken, method, body) {
1306
+ let lastError;
1307
+ for (let attempt = 0; attempt <= CODE_ASSIST_POST_RETRIES; attempt++) {
1308
+ try {
1309
+ return await codeAssistRequest(getCodeAssistMethodUrl(method), accessToken, method, {
1310
+ method: "POST",
1311
+ body: JSON.stringify(body)
1312
+ });
1313
+ } catch (err) {
1314
+ if (!(err instanceof CodeAssistHttpError) || attempt === CODE_ASSIST_POST_RETRIES || !shouldRetryCodeAssistStatus(err.status)) {
1315
+ throw err;
1316
+ }
1317
+ lastError = err;
1318
+ }
1319
+ await new Promise((resolve) => setTimeout(resolve, CODE_ASSIST_POST_RETRY_DELAY_MS));
1320
+ }
1321
+ throw lastError ?? new Error(`Gemini Code Assist ${method} failed.`);
1322
+ }
1323
+ async function codeAssistGet(accessToken, operationName) {
1324
+ return codeAssistRequest(getCodeAssistOperationUrl(operationName), accessToken, "operation", {
1325
+ method: "GET"
1326
+ });
1327
+ }
1328
+ async function codeAssistRequest(url, accessToken, label, init) {
1329
+ const response = await fetch(url, {
1330
+ ...init,
1331
+ headers: codeAssistHeaders(accessToken)
1332
+ });
1333
+ if (!response.ok) {
1334
+ const text = await response.text();
1335
+ throw new CodeAssistHttpError(label, response.status, text);
1336
+ }
1337
+ return await response.json();
1338
+ }
1339
+ function getCodeAssistBaseUrl() {
1340
+ const endpoint = process.env.CODE_ASSIST_ENDPOINT ?? CODE_ASSIST_BASE_URL;
1341
+ const version = process.env.CODE_ASSIST_API_VERSION || CODE_ASSIST_API_VERSION;
1342
+ return `${endpoint}/${version}`;
1343
+ }
1344
+ function getCodeAssistMethodUrl(method) {
1345
+ return `${getCodeAssistBaseUrl()}:${method}`;
1346
+ }
1347
+ function getCodeAssistOperationUrl(operationName) {
1348
+ return `${getCodeAssistBaseUrl()}/${operationName}`;
1349
+ }
1350
+ function shouldRetryCodeAssistStatus(status) {
1351
+ return status === 429 || status === 499 || status >= 500 && status <= 599;
1352
+ }
1353
+ function isVpcScAffectedError(error) {
1354
+ try {
1355
+ const parsed = JSON.parse(error.body);
1356
+ if (!parsed || typeof parsed !== "object" || !("error" in parsed)) return false;
1357
+ const details = parsed.error?.details;
1358
+ return Array.isArray(details) ? details.some(
1359
+ (detail) => detail != null && typeof detail === "object" && "reason" in detail && detail.reason === VPC_SC_REASON
1360
+ ) : false;
1361
+ } catch {
1362
+ return false;
1363
+ }
1364
+ }
1365
+ function codeAssistHeaders(accessToken) {
1366
+ return {
1367
+ Authorization: `Bearer ${accessToken}`,
1368
+ "Content-Type": "application/json",
1369
+ "User-Agent": "google-gemini-cli",
1370
+ "X-Goog-Api-Client": "gemini-cli/0.0.0"
1371
+ };
1372
+ }
1373
+
1374
+ // src/oauth/kimi.ts
1375
+ var import_node_child_process = require("child_process");
1376
+ var import_node_crypto5 = require("crypto");
1377
+ var import_node_fs2 = require("fs");
1378
+ var import_node_os2 = require("os");
1379
+ var import_node_path4 = __toESM(require("path"), 1);
1380
+ var CLIENT_ID3 = "17e5f671-d194-4dfb-9706-5516cb48c098";
1381
+ var DEFAULT_OAUTH_HOST = "https://auth.kimi.com";
1382
+ var DEFAULT_CODING_BASE_URL = "https://api.kimi.com/coding/v1";
1383
+ var KIMI_PLATFORM = "kimi_code_cli";
1384
+ var DEFAULT_KIMI_VERSION = "1.0.11";
1385
+ var DEVICE_TIMEOUT_MS = 15 * 60 * 1e3;
1386
+ function oauthHost() {
1387
+ const host = process.env.KIMI_CODE_OAUTH_HOST ?? process.env.KIMI_OAUTH_HOST ?? DEFAULT_OAUTH_HOST;
1388
+ return host.replace(/\/+$/, "");
1389
+ }
1390
+ function kimiCodeBaseUrl() {
1391
+ return (process.env.KIMI_CODE_BASE_URL ?? DEFAULT_CODING_BASE_URL).replace(/\/+$/, "");
1392
+ }
1393
+ function kimiVersion() {
1394
+ const v = process.env.KIMI_CODE_VERSION ?? DEFAULT_KIMI_VERSION;
1395
+ return asciiHeader(v, DEFAULT_KIMI_VERSION);
1396
+ }
1397
+ function asciiHeader(value, fallback = "unknown") {
1398
+ const cleaned = value.replace(/[^\u0020-\u007E]/g, "").trim();
1399
+ return cleaned.length > 0 ? cleaned : fallback;
1400
+ }
1401
+ function macOsProductVersion() {
1402
+ try {
1403
+ const version = (0, import_node_child_process.execFileSync)("/usr/bin/sw_vers", ["-productVersion"], {
1404
+ encoding: "utf-8",
1405
+ timeout: 1e3
1406
+ }).trim();
1407
+ return version.length > 0 ? version : void 0;
1408
+ } catch {
1409
+ return void 0;
1410
+ }
1411
+ }
1412
+ function deviceModel() {
1413
+ const os2 = (0, import_node_os2.type)();
1414
+ const version = (0, import_node_os2.release)();
1415
+ const osArch = (0, import_node_os2.arch)();
1416
+ if (os2 === "Darwin") return `macOS ${macOsProductVersion() ?? version} ${osArch}`;
1417
+ if (os2 === "Windows_NT") return `Windows ${version} ${osArch}`;
1418
+ return `${os2} ${version} ${osArch}`.trim();
1419
+ }
1420
+ function deviceId() {
1421
+ const idPath = import_node_path4.default.join(getAppPaths().agentDir, "kimi_device_id");
1422
+ if ((0, import_node_fs2.existsSync)(idPath)) {
1423
+ try {
1424
+ const text = (0, import_node_fs2.readFileSync)(idPath, "utf-8").trim();
1425
+ if (text.length > 0) return text;
1426
+ } catch {
1427
+ }
1428
+ }
1429
+ const id = (0, import_node_crypto5.randomUUID)();
1430
+ try {
1431
+ (0, import_node_fs2.mkdirSync)(getAppPaths().agentDir, { recursive: true, mode: 448 });
1432
+ (0, import_node_fs2.writeFileSync)(idPath, id, { encoding: "utf-8", mode: 384 });
1433
+ } catch {
1434
+ }
1435
+ return id;
1436
+ }
1437
+ function deviceHeaders() {
1438
+ return {
1439
+ "X-Msh-Platform": KIMI_PLATFORM,
1440
+ "X-Msh-Version": kimiVersion(),
1441
+ "X-Msh-Device-Name": asciiHeader((0, import_node_os2.hostname)()),
1442
+ "X-Msh-Device-Model": asciiHeader(deviceModel()),
1443
+ "X-Msh-Os-Version": asciiHeader((0, import_node_os2.release)()),
1444
+ "X-Msh-Device-Id": deviceId()
1445
+ };
1446
+ }
1447
+ function kimiCodingHeaders() {
1448
+ return {
1449
+ "User-Agent": `kimi-code-cli/${kimiVersion()}`,
1450
+ ...deviceHeaders()
1451
+ };
1452
+ }
1453
+ function isKimiCodingEndpoint(baseUrl) {
1454
+ if (typeof baseUrl !== "string" || baseUrl.length === 0) return false;
1455
+ const normalized = baseUrl.replace(/\/+$/, "");
1456
+ return normalized === kimiCodeBaseUrl() || /(^|\.)kimi\.com/i.test(normalized);
1457
+ }
1458
+ async function postForm(endpoint, params) {
1459
+ const response = await fetch(`${oauthHost()}${endpoint}`, {
1460
+ method: "POST",
1461
+ headers: {
1462
+ ...deviceHeaders(),
1463
+ "Content-Type": "application/x-www-form-urlencoded",
1464
+ Accept: "application/json"
1465
+ },
1466
+ body: new URLSearchParams(params).toString()
1467
+ });
1468
+ let data = {};
1469
+ try {
1470
+ const parsed = await response.json();
1471
+ if (parsed && typeof parsed === "object") data = parsed;
1472
+ } catch {
1473
+ }
1474
+ return { status: response.status, data };
1475
+ }
1476
+ function errorDetail(data) {
1477
+ const desc = data.error_description ?? data.message ?? data.error;
1478
+ return typeof desc === "string" && desc.length > 0 ? desc : "unknown error";
1479
+ }
1480
+ function credsFromTokenResponse(data, opts) {
1481
+ const accessToken = data.access_token;
1482
+ const responseRefreshToken = data.refresh_token;
1483
+ const expiresIn = Number(data.expires_in);
1484
+ if (typeof accessToken !== "string" || accessToken.length === 0) {
1485
+ throw new Error("Kimi OAuth response missing access_token.");
1486
+ }
1487
+ const refreshToken = typeof responseRefreshToken === "string" && responseRefreshToken.length > 0 ? responseRefreshToken : opts?.fallbackRefreshToken ?? "";
1488
+ if (refreshToken.length === 0) {
1489
+ throw new Error("Kimi OAuth response missing refresh_token.");
1490
+ }
1491
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
1492
+ throw new Error("Kimi OAuth response missing or invalid expires_in.");
1493
+ }
1494
+ return {
1495
+ accessToken,
1496
+ refreshToken,
1497
+ expiresAt: Date.now() + expiresIn * 1e3,
1498
+ baseUrl: kimiCodeBaseUrl()
1499
+ };
1500
+ }
1501
+ async function requestDeviceAuthorization() {
1502
+ const { status, data } = await postForm("/api/oauth/device_authorization", {
1503
+ client_id: CLIENT_ID3
1504
+ });
1505
+ if (status !== 200) {
1506
+ throw new Error(`Kimi device authorization failed (${status}): ${errorDetail(data)}`);
1507
+ }
1508
+ const userCode = data.user_code;
1509
+ const deviceCode = data.device_code;
1510
+ const verificationUriComplete = data.verification_uri_complete;
1511
+ if (typeof userCode !== "string" || typeof deviceCode !== "string") {
1512
+ throw new Error("Kimi device authorization response missing user_code/device_code.");
1513
+ }
1514
+ return {
1515
+ userCode,
1516
+ deviceCode,
1517
+ verificationUri: typeof data.verification_uri === "string" ? data.verification_uri : "",
1518
+ verificationUriComplete: typeof verificationUriComplete === "string" ? verificationUriComplete : "",
1519
+ interval: Number(data.interval ?? 5) || 5
1520
+ };
1521
+ }
1522
+ async function pollDeviceToken(deviceCode) {
1523
+ const { status, data } = await postForm("/api/oauth/token", {
1524
+ client_id: CLIENT_ID3,
1525
+ device_code: deviceCode,
1526
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
1527
+ });
1528
+ if (status === 200 && typeof data.access_token === "string") {
1529
+ return { kind: "success", creds: credsFromTokenResponse(data) };
1530
+ }
1531
+ if (status >= 500) {
1532
+ throw new Error(`Kimi token polling server error (${status}): ${errorDetail(data)}`);
1533
+ }
1534
+ const errorCode = typeof data.error === "string" ? data.error : "unknown_error";
1535
+ switch (errorCode) {
1536
+ case "authorization_pending":
1537
+ return { kind: "pending" };
1538
+ case "slow_down":
1539
+ return { kind: "slow_down" };
1540
+ case "expired_token":
1541
+ return { kind: "expired" };
1542
+ case "access_denied":
1543
+ return { kind: "denied" };
1544
+ default:
1545
+ throw new Error(`Kimi token polling failed (${status}): ${errorDetail(data)}`);
1546
+ }
1547
+ }
1548
+ function sleep(ms) {
1549
+ return new Promise((resolve) => {
1550
+ setTimeout(resolve, ms);
1551
+ });
1552
+ }
1553
+ async function loginKimi(callbacks) {
1554
+ const auth = await requestDeviceAuthorization();
1555
+ callbacks.onStatus(
1556
+ `Visit ${auth.verificationUri || auth.verificationUriComplete} and enter code: ${auth.userCode}`
1557
+ );
1558
+ callbacks.onOpenUrl(auth.verificationUriComplete || auth.verificationUri);
1559
+ callbacks.onStatus("Waiting for you to authorize in the browser...");
1560
+ const deadline = Date.now() + DEVICE_TIMEOUT_MS;
1561
+ let interval = Math.max(auth.interval, 1);
1562
+ while (Date.now() < deadline) {
1563
+ await sleep(interval * 1e3);
1564
+ const result = await pollDeviceToken(auth.deviceCode);
1565
+ if (result.kind === "success") return result.creds;
1566
+ if (result.kind === "denied") {
1567
+ throw new Error("Kimi authorization was denied.");
1568
+ }
1569
+ if (result.kind === "expired") {
1570
+ throw new Error("Kimi device code expired. Please run login again.");
1571
+ }
1572
+ if (result.kind === "slow_down") {
1573
+ interval += 5;
1574
+ }
1575
+ }
1576
+ throw new Error("Kimi login timed out. Please run login again.");
1577
+ }
1578
+ async function refreshKimiToken(refreshToken) {
1579
+ const { status, data } = await postForm("/api/oauth/token", {
1580
+ client_id: CLIENT_ID3,
1581
+ grant_type: "refresh_token",
1582
+ refresh_token: refreshToken
1583
+ });
1584
+ if (status === 200 && typeof data.access_token === "string") {
1585
+ return credsFromTokenResponse(data, { fallbackRefreshToken: refreshToken });
1586
+ }
1587
+ const errorCode = typeof data.error === "string" ? data.error : "";
1588
+ throw new Error(`Kimi token refresh failed (${status}): ${errorCode || errorDetail(data)}`);
1589
+ }
1590
+
1591
+ // src/auth-storage.ts
1592
+ var MOONSHOT_OAUTH_KEY = "moonshot-oauth";
1593
+ var REFRESH_SKEW_MS = 6e4;
1594
+ var STATIC_API_KEY_PROVIDERS = /* @__PURE__ */ new Set([
1595
+ "glm",
1596
+ "moonshot",
1597
+ "xiaomi",
1598
+ "minimax",
1599
+ "deepseek",
1600
+ "openrouter"
1601
+ ]);
1602
+ var AuthStorage = class {
1603
+ data = {};
1604
+ filePath;
1605
+ loaded = false;
1606
+ /** Per-provider lock to serialize concurrent refresh calls. */
1607
+ refreshLocks = /* @__PURE__ */ new Map();
1608
+ constructor(filePath) {
1609
+ this.filePath = filePath ?? getAppPaths().authFile;
1610
+ }
1611
+ /** Path to the on-disk auth file. Useful for status output. */
1612
+ get path() {
1613
+ return this.filePath;
1614
+ }
1615
+ /** List provider keys with stored credentials. */
1616
+ async listProviders() {
1617
+ await this.ensureLoaded();
1618
+ return Object.keys(this.data);
1619
+ }
1620
+ /** True if credentials exist for `provider`. */
1621
+ async hasCredentials(provider) {
1622
+ await this.ensureLoaded();
1623
+ return Boolean(this.data[provider]);
1624
+ }
1625
+ /**
1626
+ * True if the user has any usable auth for the logical provider. For
1627
+ * `moonshot` this is satisfied by either the Kimi OAuth credential or the
1628
+ * Moonshot API key.
1629
+ */
1630
+ async hasProviderAuth(provider) {
1631
+ await this.ensureLoaded();
1632
+ if (provider === "moonshot") {
1633
+ return Boolean(this.data[MOONSHOT_OAUTH_KEY] || this.data["moonshot"]);
1634
+ }
1635
+ return Boolean(this.data[provider]);
1636
+ }
1637
+ /**
1638
+ * True if the active credential for `provider` is a static API key with no
1639
+ * refresh mechanism. For `moonshot` this is only true when the Kimi OAuth
1640
+ * credential is absent (a present OAuth credential is refreshable).
1641
+ */
1642
+ async isStaticApiKey(provider) {
1643
+ await this.ensureLoaded();
1644
+ if (provider === "moonshot" && this.data[MOONSHOT_OAUTH_KEY]) {
1645
+ return false;
1646
+ }
1647
+ return STATIC_API_KEY_PROVIDERS.has(provider);
1648
+ }
1649
+ async load() {
1650
+ await withFileLock(this.filePath, async () => {
1651
+ try {
1652
+ const content = await import_promises4.default.readFile(this.filePath, "utf-8");
1653
+ this.data = JSON.parse(content);
1654
+ log("INFO", "auth", `Loaded credentials from ${this.filePath}`, {
1655
+ providers: Object.keys(this.data).join(",") || "(none)"
1656
+ });
1657
+ } catch (err) {
1658
+ this.data = {};
1659
+ const code = err.code;
1660
+ if (code === "ENOENT") {
1661
+ log("INFO", "auth", `No auth file found at ${this.filePath} (first run)`);
1662
+ } else {
1663
+ log(
1664
+ "ERROR",
1665
+ "auth",
1666
+ `Failed to load auth file: ${err instanceof Error ? err.message : String(err)}`,
1667
+ { path: this.filePath, code: code ?? "unknown" }
1668
+ );
1669
+ }
1670
+ }
1671
+ });
1672
+ this.loaded = true;
1673
+ }
1674
+ async ensureLoaded() {
1675
+ if (!this.loaded) await this.load();
1676
+ }
1677
+ async getCredentials(provider) {
1678
+ await this.ensureLoaded();
1679
+ return this.data[provider];
1680
+ }
1681
+ async setCredentials(provider, creds) {
1682
+ await this.ensureLoaded();
1683
+ this.data[provider] = creds;
1684
+ await this.save();
1685
+ }
1686
+ async clearCredentials(provider) {
1687
+ await this.ensureLoaded();
1688
+ delete this.data[provider];
1689
+ await this.save();
1690
+ }
1691
+ async clearAll() {
1692
+ this.data = {};
1693
+ await this.save();
1694
+ }
1695
+ /**
1696
+ * Returns valid credentials, auto-refreshing if expired.
1697
+ * If `forceRefresh` is true, refreshes even if the token hasn't expired
1698
+ * (useful when the provider rejects a token with 401 before its stored expiry).
1699
+ * Throws if not logged in.
1700
+ */
1701
+ async resolveCredentials(provider, opts) {
1702
+ await this.ensureLoaded();
1703
+ if (provider === "moonshot" && this.data[MOONSHOT_OAUTH_KEY]) {
1704
+ try {
1705
+ return await this.resolveCredentials(MOONSHOT_OAUTH_KEY, opts);
1706
+ } catch (err) {
1707
+ if (err instanceof NotLoggedInError && this.data["moonshot"]) {
1708
+ log(
1709
+ "WARN",
1710
+ "auth",
1711
+ 'Kimi OAuth credential is no longer valid \u2014 falling back to the Moonshot API key. Run "ezcoder login" and choose Kimi OAuth to restore OAuth auth.'
1712
+ );
1713
+ return this.data["moonshot"];
1714
+ }
1715
+ throw err;
1716
+ }
1717
+ }
1718
+ const creds = this.data[provider];
1719
+ if (!creds) {
1720
+ throw new NotLoggedInError(provider);
1721
+ }
1722
+ if (STATIC_API_KEY_PROVIDERS.has(provider)) {
1723
+ return creds;
1724
+ }
1725
+ if (!opts?.forceRefresh && Date.now() < creds.expiresAt - REFRESH_SKEW_MS) {
1726
+ return creds;
1727
+ }
1728
+ const existing = this.refreshLocks.get(provider);
1729
+ if (existing) return existing;
1730
+ const refreshPromise = withFileLock(this.filePath, async () => {
1731
+ try {
1732
+ const content = await import_promises4.default.readFile(this.filePath, "utf-8");
1733
+ const freshData = JSON.parse(content);
1734
+ const freshCreds = freshData[provider];
1735
+ if (freshCreds && !opts?.forceRefresh && Date.now() < freshCreds.expiresAt - REFRESH_SKEW_MS) {
1736
+ this.data[provider] = freshCreds;
1737
+ return freshCreds;
1738
+ }
1739
+ } catch {
1740
+ }
1741
+ const refreshFn = provider === "anthropic" ? refreshAnthropicToken : provider === "gemini" ? refreshGeminiToken : provider === MOONSHOT_OAUTH_KEY ? refreshKimiToken : refreshOpenAIToken;
1742
+ let refreshed;
1743
+ try {
1744
+ refreshed = await refreshFn(creds.refreshToken);
1745
+ } catch (err) {
1746
+ const msg = err instanceof Error ? err.message : String(err);
1747
+ const isAuthFailure = /\((401|400)\)/.test(msg) || /invalid_grant|invalid_token|invalid.*refresh/i.test(msg) || /unauthorized/i.test(msg);
1748
+ if (isAuthFailure) {
1749
+ delete this.data[provider];
1750
+ await atomicWriteFile(this.filePath, JSON.stringify(this.data, null, 2));
1751
+ throw new NotLoggedInError(provider);
1752
+ }
1753
+ throw err;
1754
+ }
1755
+ if (!refreshed.accountId && creds.accountId) {
1756
+ refreshed.accountId = creds.accountId;
1757
+ }
1758
+ if (!refreshed.projectId && creds.projectId) {
1759
+ refreshed.projectId = creds.projectId;
1760
+ }
1761
+ if (!refreshed.baseUrl && creds.baseUrl) {
1762
+ refreshed.baseUrl = creds.baseUrl;
1763
+ }
1764
+ this.data[provider] = refreshed;
1765
+ await atomicWriteFile(this.filePath, JSON.stringify(this.data, null, 2));
1766
+ return refreshed;
1767
+ });
1768
+ this.refreshLocks.set(provider, refreshPromise);
1769
+ try {
1770
+ return await refreshPromise;
1771
+ } finally {
1772
+ this.refreshLocks.delete(provider);
1773
+ }
1774
+ }
1775
+ /**
1776
+ * Returns a valid access token, auto-refreshing if expired.
1777
+ * Throws if not logged in.
1778
+ */
1779
+ async resolveToken(provider) {
1780
+ const creds = await this.resolveCredentials(provider);
1781
+ return creds.accessToken;
1782
+ }
1783
+ async save() {
1784
+ await withFileLock(this.filePath, async () => {
1785
+ await atomicWriteFile(this.filePath, JSON.stringify(this.data, null, 2));
1786
+ });
1787
+ }
1788
+ };
1789
+ async function atomicWriteFile(filePath, content) {
1790
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_node_crypto6.default.randomUUID().slice(0, 8)}.tmp`;
1791
+ try {
1792
+ await import_promises4.default.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
1793
+ await import_promises4.default.rename(tmpPath, filePath);
1794
+ } catch (err) {
1795
+ await import_promises4.default.unlink(tmpPath).catch(() => {
1796
+ });
1797
+ throw err;
1798
+ }
1799
+ }
1800
+ var NotLoggedInError = class extends Error {
1801
+ provider;
1802
+ constructor(provider) {
1803
+ super(`Not logged in to ${provider}. Run "ezcoder login" to authenticate.`);
1804
+ this.name = "NotLoggedInError";
1805
+ this.provider = provider;
1806
+ }
1807
+ };
1808
+
1809
+ // src/telegram.ts
1810
+ var TELEGRAM_API = "https://api.telegram.org";
1811
+ var MAX_MESSAGE_LENGTH = 4096;
1812
+ var TelegramBot = class {
1813
+ token;
1814
+ allowedUserId;
1815
+ offset = 0;
1816
+ running = false;
1817
+ onMessage = null;
1818
+ onVoiceMessage = null;
1819
+ onCallback = null;
1820
+ onBotAdded = null;
1821
+ onBotRemoved = null;
1822
+ constructor(config) {
1823
+ this.token = config.botToken;
1824
+ this.allowedUserId = config.allowedUserId;
1825
+ }
1826
+ /** Register handler for incoming text messages. */
1827
+ onText(handler) {
1828
+ this.onMessage = handler;
1829
+ }
1830
+ /** Register handler for incoming voice notes. */
1831
+ onVoice(handler) {
1832
+ this.onVoiceMessage = handler;
1833
+ }
1834
+ /** Register handler for inline keyboard button presses. */
1835
+ onCallbackQuery(handler) {
1836
+ this.onCallback = handler;
1837
+ }
1838
+ /** Register handler for when the bot is added to a group. */
1839
+ onAddedToGroup(handler) {
1840
+ this.onBotAdded = handler;
1841
+ }
1842
+ /** Register handler for when the bot is removed from a group. */
1843
+ onRemovedFromGroup(handler) {
1844
+ this.onBotRemoved = handler;
1845
+ }
1846
+ /** Start long polling. Blocks until stop() is called. */
1847
+ async start() {
1848
+ this.running = true;
1849
+ const me = await this.apiCall("getMe");
1850
+ if (!me.ok) {
1851
+ throw new Error(`Invalid bot token: ${JSON.stringify(me)}`);
1852
+ }
1853
+ while (this.running) {
1854
+ try {
1855
+ const updates = await this.getUpdates();
1856
+ for (const update of updates) {
1857
+ await this.handleUpdate(update);
1858
+ }
1859
+ } catch (err) {
1860
+ if (!this.running) break;
1861
+ console.error(`[telegram] Poll error: ${err instanceof Error ? err.message : err}`);
1862
+ await sleep2(3e3);
1863
+ }
1864
+ }
1865
+ }
1866
+ /** Stop long polling. */
1867
+ stop() {
1868
+ this.running = false;
1869
+ }
1870
+ /** Send a text message to a specific chat. Converts markdown and splits long messages. */
1871
+ async send(chatId, text, buttons) {
1872
+ const converted = toTelegramMarkdown(text);
1873
+ const chunks = splitMessage(converted);
1874
+ for (let i = 0; i < chunks.length; i++) {
1875
+ const isLast = i === chunks.length - 1;
1876
+ const replyMarkup = isLast && buttons ? {
1877
+ inline_keyboard: buttons.map(
1878
+ (row) => row.map((b) => ({ text: b.text, callback_data: b.callback_data }))
1879
+ )
1880
+ } : void 0;
1881
+ await this.apiCall("sendMessage", {
1882
+ chat_id: chatId,
1883
+ text: chunks[i],
1884
+ parse_mode: "Markdown",
1885
+ ...replyMarkup ? { reply_markup: replyMarkup } : {}
1886
+ });
1887
+ }
1888
+ }
1889
+ /** Send a plain text message (no markdown parsing) to a specific chat. */
1890
+ async sendPlain(chatId, text) {
1891
+ const chunks = splitMessage(text);
1892
+ for (const chunk of chunks) {
1893
+ await this.apiCall("sendMessage", {
1894
+ chat_id: chatId,
1895
+ text: chunk
1896
+ });
1897
+ }
1898
+ }
1899
+ /** Send a typing indicator to a specific chat. */
1900
+ async sendTyping(chatId) {
1901
+ await this.apiCall("sendChatAction", {
1902
+ chat_id: chatId,
1903
+ action: "typing"
1904
+ });
1905
+ }
1906
+ /** Get a direct download URL for a Telegram file. */
1907
+ async getFileUrl(fileId) {
1908
+ const result = await this.apiCall("getFile", { file_id: fileId });
1909
+ if (!result.ok) throw new Error(`Failed to get file: ${JSON.stringify(result)}`);
1910
+ const filePath = result.result.file_path;
1911
+ return `${TELEGRAM_API}/file/bot${this.token}/${filePath}`;
1912
+ }
1913
+ // ── Private ───────────────────────────────────────────
1914
+ async getUpdates() {
1915
+ const result = await this.apiCall("getUpdates", {
1916
+ offset: this.offset,
1917
+ timeout: 30,
1918
+ allowed_updates: ["message", "callback_query", "my_chat_member"]
1919
+ });
1920
+ if (!result.ok || !Array.isArray(result.result)) return [];
1921
+ const updates = result.result;
1922
+ if (updates.length > 0) {
1923
+ this.offset = updates[updates.length - 1].update_id + 1;
1924
+ }
1925
+ return updates;
1926
+ }
1927
+ async handleUpdate(update) {
1928
+ if (update.message) {
1929
+ const msg = update.message;
1930
+ if (msg.from.id !== this.allowedUserId) {
1931
+ return;
1932
+ }
1933
+ if (msg.text && this.onMessage) {
1934
+ this.onMessage({
1935
+ text: msg.text,
1936
+ chatId: msg.chat.id,
1937
+ chatType: msg.chat.type,
1938
+ chatTitle: msg.chat.title
1939
+ });
1940
+ } else if (msg.voice && this.onVoiceMessage) {
1941
+ this.onVoiceMessage({
1942
+ fileId: msg.voice.file_id,
1943
+ duration: msg.voice.duration,
1944
+ chatId: msg.chat.id,
1945
+ chatType: msg.chat.type,
1946
+ chatTitle: msg.chat.title
1947
+ });
1948
+ }
1949
+ }
1950
+ if (update.my_chat_member) {
1951
+ const member = update.my_chat_member;
1952
+ const status = member.new_chat_member.status;
1953
+ if ((status === "member" || status === "administrator") && this.onBotAdded) {
1954
+ this.onBotAdded(member.chat.id, member.chat.title);
1955
+ } else if ((status === "left" || status === "kicked") && this.onBotRemoved) {
1956
+ this.onBotRemoved(member.chat.id);
1957
+ }
1958
+ }
1959
+ if (update.callback_query) {
1960
+ const cb = update.callback_query;
1961
+ if (cb.from.id !== this.allowedUserId) return;
1962
+ await this.apiCall("answerCallbackQuery", { callback_query_id: cb.id });
1963
+ if (cb.data && this.onCallback) {
1964
+ this.onCallback(cb.data, cb.message.chat.id);
1965
+ }
1966
+ }
1967
+ }
1968
+ async apiCall(method, body) {
1969
+ const url = `${TELEGRAM_API}/bot${this.token}/${method}`;
1970
+ const response = await fetch(url, {
1971
+ method: "POST",
1972
+ headers: { "Content-Type": "application/json" },
1973
+ body: body ? JSON.stringify(body) : void 0
1974
+ });
1975
+ if (!response.ok) {
1976
+ return { ok: false };
1977
+ }
1978
+ return response.json();
1979
+ }
1980
+ };
1981
+ function toTelegramMarkdown(text) {
1982
+ const lines = text.split("\n");
1983
+ const result = [];
1984
+ let inCodeBlock = false;
1985
+ for (const line of lines) {
1986
+ if (line.trimStart().startsWith("```")) {
1987
+ inCodeBlock = !inCodeBlock;
1988
+ result.push(line);
1989
+ continue;
1990
+ }
1991
+ if (inCodeBlock) {
1992
+ result.push(line);
1993
+ continue;
1994
+ }
1995
+ let transformed = line;
1996
+ const headingMatch = transformed.match(/^(#{1,6})\s+(.+)$/);
1997
+ if (headingMatch) {
1998
+ transformed = `*${headingMatch[2]}*`;
1999
+ result.push(transformed);
2000
+ continue;
2001
+ }
2002
+ if (/^(-{3,}|_{3,}|\*{3,})$/.test(transformed.trim())) {
2003
+ result.push("");
2004
+ continue;
2005
+ }
2006
+ transformed = transformed.replace(/\*\*(.+?)\*\*/g, "*$1*");
2007
+ result.push(transformed);
2008
+ }
2009
+ return result.join("\n");
2010
+ }
2011
+ function splitMessage(text) {
2012
+ if (text.length <= MAX_MESSAGE_LENGTH) return [text];
2013
+ const chunks = [];
2014
+ let remaining = text;
2015
+ while (remaining.length > 0) {
2016
+ if (remaining.length <= MAX_MESSAGE_LENGTH) {
2017
+ chunks.push(remaining);
2018
+ break;
2019
+ }
2020
+ let splitAt = remaining.lastIndexOf("\n", MAX_MESSAGE_LENGTH);
2021
+ if (splitAt === -1 || splitAt < MAX_MESSAGE_LENGTH * 0.5) {
2022
+ splitAt = remaining.lastIndexOf(" ", MAX_MESSAGE_LENGTH);
2023
+ }
2024
+ if (splitAt === -1 || splitAt < MAX_MESSAGE_LENGTH * 0.5) {
2025
+ splitAt = MAX_MESSAGE_LENGTH;
2026
+ }
2027
+ chunks.push(remaining.slice(0, splitAt));
2028
+ remaining = remaining.slice(splitAt).trimStart();
2029
+ }
2030
+ return chunks;
2031
+ }
2032
+ function sleep2(ms) {
2033
+ return new Promise((r) => setTimeout(r, ms));
2034
+ }
2035
+
2036
+ // src/voice-transcriber.ts
2037
+ var TARGET_SAMPLE_RATE = 16e3;
2038
+ var MODEL_ID = "Xenova/whisper-tiny.en";
2039
+ var transcriber = null;
2040
+ var loadPromise = null;
2041
+ var onProgress = null;
2042
+ function setProgressCallback(cb) {
2043
+ onProgress = cb;
2044
+ }
2045
+ function resample(audio, fromRate, toRate) {
2046
+ if (fromRate === toRate) return audio;
2047
+ const ratio = fromRate / toRate;
2048
+ const newLength = Math.round(audio.length / ratio);
2049
+ const result = new Float32Array(newLength);
2050
+ for (let i = 0; i < newLength; i++) {
2051
+ const srcIndex = i * ratio;
2052
+ const low = Math.floor(srcIndex);
2053
+ const high = Math.min(low + 1, audio.length - 1);
2054
+ const frac = srcIndex - low;
2055
+ result[i] = audio[low] * (1 - frac) + audio[high] * frac;
2056
+ }
2057
+ return result;
2058
+ }
2059
+ function downmixToMono(channelData) {
2060
+ if (channelData.length === 0) return new Float32Array();
2061
+ if (channelData.length === 1) return channelData[0];
2062
+ const samples = channelData[0].length;
2063
+ const out = new Float32Array(samples);
2064
+ const scale = 1 / channelData.length;
2065
+ for (let i = 0; i < samples; i++) {
2066
+ let mixed = 0;
2067
+ for (const channel of channelData) mixed += channel[i] ?? 0;
2068
+ out[i] = mixed * scale;
2069
+ }
2070
+ return out;
2071
+ }
2072
+ async function decodeOggOpus(buffer) {
2073
+ const { OggOpusDecoder } = await import("ogg-opus-decoder");
2074
+ const decoder = new OggOpusDecoder();
2075
+ await decoder.ready;
2076
+ try {
2077
+ const decoded = await decoder.decodeFile(buffer);
2078
+ if (!decoded.channelData?.length || !decoded.channelData[0]?.length) {
2079
+ throw new Error("Decoded audio is empty");
2080
+ }
2081
+ const mono = downmixToMono(decoded.channelData);
2082
+ return resample(mono, decoded.sampleRate, TARGET_SAMPLE_RATE);
2083
+ } finally {
2084
+ decoder.free();
2085
+ }
2086
+ }
2087
+ async function getTranscriber() {
2088
+ if (transcriber) return transcriber;
2089
+ if (!loadPromise) {
2090
+ loadPromise = (async () => {
2091
+ const { pipeline } = await import("@huggingface/transformers");
2092
+ const instance = await pipeline("automatic-speech-recognition", MODEL_ID, {
2093
+ dtype: "fp32",
2094
+ progress_callback: onProgress ?? void 0
2095
+ });
2096
+ transcriber = instance;
2097
+ return instance;
2098
+ })();
2099
+ }
2100
+ return loadPromise;
2101
+ }
2102
+ function isModelLoaded() {
2103
+ return transcriber !== null;
2104
+ }
2105
+ async function transcribeVoice(fileUrl) {
2106
+ const response = await fetch(fileUrl);
2107
+ if (!response.ok) throw new Error(`Failed to download voice file: ${response.status}`);
2108
+ const buffer = new Uint8Array(await response.arrayBuffer());
2109
+ const pcm = await decodeOggOpus(buffer);
2110
+ const asr = await getTranscriber();
2111
+ const result = await asr(pcm);
2112
+ const text = Array.isArray(result) ? result[0]?.text : result.text;
2113
+ return (text ?? "").trim();
2114
+ }
2115
+
2116
+ // src/auto-update.ts
2117
+ var import_node_child_process2 = require("child_process");
2118
+ var import_node_fs3 = __toESM(require("fs"), 1);
2119
+ var import_node_path5 = __toESM(require("path"), 1);
2120
+ var CHECK_INTERVAL_MS = 60 * 60 * 1e3;
2121
+ var FETCH_TIMEOUT_MS2 = 1e4;
2122
+ function compareVersions(a, b) {
2123
+ const pa = a.split(".").map(Number);
2124
+ const pb = b.split(".").map(Number);
2125
+ for (let i = 0; i < 3; i++) {
2126
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
2127
+ if (diff !== 0) return diff;
2128
+ }
2129
+ return 0;
2130
+ }
2131
+ function performUpdateInBackground(command) {
2132
+ try {
2133
+ const parts = command.split(" ");
2134
+ const child = (0, import_node_child_process2.spawn)(parts[0], parts.slice(1), {
2135
+ detached: true,
2136
+ stdio: "ignore",
2137
+ env: { ...process.env, npm_config_loglevel: "silent" }
2138
+ });
2139
+ child.unref();
2140
+ } catch {
2141
+ }
2142
+ }
2143
+ function createAutoUpdater(config) {
2144
+ const REGISTRY_URL = `https://registry.npmjs.org/${config.packageName}/latest`;
2145
+ const periodicMessage = config.periodicMessage ?? (({ currentVersion, latestVersion, updateCommand }) => `Ken just pushed a fresh update \u2014 ${currentVersion} \u2192 ${latestVersion}! I'll grab it on next launch (or run ${updateCommand} if you can't wait).`);
2146
+ let periodicTimer = null;
2147
+ function stateFilePath() {
2148
+ return typeof config.stateFilePath === "function" ? config.stateFilePath() : config.stateFilePath;
2149
+ }
2150
+ function readState() {
2151
+ try {
2152
+ const raw = import_node_fs3.default.readFileSync(stateFilePath(), "utf-8");
2153
+ return JSON.parse(raw);
2154
+ } catch {
2155
+ return null;
2156
+ }
2157
+ }
2158
+ function writeState(state) {
2159
+ try {
2160
+ const filePath = stateFilePath();
2161
+ import_node_fs3.default.mkdirSync(import_node_path5.default.dirname(filePath), { recursive: true, mode: 448 });
2162
+ import_node_fs3.default.writeFileSync(filePath, JSON.stringify(state));
2163
+ } catch {
2164
+ }
2165
+ }
2166
+ function detectInstallInfo() {
2167
+ const scriptPath = (process.argv[1] ?? "").replace(/\\/g, "/");
2168
+ if (scriptPath.includes("/_npx/")) {
2169
+ return { packageManager: "unknown" /* UNKNOWN */, updateCommand: null };
2170
+ }
2171
+ if (scriptPath.includes("/.pnpm") || scriptPath.includes("/pnpm/global")) {
2172
+ return {
2173
+ packageManager: "pnpm" /* PNPM */,
2174
+ updateCommand: `pnpm add -g ${config.packageName}@latest`
2175
+ };
2176
+ }
2177
+ if (scriptPath.includes("/.yarn/") || scriptPath.includes("/yarn/global")) {
2178
+ return {
2179
+ packageManager: "yarn" /* YARN */,
2180
+ updateCommand: `yarn global add ${config.packageName}@latest`
2181
+ };
2182
+ }
2183
+ return {
2184
+ packageManager: "npm" /* NPM */,
2185
+ updateCommand: `npm install -g ${config.packageName}@latest`
2186
+ };
2187
+ }
2188
+ async function fetchLatestVersion() {
2189
+ try {
2190
+ const controller = new AbortController();
2191
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS2);
2192
+ const response = await fetch(REGISTRY_URL, { signal: controller.signal });
2193
+ clearTimeout(timeout);
2194
+ const data = await response.json();
2195
+ const version = data.version?.trim();
2196
+ return version && /^\d+\.\d+\.\d+/.test(version) ? version : null;
2197
+ } catch {
2198
+ return null;
2199
+ }
2200
+ }
2201
+ function scheduleBackgroundCheck(currentVersion) {
2202
+ fetchLatestVersion().then((latestVersion) => {
2203
+ const newState = {
2204
+ lastCheckedAt: Date.now(),
2205
+ latestVersion: latestVersion ?? void 0,
2206
+ updatePending: false
2207
+ };
2208
+ if (latestVersion && compareVersions(latestVersion, currentVersion) > 0) {
2209
+ newState.updatePending = true;
2210
+ }
2211
+ writeState(newState);
2212
+ }).catch(() => {
2213
+ });
2214
+ }
2215
+ function checkAndAutoUpdate(currentVersion) {
2216
+ try {
2217
+ const state = readState();
2218
+ let message = null;
2219
+ if (state?.updatePending && state.latestVersion) {
2220
+ if (compareVersions(state.latestVersion, currentVersion) > 0) {
2221
+ const info = detectInstallInfo();
2222
+ if (info.updateCommand) {
2223
+ performUpdateInBackground(info.updateCommand);
2224
+ message = `Ken just shipped ${state.latestVersion}! Installing in the background \u2014 takes effect next launch.`;
2225
+ writeState({
2226
+ ...state,
2227
+ lastCheckedAt: Date.now(),
2228
+ updatePending: false,
2229
+ lastUpdateAttempt: Date.now()
2230
+ });
2231
+ }
2232
+ } else {
2233
+ writeState({ ...state, updatePending: false });
2234
+ }
2235
+ }
2236
+ const shouldCheck = !state || Date.now() - state.lastCheckedAt > CHECK_INTERVAL_MS;
2237
+ if (shouldCheck) scheduleBackgroundCheck(currentVersion);
2238
+ return message;
2239
+ } catch {
2240
+ return null;
2241
+ }
2242
+ }
2243
+ function getPendingUpdate(currentVersion) {
2244
+ try {
2245
+ const state = readState();
2246
+ if (!state?.latestVersion) return null;
2247
+ if (compareVersions(state.latestVersion, currentVersion) <= 0) return null;
2248
+ return { latestVersion: state.latestVersion };
2249
+ } catch {
2250
+ return null;
2251
+ }
2252
+ }
2253
+ function startPeriodicUpdateCheck(currentVersion, onUpdate) {
2254
+ if (periodicTimer) return;
2255
+ periodicTimer = setInterval(() => {
2256
+ fetchLatestVersion().then((latestVersion) => {
2257
+ if (!latestVersion) return;
2258
+ if (compareVersions(latestVersion, currentVersion) <= 0) return;
2259
+ const info = detectInstallInfo();
2260
+ if (!info.updateCommand) return;
2261
+ writeState({ lastCheckedAt: Date.now(), latestVersion, updatePending: true });
2262
+ onUpdate(
2263
+ periodicMessage({ currentVersion, latestVersion, updateCommand: info.updateCommand })
2264
+ );
2265
+ stopPeriodicUpdateCheck();
2266
+ }).catch(() => {
2267
+ });
2268
+ }, CHECK_INTERVAL_MS);
2269
+ periodicTimer.unref();
2270
+ }
2271
+ function stopPeriodicUpdateCheck() {
2272
+ if (periodicTimer) {
2273
+ clearInterval(periodicTimer);
2274
+ periodicTimer = null;
2275
+ }
2276
+ }
2277
+ return {
2278
+ checkAndAutoUpdate,
2279
+ getPendingUpdate,
2280
+ startPeriodicUpdateCheck,
2281
+ stopPeriodicUpdateCheck
2282
+ };
2283
+ }
2284
+ // Annotate the CommonJS export names for ESM import in node:
2285
+ 0 && (module.exports = {
2286
+ AuthStorage,
2287
+ DEFAULT_MAX_VIDEO_BYTES,
2288
+ MODELS,
2289
+ MOONSHOT_OAUTH_KEY,
2290
+ NotLoggedInError,
2291
+ TelegramBot,
2292
+ closeLogger,
2293
+ createAutoUpdater,
2294
+ decodeOggOpus,
2295
+ downmixToMono,
2296
+ generatePKCE,
2297
+ getAppPaths,
2298
+ getClaudeCliUserAgent,
2299
+ getClaudeCodeVersion,
2300
+ getContextWindow,
2301
+ getDefaultModel,
2302
+ getMaxThinkingLevel,
2303
+ getModel,
2304
+ getModelsForProvider,
2305
+ getNextThinkingLevel,
2306
+ getSessionId,
2307
+ getSummaryModel,
2308
+ getSupportedThinkingLevels,
2309
+ getVideoByteLimit,
2310
+ isKimiCodingEndpoint,
2311
+ isLoggerOpen,
2312
+ isModelLoaded,
2313
+ isThinkingLevelSupported,
2314
+ kimiCodeBaseUrl,
2315
+ kimiCodingHeaders,
2316
+ log,
2317
+ loginAnthropic,
2318
+ loginGemini,
2319
+ loginKimi,
2320
+ loginOpenAI,
2321
+ openLog,
2322
+ refreshAnthropicToken,
2323
+ refreshGeminiToken,
2324
+ refreshKimiToken,
2325
+ refreshOpenAIToken,
2326
+ registerLogCleanup,
2327
+ resample,
2328
+ setProgressCallback,
2329
+ transcribeVoice,
2330
+ usesOpenAICodexTransport,
2331
+ withFileLock
2332
+ });
2333
+ //# sourceMappingURL=index.cjs.map