@kenkaiiii/gg-core 6.3.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -33,7 +33,6 @@ __export(index_exports, {
33
33
  AUTH_PROVIDERS: () => AUTH_PROVIDERS,
34
34
  AuthStorage: () => AuthStorage,
35
35
  CHATGPT_PLAN_BASE_URL: () => CHATGPT_PLAN_BASE_URL,
36
- CHATGPT_PLAN_NOT_ENABLED_MESSAGE: () => CHATGPT_PLAN_NOT_ENABLED_MESSAGE,
37
36
  CHATGPT_PLAN_SCOPE: () => CHATGPT_PLAN_SCOPE,
38
37
  CHATGPT_USAGE_URL: () => CHATGPT_USAGE_URL,
39
38
  CLAUDE_CODE_AUTH_KEY: () => CLAUDE_CODE_AUTH_KEY,
@@ -65,7 +64,6 @@ __export(index_exports, {
65
64
  PLAN_MODE_THINKING_CAP: () => PLAN_MODE_THINKING_CAP,
66
65
  RETIRED_SIGN_INS: () => RETIRED_SIGN_INS,
67
66
  SubscriptionUsageError: () => SubscriptionUsageError,
68
- TelegramBot: () => TelegramBot,
69
67
  XIAOMI_CREDITS_KEY: () => XIAOMI_CREDITS_KEY,
70
68
  XIAOMI_TOKEN_PLAN_BASE_URLS: () => XIAOMI_TOKEN_PLAN_BASE_URLS,
71
69
  apiKeyStorageKeys: () => apiKeyStorageKeys,
@@ -82,14 +80,12 @@ __export(index_exports, {
82
80
  clearLocalDiscoveryCache: () => clearLocalDiscoveryCache,
83
81
  clearRuntimeModels: () => clearRuntimeModels,
84
82
  closeLogger: () => closeLogger,
85
- createAutoUpdater: () => createAutoUpdater,
86
- decodeOggOpus: () => decodeOggOpus,
83
+ configureAppDataDir: () => configureAppDataDir,
87
84
  describeAuthMethods: () => describeAuthMethods,
88
85
  detectKimiCodeBaseUrl: () => detectKimiCodeBaseUrl,
89
86
  detectMiniMaxBaseUrl: () => detectMiniMaxBaseUrl,
90
87
  detectXiaomiTokenPlanBaseUrl: () => detectXiaomiTokenPlanBaseUrl,
91
88
  discoverLocalModels: () => discoverLocalModels,
92
- downmixToMono: () => downmixToMono,
93
89
  dualAuthProvider: () => dualAuthProvider,
94
90
  dualAuthProviderByOAuthKey: () => dualAuthProviderByOAuthKey,
95
91
  endpointRoot: () => endpointRoot,
@@ -128,7 +124,6 @@ __export(index_exports, {
128
124
  isLegacyClaudeOAuth: () => isLegacyClaudeOAuth,
129
125
  isLocalModelId: () => isLocalModelId,
130
126
  isLoggerOpen: () => isLoggerOpen,
131
- isModelLoaded: () => isModelLoaded,
132
127
  isPaidModel: () => isPaidModel,
133
128
  isThinkingLevelSupported: () => isThinkingLevelSupported,
134
129
  localAuthStorageKey: () => localAuthStorageKey,
@@ -155,17 +150,14 @@ __export(index_exports, {
155
150
  registerLogCleanup: () => registerLogCleanup,
156
151
  registerRuntimeModels: () => registerRuntimeModels,
157
152
  requiredKeyLabel: () => requiredKeyLabel,
158
- resample: () => resample,
159
153
  resolveClaudeCodeBinary: () => resolveClaudeCodeBinary,
160
154
  revokeChatGPTSignIn: () => revokeChatGPTSignIn,
161
155
  savedChatGPTAccounts: () => savedChatGPTAccounts,
162
- setProgressCallback: () => setProgressCallback,
163
156
  setProviderCatalog: () => setProviderCatalog,
164
157
  signInWithClaudeCode: () => signInWithClaudeCode,
165
158
  signOutOfClaudeCode: () => signOutOfClaudeCode,
166
159
  storageKeyProvider: () => storageKeyProvider,
167
160
  toModelInfo: () => toModelInfo,
168
- transcribeVoice: () => transcribeVoice,
169
161
  usesOpenAICodexTransport: () => usesOpenAICodexTransport,
170
162
  verifyIdToken: () => verifyIdToken,
171
163
  withFileLock: () => withFileLock,
@@ -181,7 +173,7 @@ var KIMI_CODE_BASE_URLS = [KIMI_CODE_DEFAULT_BASE_URL, KIMI_CODE_OVERSEAS_BASE_U
181
173
  async function probeHost(baseUrl, apiKey, fetchImpl, timeoutMs) {
182
174
  try {
183
175
  const res = await fetchImpl(`${baseUrl}/models`, {
184
- headers: { Authorization: `Bearer ${apiKey}`, "User-Agent": import_gg_ai.GG_CODER_USER_AGENT },
176
+ headers: { Authorization: `Bearer ${apiKey}`, "User-Agent": (0, import_gg_ai.getAppIdentity)().userAgent },
185
177
  signal: AbortSignal.timeout(timeoutMs)
186
178
  });
187
179
  if (res.ok) return "authorized";
@@ -213,8 +205,12 @@ var import_node_crypto4 = __toESM(require("crypto"), 1);
213
205
  // src/paths.ts
214
206
  var import_node_path = __toESM(require("path"), 1);
215
207
  var import_node_os = __toESM(require("os"), 1);
208
+ var dataDirOverride;
209
+ function configureAppDataDir(dir) {
210
+ dataDirOverride = dir === void 0 ? void 0 : import_node_path.default.resolve(dir);
211
+ }
216
212
  function getAppPaths() {
217
- const agentDir = import_node_path.default.join(import_node_os.default.homedir(), ".gg");
213
+ const agentDir = dataDirOverride ?? import_node_path.default.join(import_node_os.default.homedir(), ".gg");
218
214
  return {
219
215
  agentDir,
220
216
  sessionsDir: import_node_path.default.join(agentDir, "sessions"),
@@ -337,9 +333,9 @@ async function extractFileFromTarGz(tgzPath, entryName, destPath) {
337
333
  if (type === "x") kind = "pax";
338
334
  else if (type === "L") kind = "longname";
339
335
  else {
340
- const path7 = overridePath ?? name;
336
+ const path6 = overridePath ?? name;
341
337
  overridePath = void 0;
342
- if ((type === "0" || type === "\0" || type === "7") && path7 === entryName) {
338
+ if ((type === "0" || type === "\0" || type === "7") && path6 === entryName) {
343
339
  kind = "target";
344
340
  out = await import_promises.default.open(destPath, "w", 493);
345
341
  if (size === 0) {
@@ -756,6 +752,7 @@ var import_node_http = __toESM(require("http"), 1);
756
752
  var import_node_crypto2 = __toESM(require("crypto"), 1);
757
753
  var import_promises3 = __toESM(require("fs/promises"), 1);
758
754
  var import_node_path3 = __toESM(require("path"), 1);
755
+ var import_gg_ai2 = require("@kenkaiiii/gg-ai");
759
756
 
760
757
  // src/oauth/pkce.ts
761
758
  function base64urlEncode(bytes) {
@@ -788,7 +785,6 @@ var TOKEN_URL = `${ISSUER}/api/accounts/oauth/token`;
788
785
  var REVOKE_URL = `${ISSUER}/api/accounts/oauth/revoke`;
789
786
  var JWKS_URL = `${ISSUER}/.well-known/jwks.json`;
790
787
  var REGISTRATION_CLIENT_ID = "dynamic_agent_client";
791
- var AGENT_NAME = "GG Coder";
792
788
  var RESOURCE = "https://api.openai.com/v1";
793
789
  var CHATGPT_PLAN_SCOPE = "chatgpt.tokens.use.direct";
794
790
  var SCOPES = `openid profile email offline_access resource.invoke ${CHATGPT_PLAN_SCOPE}`;
@@ -799,10 +795,13 @@ var PREFERRED_PORT = 1455;
799
795
  var CALLBACK_TIMEOUT_MS = 12e4;
800
796
  var MAX_PASTE_ATTEMPTS = 3;
801
797
  var ID_TOKEN_CLOCK_SKEW_S = 60;
802
- var CHATGPT_PLAN_NOT_ENABLED_MESSAGE = "ChatGPT plan use isn't enabled for GG Coder. Allow Use your ChatGPT plan, or add an OpenAI API key.";
798
+ var appName = () => (0, import_gg_ai2.getAppIdentity)().name;
799
+ function chatgptPlanNotEnabledMessage() {
800
+ return `ChatGPT plan use isn't enabled for ${appName()}. Allow Use your ChatGPT plan, or add an OpenAI API key.`;
801
+ }
803
802
  var ChatGPTPlanNotEnabledError = class extends Error {
804
803
  constructor() {
805
- super(CHATGPT_PLAN_NOT_ENABLED_MESSAGE);
804
+ super(chatgptPlanNotEnabledMessage());
806
805
  this.name = "ChatGPTPlanNotEnabledError";
807
806
  }
808
807
  };
@@ -908,7 +907,7 @@ async function loginChatGPT(callbacks, options = {}) {
908
907
  const redirectUri = `http://127.0.0.1:${listener.port}${CALLBACK_PATH}`;
909
908
  const url = new URL(AUTHORIZE_URL);
910
909
  url.searchParams.set("client_id", knownClientId ?? REGISTRATION_CLIENT_ID);
911
- if (!knownClientId) url.searchParams.set("agent_name_hint", AGENT_NAME);
910
+ if (!knownClientId) url.searchParams.set("agent_name_hint", appName());
912
911
  url.searchParams.set("ext_agent_host_id", hostId);
913
912
  if (registration && current && options.previous?.idToken) {
914
913
  url.searchParams.set("id_token_hint", options.previous.idToken);
@@ -942,7 +941,7 @@ async function loginChatGPT(callbacks, options = {}) {
942
941
  const clientId = knownClientId ?? issued;
943
942
  if (!clientId || clientId === REGISTRATION_CLIENT_ID) {
944
943
  throw new Error(
945
- "ChatGPT didn't finish registering GG Coder. Start the sign-in again, and paste the full callback URL if you're on another machine."
944
+ `ChatGPT didn't finish registering ${appName()}. Start the sign-in again, and paste the full callback URL if you're on another machine.`
946
945
  );
947
946
  }
948
947
  issuedClientId = clientId;
@@ -1042,7 +1041,7 @@ async function startCallbackListener(expectedState, anyPort) {
1042
1041
  }
1043
1042
  res.writeHead(200, { "Content-Type": "text/html" });
1044
1043
  res.end(
1045
- "<html><body><h1>You're signed in to GG Coder.</h1><p>You can close this tab.</p></body></html>"
1044
+ `<html><body><h1>You're signed in to ${escapeHtml(appName())}.</h1><p>You can close this tab.</p></body></html>`
1046
1045
  );
1047
1046
  settle?.resolve(url.searchParams);
1048
1047
  server.close();
@@ -1283,6 +1282,9 @@ async function verifyIdToken(idToken, expected) {
1283
1282
  if (claims.nonce !== expected.nonce) throw new Error("ChatGPT ID token nonce mismatch.");
1284
1283
  return claims;
1285
1284
  }
1285
+ function escapeHtml(text) {
1286
+ return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
1287
+ }
1286
1288
 
1287
1289
  // src/file-lock.ts
1288
1290
  var import_promises4 = __toESM(require("fs/promises"), 1);
@@ -1372,7 +1374,7 @@ function isAlive(pid) {
1372
1374
  var import_node_fs3 = __toESM(require("fs"), 1);
1373
1375
  var import_node_path4 = __toESM(require("path"), 1);
1374
1376
  var import_node_crypto3 = require("crypto");
1375
- var import_gg_ai2 = require("@kenkaiiii/gg-ai");
1377
+ var import_gg_ai3 = require("@kenkaiiii/gg-ai");
1376
1378
  var MAX_BYTES = 10 * 1024 * 1024;
1377
1379
  var ROTATED_GENERATIONS = 3;
1378
1380
  var MIN_HEADROOM_BYTES = 64 * 1024;
@@ -1383,7 +1385,7 @@ var processBytes = 0;
1383
1385
  var rotationFailed = false;
1384
1386
  var capped = false;
1385
1387
  var sessionId = "";
1386
- var appName = "app";
1388
+ var appName2 = "app";
1387
1389
  var cleanups = [];
1388
1390
  var exactSecrets = [];
1389
1391
  function rotateIfNeeded(filePath, force = false) {
@@ -1438,8 +1440,8 @@ function rotateOpenLog() {
1438
1440
  }
1439
1441
  function openLog(filePath, name) {
1440
1442
  if (fd !== null || capped) return false;
1441
- appName = name;
1442
- exactSecrets = (0, import_gg_ai2.environmentSecrets)(process.env);
1443
+ appName2 = name;
1444
+ exactSecrets = (0, import_gg_ai3.environmentSecrets)(process.env);
1443
1445
  try {
1444
1446
  import_node_fs3.default.mkdirSync(import_node_path4.default.dirname(filePath), { recursive: true, mode: 448 });
1445
1447
  } catch {
@@ -1486,10 +1488,10 @@ function isLoggerOpen() {
1486
1488
  function log(level, category, message, data) {
1487
1489
  if (fd === null) return;
1488
1490
  const ts = (/* @__PURE__ */ new Date()).toISOString();
1489
- const safeMessage = (0, import_gg_ai2.redactText)(message, { secrets: exactSecrets });
1491
+ const safeMessage = (0, import_gg_ai3.redactText)(message, { secrets: exactSecrets });
1490
1492
  let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
1491
1493
  if (data) {
1492
- const safeData = (0, import_gg_ai2.redactValue)(data, { secrets: exactSecrets });
1494
+ const safeData = (0, import_gg_ai3.redactValue)(data, { secrets: exactSecrets });
1493
1495
  const pairs = Object.entries(safeData).map(([k, v]) => {
1494
1496
  if (typeof v === "string") return `${k}=${v}`;
1495
1497
  if (typeof v === "bigint") return `${k}=${String(v)}`;
@@ -1527,7 +1529,7 @@ function registerLogCleanup(fn) {
1527
1529
  }
1528
1530
  function closeLogger(opts) {
1529
1531
  if (fd !== null) {
1530
- if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
1532
+ if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName2} shutting down`);
1531
1533
  try {
1532
1534
  if (fd !== null) import_node_fs3.default.closeSync(fd);
1533
1535
  } catch {
@@ -1551,7 +1553,7 @@ function isHiddenProvider(provider) {
1551
1553
  }
1552
1554
 
1553
1555
  // src/auth-storage.ts
1554
- var import_gg_ai3 = require("@kenkaiiii/gg-ai");
1556
+ var import_gg_ai4 = require("@kenkaiiii/gg-ai");
1555
1557
 
1556
1558
  // src/minimax-region.ts
1557
1559
  var MINIMAX_GLOBAL_BASE_URL = "https://api.minimax.io/anthropic";
@@ -1920,7 +1922,7 @@ var AuthStorage = class {
1920
1922
  */
1921
1923
  async setLocalEndpoint(endpointId, baseUrl, apiKey) {
1922
1924
  await this.setCredentials(`${LOCAL_AUTH_KEY_PREFIX}${endpointId}`, {
1923
- accessToken: apiKey && apiKey.length > 0 ? apiKey : import_gg_ai3.LOCAL_NO_API_KEY,
1925
+ accessToken: apiKey && apiKey.length > 0 ? apiKey : import_gg_ai4.LOCAL_NO_API_KEY,
1924
1926
  refreshToken: "",
1925
1927
  expiresAt: Date.now() + LOCAL_CREDENTIAL_LIFETIME_MS,
1926
1928
  baseUrl
@@ -3754,12 +3756,12 @@ function clampThinkingForPlanMode(level) {
3754
3756
  }
3755
3757
 
3756
3758
  // src/local-models.ts
3757
- var import_gg_ai4 = require("@kenkaiiii/gg-ai");
3759
+ var import_gg_ai5 = require("@kenkaiiii/gg-ai");
3758
3760
  var DEFAULT_LOCAL_ENDPOINTS = [
3759
3761
  { id: "ollama", label: "Ollama", baseUrl: "http://127.0.0.1:11434/v1", kind: "ollama" }
3760
3762
  ];
3761
3763
  var FALLBACK_CONTEXT_WINDOW = 4096;
3762
- var LOCAL_API_KEY_PLACEHOLDER = import_gg_ai4.LOCAL_NO_API_KEY;
3764
+ var LOCAL_API_KEY_PLACEHOLDER = import_gg_ai5.LOCAL_NO_API_KEY;
3763
3765
  var DEFAULT_PROBE_TIMEOUT_MS = 1200;
3764
3766
  var ENRICH_CONCURRENCY = 6;
3765
3767
  var CACHE_TTL_MS = 3e4;
@@ -3788,7 +3790,7 @@ function endpointRoot(baseUrl) {
3788
3790
  return baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
3789
3791
  }
3790
3792
  function authHeaders(endpoint) {
3791
- const key = (0, import_gg_ai4.localBearerKey)(endpoint.apiKey);
3793
+ const key = (0, import_gg_ai5.localBearerKey)(endpoint.apiKey);
3792
3794
  return {
3793
3795
  ...key ? { Authorization: `Bearer ${key}` } : {},
3794
3796
  Accept: "application/json"
@@ -4465,7 +4467,7 @@ function authPriorityNote(provider) {
4465
4467
  }
4466
4468
 
4467
4469
  // src/provider-usage.ts
4468
- var import_gg_ai5 = require("@kenkaiiii/gg-ai");
4470
+ var import_gg_ai6 = require("@kenkaiiii/gg-ai");
4469
4471
  var SubscriptionUsageError = class extends Error {
4470
4472
  constructor(message, status, retryAfterMs2) {
4471
4473
  super(message);
@@ -4543,7 +4545,7 @@ async function fetchKimiUsage(credentials, fetchFn, signal, now) {
4543
4545
  headers: {
4544
4546
  Authorization: "Bearer " + credentials.accessToken,
4545
4547
  Accept: "application/json",
4546
- "User-Agent": import_gg_ai5.GG_CODER_USER_AGENT
4548
+ "User-Agent": (0, import_gg_ai6.getAppIdentity)().userAgent
4547
4549
  }
4548
4550
  });
4549
4551
  const data = await readUsageResponse(response, now());
@@ -4602,508 +4604,11 @@ async function fetchSubscriptionUsage(provider, credentials, options = {}) {
4602
4604
  throw new SubscriptionUsageError(message);
4603
4605
  }
4604
4606
  }
4605
-
4606
- // src/telegram.ts
4607
- var TELEGRAM_API = "https://api.telegram.org";
4608
- var LONG_POLL_SECONDS = 30;
4609
- var API_TIMEOUT_MS = 3e4;
4610
- var MAX_MESSAGE_LENGTH = 4096;
4611
- var TelegramBot = class {
4612
- token;
4613
- allowedUserId;
4614
- offset = 0;
4615
- running = false;
4616
- /** Aborts the in-flight long poll so stop() takes effect immediately. */
4617
- pollAbort = null;
4618
- onMessage = null;
4619
- onVoiceMessage = null;
4620
- onCallback = null;
4621
- onBotAdded = null;
4622
- onBotRemoved = null;
4623
- constructor(config) {
4624
- this.token = config.botToken;
4625
- this.allowedUserId = config.allowedUserId;
4626
- }
4627
- /** Register handler for incoming text messages. */
4628
- onText(handler) {
4629
- this.onMessage = handler;
4630
- }
4631
- /** Register handler for incoming voice notes. */
4632
- onVoice(handler) {
4633
- this.onVoiceMessage = handler;
4634
- }
4635
- /** Register handler for inline keyboard button presses. */
4636
- onCallbackQuery(handler) {
4637
- this.onCallback = handler;
4638
- }
4639
- /** Register handler for when the bot is added to a group. */
4640
- onAddedToGroup(handler) {
4641
- this.onBotAdded = handler;
4642
- }
4643
- /** Register handler for when the bot is removed from a group. */
4644
- onRemovedFromGroup(handler) {
4645
- this.onBotRemoved = handler;
4646
- }
4647
- /** Start long polling. Blocks until stop() is called. */
4648
- async start() {
4649
- this.running = true;
4650
- const me = await this.apiCall("getMe");
4651
- if (!me.ok) {
4652
- throw new Error(`Invalid bot token: ${JSON.stringify(me)}`);
4653
- }
4654
- while (this.running) {
4655
- try {
4656
- const updates = await this.getUpdates();
4657
- for (const update of updates) {
4658
- await this.handleUpdate(update);
4659
- }
4660
- } catch (err) {
4661
- if (!this.running) break;
4662
- console.error(`[telegram] Poll error: ${err instanceof Error ? err.message : err}`);
4663
- await sleep(3e3);
4664
- }
4665
- }
4666
- }
4667
- /** Stop long polling. */
4668
- stop() {
4669
- this.running = false;
4670
- this.pollAbort?.abort();
4671
- }
4672
- /** Send a text message to a specific chat. Converts markdown and splits long messages. */
4673
- async send(chatId, text, buttons) {
4674
- const converted = toTelegramMarkdown(text);
4675
- const chunks = splitMessage(converted);
4676
- for (let i = 0; i < chunks.length; i++) {
4677
- const isLast = i === chunks.length - 1;
4678
- const replyMarkup = isLast && buttons ? {
4679
- inline_keyboard: buttons.map(
4680
- (row) => row.map((b) => ({ text: b.text, callback_data: b.callback_data }))
4681
- )
4682
- } : void 0;
4683
- await this.apiCall("sendMessage", {
4684
- chat_id: chatId,
4685
- text: chunks[i],
4686
- parse_mode: "Markdown",
4687
- ...replyMarkup ? { reply_markup: replyMarkup } : {}
4688
- });
4689
- }
4690
- }
4691
- /** Send a plain text message (no markdown parsing) to a specific chat. */
4692
- async sendPlain(chatId, text) {
4693
- const chunks = splitMessage(text);
4694
- for (const chunk of chunks) {
4695
- await this.apiCall("sendMessage", {
4696
- chat_id: chatId,
4697
- text: chunk
4698
- });
4699
- }
4700
- }
4701
- /** Send a typing indicator to a specific chat. */
4702
- async sendTyping(chatId) {
4703
- await this.apiCall("sendChatAction", {
4704
- chat_id: chatId,
4705
- action: "typing"
4706
- });
4707
- }
4708
- /** Get a direct download URL for a Telegram file. */
4709
- async getFileUrl(fileId) {
4710
- const result = await this.apiCall("getFile", { file_id: fileId });
4711
- if (!result.ok) throw new Error(`Failed to get file: ${JSON.stringify(result)}`);
4712
- const filePath = result.result.file_path;
4713
- return `${TELEGRAM_API}/file/bot${this.token}/${filePath}`;
4714
- }
4715
- // ── Private ───────────────────────────────────────────
4716
- async getUpdates() {
4717
- const poll = new AbortController();
4718
- this.pollAbort = poll;
4719
- let result;
4720
- try {
4721
- result = await this.apiCall(
4722
- "getUpdates",
4723
- {
4724
- offset: this.offset,
4725
- timeout: LONG_POLL_SECONDS,
4726
- allowed_updates: ["message", "callback_query", "my_chat_member"]
4727
- },
4728
- // A half-open socket would otherwise hang the poll forever.
4729
- AbortSignal.any([poll.signal, AbortSignal.timeout((LONG_POLL_SECONDS + 15) * 1e3)])
4730
- );
4731
- } finally {
4732
- if (this.pollAbort === poll) this.pollAbort = null;
4733
- }
4734
- if (!result.ok || !Array.isArray(result.result)) {
4735
- throw new Error(`getUpdates failed: ${JSON.stringify(result)}`);
4736
- }
4737
- const updates = result.result;
4738
- if (updates.length > 0) {
4739
- this.offset = updates[updates.length - 1].update_id + 1;
4740
- }
4741
- return updates;
4742
- }
4743
- async handleUpdate(update) {
4744
- if (update.message) {
4745
- const msg = update.message;
4746
- if (msg.from.id !== this.allowedUserId) {
4747
- return;
4748
- }
4749
- if (msg.text && this.onMessage) {
4750
- this.onMessage({
4751
- text: msg.text,
4752
- chatId: msg.chat.id,
4753
- chatType: msg.chat.type,
4754
- chatTitle: msg.chat.title
4755
- });
4756
- } else if (msg.voice && this.onVoiceMessage) {
4757
- this.onVoiceMessage({
4758
- fileId: msg.voice.file_id,
4759
- duration: msg.voice.duration,
4760
- chatId: msg.chat.id,
4761
- chatType: msg.chat.type,
4762
- chatTitle: msg.chat.title
4763
- });
4764
- }
4765
- }
4766
- if (update.my_chat_member) {
4767
- const member = update.my_chat_member;
4768
- const status = member.new_chat_member.status;
4769
- if ((status === "member" || status === "administrator") && this.onBotAdded) {
4770
- this.onBotAdded(member.chat.id, member.chat.title);
4771
- } else if ((status === "left" || status === "kicked") && this.onBotRemoved) {
4772
- this.onBotRemoved(member.chat.id);
4773
- }
4774
- }
4775
- if (update.callback_query) {
4776
- const cb = update.callback_query;
4777
- if (cb.from.id !== this.allowedUserId) return;
4778
- await this.apiCall("answerCallbackQuery", { callback_query_id: cb.id });
4779
- if (cb.data && this.onCallback) {
4780
- this.onCallback(cb.data, cb.message.chat.id);
4781
- }
4782
- }
4783
- }
4784
- async apiCall(method, body, signal = AbortSignal.timeout(API_TIMEOUT_MS)) {
4785
- const url = `${TELEGRAM_API}/bot${this.token}/${method}`;
4786
- const response = await fetch(url, {
4787
- method: "POST",
4788
- headers: { "Content-Type": "application/json" },
4789
- body: body ? JSON.stringify(body) : void 0,
4790
- signal
4791
- });
4792
- if (!response.ok) {
4793
- return { ok: false };
4794
- }
4795
- return response.json();
4796
- }
4797
- };
4798
- function toTelegramMarkdown(text) {
4799
- const lines = text.split("\n");
4800
- const result = [];
4801
- let inCodeBlock = false;
4802
- for (const line of lines) {
4803
- if (line.trimStart().startsWith("```")) {
4804
- inCodeBlock = !inCodeBlock;
4805
- result.push(line);
4806
- continue;
4807
- }
4808
- if (inCodeBlock) {
4809
- result.push(line);
4810
- continue;
4811
- }
4812
- let transformed = line;
4813
- const headingMatch = transformed.match(/^(#{1,6})\s+(.+)$/);
4814
- if (headingMatch) {
4815
- transformed = `*${headingMatch[2]}*`;
4816
- result.push(transformed);
4817
- continue;
4818
- }
4819
- if (/^(-{3,}|_{3,}|\*{3,})$/.test(transformed.trim())) {
4820
- result.push("");
4821
- continue;
4822
- }
4823
- transformed = transformed.replace(/\*\*(.+?)\*\*/g, "*$1*");
4824
- result.push(transformed);
4825
- }
4826
- return result.join("\n");
4827
- }
4828
- function splitMessage(text) {
4829
- if (text.length <= MAX_MESSAGE_LENGTH) return [text];
4830
- const chunks = [];
4831
- let remaining = text;
4832
- while (remaining.length > 0) {
4833
- if (remaining.length <= MAX_MESSAGE_LENGTH) {
4834
- chunks.push(remaining);
4835
- break;
4836
- }
4837
- let splitAt = remaining.lastIndexOf("\n", MAX_MESSAGE_LENGTH);
4838
- if (splitAt === -1 || splitAt < MAX_MESSAGE_LENGTH * 0.5) {
4839
- splitAt = remaining.lastIndexOf(" ", MAX_MESSAGE_LENGTH);
4840
- }
4841
- if (splitAt === -1 || splitAt < MAX_MESSAGE_LENGTH * 0.5) {
4842
- splitAt = MAX_MESSAGE_LENGTH;
4843
- }
4844
- chunks.push(remaining.slice(0, splitAt));
4845
- remaining = remaining.slice(splitAt).trimStart();
4846
- }
4847
- return chunks;
4848
- }
4849
- function sleep(ms) {
4850
- return new Promise((r) => setTimeout(r, ms));
4851
- }
4852
-
4853
- // src/voice-transcriber.ts
4854
- var TARGET_SAMPLE_RATE = 16e3;
4855
- var MODEL_ID = "Xenova/whisper-tiny.en";
4856
- var transcriber = null;
4857
- var loadPromise = null;
4858
- var onProgress = null;
4859
- function setProgressCallback(cb) {
4860
- onProgress = cb;
4861
- }
4862
- function resample(audio, fromRate, toRate) {
4863
- if (fromRate === toRate) return audio;
4864
- const ratio = fromRate / toRate;
4865
- const newLength = Math.round(audio.length / ratio);
4866
- const result = new Float32Array(newLength);
4867
- for (let i = 0; i < newLength; i++) {
4868
- const srcIndex = i * ratio;
4869
- const low = Math.floor(srcIndex);
4870
- const high = Math.min(low + 1, audio.length - 1);
4871
- const frac = srcIndex - low;
4872
- result[i] = audio[low] * (1 - frac) + audio[high] * frac;
4873
- }
4874
- return result;
4875
- }
4876
- function downmixToMono(channelData) {
4877
- if (channelData.length === 0) return new Float32Array();
4878
- if (channelData.length === 1) return channelData[0];
4879
- const samples = channelData[0].length;
4880
- const out = new Float32Array(samples);
4881
- const scale = 1 / channelData.length;
4882
- for (let i = 0; i < samples; i++) {
4883
- let mixed = 0;
4884
- for (const channel of channelData) mixed += channel[i] ?? 0;
4885
- out[i] = mixed * scale;
4886
- }
4887
- return out;
4888
- }
4889
- async function decodeOggOpus(buffer) {
4890
- const { OggOpusDecoder } = await import("ogg-opus-decoder");
4891
- const decoder = new OggOpusDecoder();
4892
- await decoder.ready;
4893
- try {
4894
- const decoded = await decoder.decodeFile(buffer);
4895
- if (!decoded.channelData?.length || !decoded.channelData[0]?.length) {
4896
- throw new Error("Decoded audio is empty");
4897
- }
4898
- const mono = downmixToMono(decoded.channelData);
4899
- return resample(mono, decoded.sampleRate, TARGET_SAMPLE_RATE);
4900
- } finally {
4901
- decoder.free();
4902
- }
4903
- }
4904
- async function getTranscriber() {
4905
- if (transcriber) return transcriber;
4906
- if (!loadPromise) {
4907
- loadPromise = (async () => {
4908
- const { pipeline } = await import("@huggingface/transformers");
4909
- const instance = await pipeline("automatic-speech-recognition", MODEL_ID, {
4910
- dtype: "fp32",
4911
- progress_callback: onProgress ?? void 0
4912
- });
4913
- transcriber = instance;
4914
- return instance;
4915
- })();
4916
- }
4917
- return loadPromise;
4918
- }
4919
- function isModelLoaded() {
4920
- return transcriber !== null;
4921
- }
4922
- async function transcribeVoice(fileUrl) {
4923
- const response = await fetch(fileUrl, { signal: AbortSignal.timeout(6e4) });
4924
- if (!response.ok) throw new Error(`Failed to download voice file: ${response.status}`);
4925
- const buffer = new Uint8Array(await response.arrayBuffer());
4926
- const pcm = await decodeOggOpus(buffer);
4927
- const asr = await getTranscriber();
4928
- const result = await asr(pcm);
4929
- const text = Array.isArray(result) ? result[0]?.text : result.text;
4930
- return (text ?? "").trim();
4931
- }
4932
-
4933
- // src/auto-update.ts
4934
- var import_node_child_process2 = require("child_process");
4935
- var import_node_fs5 = __toESM(require("fs"), 1);
4936
- var import_node_path6 = __toESM(require("path"), 1);
4937
- var CHECK_INTERVAL_MS = 60 * 60 * 1e3;
4938
- var FETCH_TIMEOUT_MS = 1e4;
4939
- function compareVersions2(a, b) {
4940
- const pa = a.split(".").map(Number);
4941
- const pb = b.split(".").map(Number);
4942
- for (let i = 0; i < 3; i++) {
4943
- const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
4944
- if (diff !== 0) return diff;
4945
- }
4946
- return 0;
4947
- }
4948
- function performUpdateInBackground(command) {
4949
- try {
4950
- const parts = command.split(" ");
4951
- const child = (0, import_node_child_process2.spawn)(parts[0], parts.slice(1), {
4952
- detached: true,
4953
- stdio: "ignore",
4954
- env: { ...process.env, npm_config_loglevel: "silent" }
4955
- });
4956
- child.unref();
4957
- } catch {
4958
- }
4959
- }
4960
- function createAutoUpdater(config) {
4961
- const REGISTRY_URL = `https://registry.npmjs.org/${config.packageName}/latest`;
4962
- 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).`);
4963
- let periodicTimer = null;
4964
- function stateFilePath() {
4965
- return typeof config.stateFilePath === "function" ? config.stateFilePath() : config.stateFilePath;
4966
- }
4967
- function readState() {
4968
- try {
4969
- const raw = import_node_fs5.default.readFileSync(stateFilePath(), "utf-8");
4970
- return JSON.parse(raw);
4971
- } catch {
4972
- return null;
4973
- }
4974
- }
4975
- function writeState(state) {
4976
- try {
4977
- const filePath = stateFilePath();
4978
- import_node_fs5.default.mkdirSync(import_node_path6.default.dirname(filePath), { recursive: true, mode: 448 });
4979
- import_node_fs5.default.writeFileSync(filePath, JSON.stringify(state));
4980
- } catch {
4981
- }
4982
- }
4983
- function detectInstallInfo() {
4984
- const scriptPath = (process.argv[1] ?? "").replace(/\\/g, "/");
4985
- if (scriptPath.includes("/_npx/")) {
4986
- return { packageManager: "unknown" /* UNKNOWN */, updateCommand: null };
4987
- }
4988
- if (scriptPath.includes("/.pnpm") || scriptPath.includes("/pnpm/global")) {
4989
- return {
4990
- packageManager: "pnpm" /* PNPM */,
4991
- updateCommand: `pnpm add -g ${config.packageName}@latest`
4992
- };
4993
- }
4994
- if (scriptPath.includes("/.yarn/") || scriptPath.includes("/yarn/global")) {
4995
- return {
4996
- packageManager: "yarn" /* YARN */,
4997
- updateCommand: `yarn global add ${config.packageName}@latest`
4998
- };
4999
- }
5000
- return {
5001
- packageManager: "npm" /* NPM */,
5002
- updateCommand: `npm install -g ${config.packageName}@latest`
5003
- };
5004
- }
5005
- async function fetchLatestVersion() {
5006
- try {
5007
- const controller = new AbortController();
5008
- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
5009
- const response = await fetch(REGISTRY_URL, { signal: controller.signal });
5010
- clearTimeout(timeout);
5011
- const data = await response.json();
5012
- const version = data.version?.trim();
5013
- return version && /^\d+\.\d+\.\d+/.test(version) ? version : null;
5014
- } catch {
5015
- return null;
5016
- }
5017
- }
5018
- function scheduleBackgroundCheck(currentVersion) {
5019
- fetchLatestVersion().then((latestVersion) => {
5020
- const newState = {
5021
- lastCheckedAt: Date.now(),
5022
- latestVersion: latestVersion ?? void 0,
5023
- updatePending: false
5024
- };
5025
- if (latestVersion && compareVersions2(latestVersion, currentVersion) > 0) {
5026
- newState.updatePending = true;
5027
- }
5028
- writeState(newState);
5029
- }).catch(() => {
5030
- });
5031
- }
5032
- function checkAndAutoUpdate(currentVersion) {
5033
- try {
5034
- const state = readState();
5035
- let message = null;
5036
- if (state?.updatePending && state.latestVersion) {
5037
- if (compareVersions2(state.latestVersion, currentVersion) > 0) {
5038
- const info = detectInstallInfo();
5039
- if (info.updateCommand) {
5040
- performUpdateInBackground(info.updateCommand);
5041
- message = `Ken just shipped ${state.latestVersion}! Installing in the background \u2014 takes effect next launch.`;
5042
- writeState({
5043
- ...state,
5044
- lastCheckedAt: Date.now(),
5045
- updatePending: false,
5046
- lastUpdateAttempt: Date.now()
5047
- });
5048
- }
5049
- } else {
5050
- writeState({ ...state, updatePending: false });
5051
- }
5052
- }
5053
- const shouldCheck = !state || Date.now() - state.lastCheckedAt > CHECK_INTERVAL_MS;
5054
- if (shouldCheck) scheduleBackgroundCheck(currentVersion);
5055
- return message;
5056
- } catch {
5057
- return null;
5058
- }
5059
- }
5060
- function getPendingUpdate(currentVersion) {
5061
- try {
5062
- const state = readState();
5063
- if (!state?.latestVersion) return null;
5064
- if (compareVersions2(state.latestVersion, currentVersion) <= 0) return null;
5065
- return { latestVersion: state.latestVersion };
5066
- } catch {
5067
- return null;
5068
- }
5069
- }
5070
- function startPeriodicUpdateCheck(currentVersion, onUpdate) {
5071
- if (periodicTimer) return;
5072
- periodicTimer = setInterval(() => {
5073
- fetchLatestVersion().then((latestVersion) => {
5074
- if (!latestVersion) return;
5075
- if (compareVersions2(latestVersion, currentVersion) <= 0) return;
5076
- const info = detectInstallInfo();
5077
- if (!info.updateCommand) return;
5078
- writeState({ lastCheckedAt: Date.now(), latestVersion, updatePending: true });
5079
- onUpdate(
5080
- periodicMessage({ currentVersion, latestVersion, updateCommand: info.updateCommand })
5081
- );
5082
- stopPeriodicUpdateCheck();
5083
- }).catch(() => {
5084
- });
5085
- }, CHECK_INTERVAL_MS);
5086
- periodicTimer.unref();
5087
- }
5088
- function stopPeriodicUpdateCheck() {
5089
- if (periodicTimer) {
5090
- clearInterval(periodicTimer);
5091
- periodicTimer = null;
5092
- }
5093
- }
5094
- return {
5095
- checkAndAutoUpdate,
5096
- getPendingUpdate,
5097
- startPeriodicUpdateCheck,
5098
- stopPeriodicUpdateCheck
5099
- };
5100
- }
5101
4607
  // Annotate the CommonJS export names for ESM import in node:
5102
4608
  0 && (module.exports = {
5103
4609
  AUTH_PROVIDERS,
5104
4610
  AuthStorage,
5105
4611
  CHATGPT_PLAN_BASE_URL,
5106
- CHATGPT_PLAN_NOT_ENABLED_MESSAGE,
5107
4612
  CHATGPT_PLAN_SCOPE,
5108
4613
  CHATGPT_USAGE_URL,
5109
4614
  CLAUDE_CODE_AUTH_KEY,
@@ -5135,7 +4640,6 @@ function createAutoUpdater(config) {
5135
4640
  PLAN_MODE_THINKING_CAP,
5136
4641
  RETIRED_SIGN_INS,
5137
4642
  SubscriptionUsageError,
5138
- TelegramBot,
5139
4643
  XIAOMI_CREDITS_KEY,
5140
4644
  XIAOMI_TOKEN_PLAN_BASE_URLS,
5141
4645
  apiKeyStorageKeys,
@@ -5152,14 +4656,12 @@ function createAutoUpdater(config) {
5152
4656
  clearLocalDiscoveryCache,
5153
4657
  clearRuntimeModels,
5154
4658
  closeLogger,
5155
- createAutoUpdater,
5156
- decodeOggOpus,
4659
+ configureAppDataDir,
5157
4660
  describeAuthMethods,
5158
4661
  detectKimiCodeBaseUrl,
5159
4662
  detectMiniMaxBaseUrl,
5160
4663
  detectXiaomiTokenPlanBaseUrl,
5161
4664
  discoverLocalModels,
5162
- downmixToMono,
5163
4665
  dualAuthProvider,
5164
4666
  dualAuthProviderByOAuthKey,
5165
4667
  endpointRoot,
@@ -5198,7 +4700,6 @@ function createAutoUpdater(config) {
5198
4700
  isLegacyClaudeOAuth,
5199
4701
  isLocalModelId,
5200
4702
  isLoggerOpen,
5201
- isModelLoaded,
5202
4703
  isPaidModel,
5203
4704
  isThinkingLevelSupported,
5204
4705
  localAuthStorageKey,
@@ -5225,17 +4726,14 @@ function createAutoUpdater(config) {
5225
4726
  registerLogCleanup,
5226
4727
  registerRuntimeModels,
5227
4728
  requiredKeyLabel,
5228
- resample,
5229
4729
  resolveClaudeCodeBinary,
5230
4730
  revokeChatGPTSignIn,
5231
4731
  savedChatGPTAccounts,
5232
- setProgressCallback,
5233
4732
  setProviderCatalog,
5234
4733
  signInWithClaudeCode,
5235
4734
  signOutOfClaudeCode,
5236
4735
  storageKeyProvider,
5237
4736
  toModelInfo,
5238
- transcribeVoice,
5239
4737
  usesOpenAICodexTransport,
5240
4738
  verifyIdToken,
5241
4739
  withFileLock,