kimiflare 0.37.0 → 0.38.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.js CHANGED
@@ -486,6 +486,7 @@ async function* runKimi(opts2) {
486
486
  if (opts2.cloudMode && !opts2.cloudToken) {
487
487
  throw new KimiApiError("kimiflare: cloud mode requires a cloud token. Run `kimiflare auth cloud` to authenticate.", void 0, 401);
488
488
  }
489
+ const requestId = opts2.requestId ?? crypto.randomUUID();
489
490
  const { url, headers: gatewayHeaders } = buildKimiRequestTarget(opts2);
490
491
  const body = {
491
492
  messages: sanitizeMessagesForApi(opts2.messages),
@@ -510,6 +511,7 @@ async function* runKimi(opts2) {
510
511
  headers["X-Session-ID"] = opts2.sessionId;
511
512
  headers["x-session-affinity"] = opts2.sessionId;
512
513
  }
514
+ headers["X-Request-ID"] = requestId;
513
515
  res = await fetch(url, {
514
516
  method: "POST",
515
517
  headers,
@@ -547,7 +549,31 @@ async function* runKimi(opts2) {
547
549
  if (!res.body) throw new KimiApiError("kimiflare: empty response body", void 0, res.status);
548
550
  const meta = readGatewayMeta(res.headers);
549
551
  if (meta) yield { type: "gateway_meta", meta };
550
- yield* parseStream(res.body, opts2.signal);
552
+ let lastUsage = null;
553
+ for await (const ev of parseStream(res.body, opts2.signal)) {
554
+ if (ev.type === "usage") lastUsage = ev.usage;
555
+ yield ev;
556
+ }
557
+ if (opts2.cloudMode && lastUsage && opts2.cloudToken) {
558
+ const reportUrl = "https://api.kimiflare.com/v1/usage/report";
559
+ const reportHeaders = {
560
+ Authorization: `Bearer ${opts2.cloudToken}`,
561
+ "Content-Type": "application/json"
562
+ };
563
+ if (opts2.cloudDeviceId) reportHeaders["X-Device-ID"] = opts2.cloudDeviceId;
564
+ if (opts2.sessionId) reportHeaders["X-Session-ID"] = opts2.sessionId;
565
+ fetch(reportUrl, {
566
+ method: "POST",
567
+ headers: reportHeaders,
568
+ body: JSON.stringify({
569
+ request_id: requestId,
570
+ prompt_tokens: lastUsage.prompt_tokens,
571
+ completion_tokens: lastUsage.completion_tokens,
572
+ cached_tokens: lastUsage.prompt_tokens_details?.cached_tokens ?? 0
573
+ })
574
+ }).catch(() => {
575
+ });
576
+ }
551
577
  return;
552
578
  }
553
579
  }