| 1603 | } |
| 1604 | |
| 1605 | async function fetchAlibabaUsage(input: { |
| 1606 | provider: Provider.Info |
| 1607 | sessionID?: string |
| 1608 | timePeriod?: TimePeriod |
| 1609 | }): Promise<Omit<Record, "providerID" | "providerName" | "fetchedAt">> { |
| 1610 | const DAILY_REQUEST_LIMIT = 2000 |
| 1611 | |
| 1612 | // Alibaba quota is DAILY (2000 req/day), not per-session |
| 1613 | // Always count all requests from today, regardless of session context |
| 1614 | const now = Date.now() |
| 1615 | const startOfDay = new Date(now) |
| 1616 | startOfDay.setHours(0, 0, 0, 0) |
| 1617 | const dayStart = startOfDay.getTime() |
| 1618 | |
| 1619 | // Always scan all sessions for daily quota |
| 1620 | const messageKeys = await Storage.list(["message"]) |
| 1621 | let requestCount = 0 |
| 1622 | |
| 1623 | for (const messageKey of messageKeys) { |
| 1624 | const msg = await Storage.read<MessageV2.Info>(messageKey) |
| 1625 | |
| 1626 | // Only count assistant messages from alibaba provider (use baseProvider if available for connections) |
| 1627 | const targetProviderID = input.provider.baseProvider ?? input.provider.id |
| 1628 | if (msg.role !== "assistant" || msg.providerID !== targetProviderID) { |
| 1629 | continue |
| 1630 | } |
| 1631 | |
| 1632 | const messageTime = msg.time?.completed ?? msg.time?.created |
| 1633 | if (!messageTime || messageTime < dayStart) { |
| 1634 | continue |
| 1635 | } |
| 1636 | |
| 1637 | requestCount++ |
| 1638 | } |
| 1639 | |
| 1640 | const usedPercent = (requestCount / DAILY_REQUEST_LIMIT) * 100 |
| 1641 | const remaining = Math.max(0, DAILY_REQUEST_LIMIT - requestCount) |
| 1642 | const limitReached = requestCount >= DAILY_REQUEST_LIMIT |
| 1643 | |
| 1644 | // Calculate when the quota resets (midnight) |
| 1645 | const tomorrow = new Date(now) |
| 1646 | tomorrow.setDate(tomorrow.getDate() + 1) |
| 1647 | tomorrow.setHours(0, 0, 0, 0) |
| 1648 | const resetsAt = Math.floor(tomorrow.getTime() / 1000) |
| 1649 | |
| 1650 | return { |
| 1651 | planType: `Qwen OAuth\n- Daily requests: ${requestCount.toLocaleString()} / ${DAILY_REQUEST_LIMIT.toLocaleString()} (${remaining.toLocaleString()} remaining)`, |
| 1652 | allowed: !limitReached, |
| 1653 | limitReached, |
| 1654 | limits: { |
| 1655 | primary: { |
| 1656 | usedPercent, |
| 1657 | resetsAt, |
| 1658 | label: "Daily", |
| 1659 | }, |
| 1660 | }, |
| 1661 | credits: { |
| 1662 | hasCredits: true, |