nolo-cli 0.252.0-alpha.2 → 0.253.0-alpha.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.
Files changed (127) hide show
  1. package/{_executeModel-RXHY2BDR.js → _executeModel-VUXEWLLQ.js} +29 -29
  2. package/{addContentAction-F4XO3VRF.js → addContentAction-MT4BECXT.js} +6 -6
  3. package/{addDialogAgentAction-NSCVHTZJ.js → addDialogAgentAction-ZZTJ5GBD.js} +5 -5
  4. package/{agentDeleteCommand-EJAI2VTH.js → agentDeleteCommand-SU5IKIW3.js} +41 -41
  5. package/{agentEmailCommands-YBKHZMMZ.js → agentEmailCommands-SHLVY627.js} +41 -41
  6. package/{agentListCommands-M2KYLAOB.js → agentListCommands-3NTMYMVI.js} +17 -17
  7. package/{agentMachineCommands-GLY6NJWZ.js → agentMachineCommands-MYXLAKQF.js} +13 -12
  8. package/{agentPullCommand-6OCNLVGC.js → agentPullCommand-2EYJ5ENC.js} +1 -1
  9. package/{agentRecordCommands-JANPX6XI.js → agentRecordCommands-EIZTKSWW.js} +41 -41
  10. package/{agentRunCommand-TNLAXLUU.js → agentRunCommand-RB3EIT4I.js} +41 -41
  11. package/{agentRunControl-KNNDEEDI.js → agentRunControl-5ABAIBQT.js} +2 -2
  12. package/{agentRuntimeLocal-EOW6FFXL.js → agentRuntimeLocal-IO3GGTCJ.js} +7 -7
  13. package/{agentSlice-PVFGBJXB.js → agentSlice-TQVS23WV.js} +6 -6
  14. package/{appDeleteCommands-3VCRRWUX.js → appDeleteCommands-ZQ4ZEKTC.js} +13 -12
  15. package/{appDeployCommands-XN6IEMYK.js → appDeployCommands-4XT7PFW5.js} +13 -12
  16. package/{appDeployStatusCommands-ZSJJXMVR.js → appDeployStatusCommands-5RVMRYQW.js} +13 -12
  17. package/{appGetCommands-DJ7YQCEE.js → appGetCommands-VH5W3RFK.js} +13 -12
  18. package/{appListCommands-4KU5CV5H.js → appListCommands-TAHZLAL3.js} +13 -12
  19. package/{authCommand-5DC3ES4Q.js → authCommand-HBO5G6RL.js} +3 -3
  20. package/{authCommands-BLXNAUF4.js → authCommands-T5FODCEG.js} +2 -2
  21. package/{builtinSkillRegistry-PQWEXSFW.js → builtinSkillRegistry-66PEOD4Y.js} +1 -1
  22. package/{chunk-25GCVHBZ.js → chunk-25BDZGD7.js} +1 -1
  23. package/{chunk-2HF6DINU.js → chunk-2BJ53346.js} +6 -6
  24. package/{chunk-VZWYP7LD.js → chunk-2RCMFPUZ.js} +2 -2
  25. package/{chunk-OQOXDQLB.js → chunk-2VYX3ZCR.js} +3 -3
  26. package/{chunk-UDQZ5JT7.js → chunk-3SEBCWLD.js} +17394 -17306
  27. package/{chunk-NWZRCUHM.js → chunk-4AFKLWZP.js} +101 -192
  28. package/{chunk-GUFTHWDO.js → chunk-4BQ5QKIG.js} +9 -9
  29. package/{chunk-YWLMUFZ5.js → chunk-4GWNEPY6.js} +1 -1
  30. package/{chunk-GJ4UTSAW.js → chunk-53UOBNTI.js} +4 -4
  31. package/{chunk-5QEOTC35.js → chunk-6AJIU6OC.js} +1 -1
  32. package/{chunk-NRWZHHOB.js → chunk-7STRX24O.js} +4 -4
  33. package/chunk-AIHNB5QH.js +1394 -0
  34. package/{chunk-BVCCRSGK.js → chunk-ANQ544EU.js} +5 -5
  35. package/{chunk-UTFTXJU3.js → chunk-CF7U32BX.js} +3 -3
  36. package/{chunk-MOAVLCCM.js → chunk-CMYZT2XN.js} +3 -3
  37. package/{chunk-U3ZK2MXG.js → chunk-CUQNRU4X.js} +3 -3
  38. package/{chunk-EQJK6LSN.js → chunk-D4CUS6NT.js} +3 -3
  39. package/{chunk-SBBSUBY3.js → chunk-DNY33GGQ.js} +1 -1
  40. package/{chunk-J4KLOLYP.js → chunk-FZSGYLFV.js} +3 -3
  41. package/{chunk-N2ZAY2DK.js → chunk-GFXPPQZN.js} +1 -1
  42. package/{chunk-BTQU2PRC.js → chunk-GK772DEV.js} +1 -1
  43. package/{chunk-N7UXTVAR.js → chunk-HEQJ5XND.js} +1 -1
  44. package/{chunk-BLBGVSLB.js → chunk-HEUHCHAR.js} +5 -5
  45. package/{chunk-EFM2IPZR.js → chunk-HQUGB2HM.js} +1 -1
  46. package/{chunk-WNIBQBOR.js → chunk-HS4JGZQH.js} +1 -1
  47. package/{chunk-NMXGIRSG.js → chunk-HSBHS6KT.js} +1 -1
  48. package/{chunk-N2MDL5AZ.js → chunk-IRORRPH2.js} +9 -9
  49. package/{chunk-7RYODZDD.js → chunk-J55F3IEZ.js} +1 -1
  50. package/chunk-JJABK3QO.js +321 -0
  51. package/{chunk-64ACTEAE.js → chunk-JKO32CCL.js} +1 -1
  52. package/{chunk-LUPZLKXL.js → chunk-JLZJL3WC.js} +31 -3
  53. package/{chunk-ZMXO5G3E.js → chunk-K4LLTJUO.js} +4 -2
  54. package/{chunk-MDWHMQON.js → chunk-M7GMJBQJ.js} +1 -1
  55. package/{chunk-FJPVVLP3.js → chunk-MARF3TN2.js} +4 -4
  56. package/{chunk-KO6JNZCF.js → chunk-MPOUZIF4.js} +21 -8
  57. package/{chunk-WJOC3AEM.js → chunk-MRYKRL2V.js} +1 -1
  58. package/{chunk-Z47UZT27.js → chunk-NMGG3NUB.js} +1 -1
  59. package/{chunk-EPBEZKYK.js → chunk-O3WZMJAN.js} +2 -2
  60. package/{chunk-3LL5HRIJ.js → chunk-OLS2J3WE.js} +1 -1
  61. package/{chunk-HZD5HXUO.js → chunk-OQFOE4SJ.js} +1 -1
  62. package/{chunk-VH7AQEEF.js → chunk-OWXOXKH7.js} +2 -2
  63. package/{chunk-7XO73H5X.js → chunk-P4JX7YMQ.js} +1 -1
  64. package/{chunk-Q5M27DUE.js → chunk-PR25J652.js} +1 -1
  65. package/{chunk-JX2IG37T.js → chunk-PTY2VZM5.js} +1 -1
  66. package/{chunk-OTNPEE4G.js → chunk-SID2TFMV.js} +87 -63
  67. package/{chunk-26KL6533.js → chunk-TI2JIXK4.js} +18 -18
  68. package/{chunk-NJDOID7N.js → chunk-TOHMK27J.js} +24 -26
  69. package/{chunk-F6GZFIGR.js → chunk-UHTT23PH.js} +14 -14
  70. package/{chunk-IQXMWBI6.js → chunk-UMI4NNZP.js} +2 -2
  71. package/{chunk-CSTCYYCR.js → chunk-VKAITWPC.js} +9 -9
  72. package/{chunk-UGHNYYOE.js → chunk-VPSPVLCM.js} +2 -2
  73. package/{chunk-OTOPQXP5.js → chunk-XWR2YD4L.js} +1 -1
  74. package/{chunk-K7RWY7JH.js → chunk-YQYSQUP3.js} +7 -7
  75. package/{chunk-ZMWDHPNG.js → chunk-Z2ZCKNKX.js} +1 -5
  76. package/{chunk-SSZHE2RK.js → chunk-ZYPXOQS2.js} +1 -1
  77. package/{cliAuthorityBrokerProcess-IUCB4XA6.js → cliAuthorityBrokerProcess-5ZFBTHLB.js} +1 -1
  78. package/{cliLocalAgentRecordReader-OHAC4JTY.js → cliLocalAgentRecordReader-2WBUVRVD.js} +9 -9
  79. package/{commandRegistry-YQMAXCLP.js → commandRegistry-JDCGWIWD.js} +61 -132
  80. package/{contentThunks-GSMUNWBA.js → contentThunks-B6BY7GS3.js} +11 -11
  81. package/{createAgentAutomationAction-RMADR4LG.js → createAgentAutomationAction-TQ6IA5SV.js} +11 -11
  82. package/{createDialogAction-CM5CBQVH.js → createDialogAction-QKMGD2TS.js} +12 -12
  83. package/{createPageAction-JMGVMCTH.js → createPageAction-7EEVGWGG.js} +12 -12
  84. package/{dbSlice-Q637QR4L.js → dbSlice-HXFRXGI3.js} +5 -5
  85. package/{deleteFile-TP6MKFUX.js → deleteFile-QDSZVTUJ.js} +3 -3
  86. package/{dialogCommands-ULWP5ASX.js → dialogCommands-MEH4CVRL.js} +17 -16
  87. package/{dialogSlice-ARQKXXTD.js → dialogSlice-6WIME53P.js} +9 -9
  88. package/{dialogUsageCommand-IHAXS7DW.js → dialogUsageCommand-3JMINURR.js} +1 -1
  89. package/{docCreateCommands-ZJFHCZV4.js → docCreateCommands-MVAYVGQ5.js} +12 -11
  90. package/{docDeleteCommands-LY5MF2BI.js → docDeleteCommands-TKXPRA3O.js} +13 -12
  91. package/{docReadCommands-4X2DHCNZ.js → docReadCommands-MR2YKCZP.js} +12 -11
  92. package/{docStore-QWRVKIRI.js → docStore-VEHQHXRM.js} +6 -6
  93. package/{docUpdateCommands-5TIT7DAJ.js → docUpdateCommands-VJ6A6F7F.js} +12 -11
  94. package/{handleSendMessageAction-TVR55KVT.js → handleSendMessageAction-X5LGNJX5.js} +22 -22
  95. package/{hostCredentialCreate-SIRXPUFR.js → hostCredentialCreate-AQYSWUKA.js} +41 -41
  96. package/index.js +6 -6
  97. package/{localRuntimeAdapter-VRB5EDDZ.js → localRuntimeAdapter-FA4OGZGU.js} +39 -39
  98. package/{localRuntimeAuthority-QKWTPBQQ.js → localRuntimeAuthority-UF2DAQ3F.js} +2 -2
  99. package/{localRuntimeDb-3CIC4SKC.js → localRuntimeDb-ZJFGNHML.js} +1 -1
  100. package/{machineCommands-MG3BB6XM.js → machineCommands-VKU6MAFA.js} +40 -40
  101. package/{machineWsRunDispatch-3TOO3NCU.js → machineWsRunDispatch-XQQHHOX4.js} +40 -40
  102. package/{mcpLocalAuthorizeCommand-LO7E4VQ5.js → mcpLocalAuthorizeCommand-Y3SOZFXT.js} +3 -3
  103. package/{memberThunks-IGYRMEQC.js → memberThunks-ZXEUM6DH.js} +7 -7
  104. package/package.json +1 -1
  105. package/{projectArchive-Q46BYZQ6.js → projectArchive-674NJOYI.js} +12 -12
  106. package/{read-MPPXZHAO.js → read-T5WPCAY7.js} +3 -3
  107. package/{readDocTool-PKZ35PCR.js → readDocTool-DW4DCRQG.js} +1 -1
  108. package/{readlineWorkspace-RBH6PSE7.js → readlineWorkspace-HFPEDOHN.js} +53 -71
  109. package/{removeDialogAgentAction-H6S7VLNA.js → removeDialogAgentAction-MXJEB77K.js} +6 -6
  110. package/{runAgentClientLoop-WZJ4HXOH.js → runAgentClientLoop-NU3JNHSH.js} +27 -27
  111. package/{runtimeDoctorCommands-QGZSKNSE.js → runtimeDoctorCommands-V3M3JTUV.js} +2 -2
  112. package/{setDialogExtraReferencesAction-CARUTAWS.js → setDialogExtraReferencesAction-BILVMHM7.js} +6 -6
  113. package/{setPrimaryDialogAgentAction-VRV56MLG.js → setPrimaryDialogAgentAction-CUBBWACR.js} +6 -6
  114. package/{settingThunks-4FC4HXGN.js → settingThunks-BRBBAGEK.js} +5 -5
  115. package/{spaceCommands-27Z5JAU3.js → spaceCommands-K4HHG7OO.js} +12 -11
  116. package/{streamAgentChatTurn-JKMBFM2O.js → streamAgentChatTurn-7FDXIRMB.js} +35 -35
  117. package/{switchDialogAgentAction-O236K6HB.js → switchDialogAgentAction-SSI2CSNE.js} +5 -5
  118. package/{tools-4RFLNHUW.js → tools-GC45557U.js} +23 -23
  119. package/{tuiRestart-GF4DGAAN.js → tuiRestart-7IKI6JZK.js} +3 -3
  120. package/{updateDialogTitleAction-F3ONQM3N.js → updateDialogTitleAction-OAC5MWMS.js} +11 -11
  121. package/{usageCommand-XVJ7ZUTM.js → usageCommand-HVCMX7BG.js} +2 -2
  122. package/{usageRebuildCommand-NK6S3D4J.js → usageRebuildCommand-VMPIZ2ME.js} +2 -2
  123. package/chunk-CGSIW2KI.js +0 -594
  124. package/chunk-HF4C5WIU.js +0 -980
  125. package/chunk-U5LOKQ2R.js +0 -176
  126. package/{chunk-REINTCQF.js → chunk-4CL6QIQZ.js} +3 -3
  127. package/{chunk-5BRVDQTX.js → chunk-KWARDHBI.js} +7 -7
@@ -0,0 +1,1394 @@
1
+ import {
2
+ resolveObservedSpeed
3
+ } from "./chunk-AMWMV56B.js";
4
+ import {
5
+ fnv1a32Hex
6
+ } from "./chunk-UEILX4EV.js";
7
+ import {
8
+ compareAgentSelection,
9
+ resolveModelTier
10
+ } from "./chunk-K4LLTJUO.js";
11
+ import {
12
+ resolveAgentAvailability
13
+ } from "./chunk-LS5KAVFQ.js";
14
+ import {
15
+ LIST_AGENTS_PAGE_BUDGET,
16
+ sanitizeToolOutputText,
17
+ scrubSecrets
18
+ } from "./chunk-PTY2VZM5.js";
19
+ import {
20
+ isOAuthApiKeyRef
21
+ } from "./chunk-UKZX3NHN.js";
22
+ import {
23
+ createKey,
24
+ createTokenKey
25
+ } from "./chunk-SYTHYBMI.js";
26
+ import {
27
+ isOwnedAgentKey,
28
+ ownedAgentKey,
29
+ publicAgentKey
30
+ } from "./chunk-M2EJHDJP.js";
31
+ import {
32
+ isAntigravityOAuthAgent,
33
+ isSubscriptionEndpoint,
34
+ isSubscriptionOAuthCredential
35
+ } from "./chunk-6SOWMEAY.js";
36
+ import {
37
+ REASONING_EFFORT_OPTIONS,
38
+ resolveModelReasoningCapability
39
+ } from "./chunk-OKH74FML.js";
40
+ import {
41
+ asTrimmedLowercaseString
42
+ } from "./chunk-QSJ3HFEF.js";
43
+
44
+ // packages/core/gptProTier.ts
45
+ var GPT_PRO_REQUIRED_RECHARGE_AMOUNT = 199;
46
+ var SUPPORTED_TIER_PROVIDERS = /* @__PURE__ */ new Set([
47
+ "nolo",
48
+ "openai",
49
+ "deepinfra"
50
+ ]);
51
+ var CLAUDE_PREMIUM_RE = /^(?:anthropic\/)?claude-(opus|fable)(?:-\d+(?:[.-]\d+)*(?:-[a-z0-9]+)*)?$/i;
52
+ var GPT_PRO_RE = /^(?:openai\/)?gpt-[a-z0-9.-]+-pro(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
53
+ var GPT_SOL_RE = /^(?:openai\/)?gpt-\d+(?:\.\d+)*-sol(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
54
+ var GPT_ASTRA_RE = /^(?:openai\/)?gpt-\d+(?:\.\d+)*-astra(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
55
+ var KIMI_K3_MODELS = /* @__PURE__ */ new Set([
56
+ "kimi-k3",
57
+ "moonshotai/kimi-k3",
58
+ // 2026-11-18:K3 由 K3.1 Pro 接替(目录换成 kimi-k3.1-pro),旗舰档门槛保持一致 —
59
+ // 不因换代把 199 档位约束漏掉。
60
+ "kimi-k3.1-pro",
61
+ "moonshotai/kimi-k3.1-pro",
62
+ // 旧 K2.6 经 PLATFORM_MODEL_ALIASES 执行同一 K3.1 Pro 上游与计费:档位判定按
63
+ // 请求 id 直查,不带这一条就会出现「换个旧 id 绕过 premium 门槛」。
64
+ "kimi-k2.6",
65
+ "moonshotai/kimi-k2.6"
66
+ ]);
67
+ function classifyPremiumModel(model) {
68
+ const normalizedModel = asTrimmedLowercaseString(model);
69
+ if (!normalizedModel) return void 0;
70
+ const claudeMatch = CLAUDE_PREMIUM_RE.exec(normalizedModel);
71
+ if (claudeMatch) {
72
+ return claudeMatch[1].toLowerCase() === "opus" ? "claude-opus" : "claude-fable";
73
+ }
74
+ if (GPT_PRO_RE.test(normalizedModel)) {
75
+ return "gpt-pro";
76
+ }
77
+ if (GPT_SOL_RE.test(normalizedModel)) {
78
+ return "gpt-sol";
79
+ }
80
+ if (GPT_ASTRA_RE.test(normalizedModel)) {
81
+ return "gpt-astra";
82
+ }
83
+ if (KIMI_K3_MODELS.has(normalizedModel)) {
84
+ return "kimi-k3";
85
+ }
86
+ return void 0;
87
+ }
88
+ function isGptProModel(provider, model) {
89
+ const normalizedProvider = asTrimmedLowercaseString(provider);
90
+ if (!SUPPORTED_TIER_PROVIDERS.has(normalizedProvider)) {
91
+ return false;
92
+ }
93
+ return classifyPremiumModel(model) !== void 0;
94
+ }
95
+ var GPT_PRO_BLOCKED_MESSAGE = `GPT Pro / Kimi K3.1 Pro \u7B49\u9AD8\u7EA7\u6A21\u578B\u9700\u8981\u5148\u5F00\u901A ${GPT_PRO_REQUIRED_RECHARGE_AMOUNT} \u79EF\u5206\u6863\u4F4D\u3002`;
96
+ function shouldBlockForGptPro(input) {
97
+ if (input?.premium !== true || input?.platformPaid !== true) {
98
+ return { blocked: false };
99
+ }
100
+ if (asTrimmedLowercaseString(input.gptProStatus) === "active") {
101
+ return { blocked: false };
102
+ }
103
+ return { blocked: true, message: GPT_PRO_BLOCKED_MESSAGE };
104
+ }
105
+
106
+ // packages/ai/agent/agentBilling.ts
107
+ function resolveBillingSource(candidate) {
108
+ if (candidate?.local === true || candidate?.isLocal === true || candidate?.cliProvider === "local" || candidate?.apiSource === "local" || candidate?.provider === "local" || candidate?.billingSource === "local") return "local";
109
+ if (candidate?.isOwned !== true) {
110
+ const ownerUserId = typeof candidate?.userId === "string" && candidate.userId.trim() ? candidate.userId.trim() : typeof candidate?.ownerId === "string" && candidate.ownerId.trim() ? candidate.ownerId.trim() : "";
111
+ if (ownerUserId && (candidate?.isOAuth === true || isOAuthApiKeyRef(candidate?.apiKeyRef) || isAntigravityOAuthAgent({
112
+ key: "billing-source-probe",
113
+ apiKeyRef: candidate?.apiKeyRef ?? void 0,
114
+ provider: candidate?.provider ?? void 0,
115
+ customProviderUrl: candidate?.customProviderUrl ?? void 0
116
+ }))) {
117
+ return "owner_subscription";
118
+ }
119
+ return "platform_credits";
120
+ }
121
+ if (candidate?.isOAuth === true || candidate?.billingSource === "user_subscription" || candidate?.apiSource === "oauth" || isOAuthApiKeyRef(candidate?.apiKeyRef)) return "user_subscription";
122
+ if (candidate?.apiSource === "custom" || candidate?.billingSource === "user_api") {
123
+ if (isSubscriptionEndpoint(candidate?.customProviderUrl) || isSubscriptionOAuthCredential(candidate?.apiKeyRef)) {
124
+ return "user_subscription";
125
+ }
126
+ return "user_api";
127
+ }
128
+ return "platform_credits";
129
+ }
130
+
131
+ // packages/ai/economics/economicsPolicy.ts
132
+ var DEEPSEEK_PRICING_DOC = "https://api-docs.deepseek.com/quick_start/pricing";
133
+ var BIGMODEL_CODING_PLAN_USAGE_NOTES = "https://docs.bigmodel.cn/cn/coding-plan/usage-notes";
134
+ var WEEKDAYS_MON_FRI = [1, 2, 3, 4, 5];
135
+ var DEEPSEEK_API_POLICY = {
136
+ id: "deepseek_api",
137
+ version: "2026-09-weekday-utc-peak-2x",
138
+ windows: [
139
+ { timezone: "UTC", weekdays: WEEKDAYS_MON_FRI, startMinute: 60, endMinute: 240 },
140
+ { timezone: "UTC", weekdays: WEEKDAYS_MON_FRI, startMinute: 360, endMinute: 600 }
141
+ ],
142
+ effectiveFrom: Date.UTC(2026, 7, 16, 16, 0, 0),
143
+ peakPriceMultiplier: 2,
144
+ offPeakPriceMultiplier: 1,
145
+ sourceUrl: DEEPSEEK_PRICING_DOC
146
+ };
147
+ var BIGMODEL_GLM_CODING_PLAN_POLICY = {
148
+ id: "bigmodel_glm_coding_plan",
149
+ version: "2026-09-coding-plan-sh-peak-14-18",
150
+ windows: [
151
+ { timezone: "Asia/Shanghai", weekdays: WEEKDAYS_MON_FRI, startMinute: 840, endMinute: 1080 }
152
+ ],
153
+ peakQuotaMultiplier: 1,
154
+ offPeakQuotaMultiplier: 0.5,
155
+ sourceUrl: BIGMODEL_CODING_PLAN_USAGE_NOTES
156
+ };
157
+ var ECONOMICS_POLICIES = [
158
+ DEEPSEEK_API_POLICY,
159
+ BIGMODEL_GLM_CODING_PLAN_POLICY
160
+ ];
161
+ function resolveEconomicsSourceId(input) {
162
+ const provider = typeof input?.provider === "string" ? input.provider.trim().toLowerCase() : "";
163
+ if (input?.apiSource?.trim().toLowerCase() === "platform") return null;
164
+ const rawUrl = typeof input?.customProviderUrl === "string" ? input.customProviderUrl.trim() : "";
165
+ let hostname = "";
166
+ let pathname = "";
167
+ if (rawUrl) {
168
+ try {
169
+ const parsed = new URL(rawUrl);
170
+ hostname = parsed.hostname.toLowerCase();
171
+ pathname = parsed.pathname;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+ if (provider === "deepseek") {
177
+ if (rawUrl && hostname !== "api.deepseek.com") return null;
178
+ return rawUrl ? "deepseek_api" : null;
179
+ }
180
+ if (provider === "bigmodel") {
181
+ if (hostname === "open.bigmodel.cn" && pathname.startsWith("/api/coding/")) {
182
+ return "bigmodel_glm_coding_plan";
183
+ }
184
+ return null;
185
+ }
186
+ return null;
187
+ }
188
+
189
+ // packages/ai/economics/economicsSnapshot.ts
190
+ var wallClockFormatterCache = /* @__PURE__ */ new Map();
191
+ function getWallClockFormatter(timezone) {
192
+ let formatter = wallClockFormatterCache.get(timezone);
193
+ if (!formatter) {
194
+ formatter = new Intl.DateTimeFormat("en-US", {
195
+ timeZone: timezone,
196
+ hourCycle: "h23",
197
+ year: "numeric",
198
+ month: "2-digit",
199
+ day: "2-digit",
200
+ hour: "2-digit",
201
+ minute: "2-digit",
202
+ second: "2-digit"
203
+ });
204
+ wallClockFormatterCache.set(timezone, formatter);
205
+ }
206
+ return formatter;
207
+ }
208
+ function getZonedWallClock(timezone, at) {
209
+ const parts = getWallClockFormatter(timezone).formatToParts(new Date(at));
210
+ const values = {};
211
+ for (const part of parts) {
212
+ if (part.type !== "literal") values[part.type] = Number(part.value);
213
+ }
214
+ const year = values.year;
215
+ const month = values.month;
216
+ const day = values.day;
217
+ const hour = values.hour;
218
+ const minute = values.minute;
219
+ const second = values.second;
220
+ const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
221
+ return { year, month, day, hour, minute, second, weekday, minutesOfDay: hour * 60 + minute };
222
+ }
223
+ function getTimeZoneOffsetMs(timezone, at) {
224
+ const atSecond = Math.floor(at / 1e3) * 1e3;
225
+ const clock = getZonedWallClock(timezone, atSecond);
226
+ return Date.UTC(clock.year, clock.month - 1, clock.day, clock.hour, clock.minute, clock.second) - atSecond;
227
+ }
228
+ function zonedWallClockToEpochMs(timezone, year, month, day, minutesOfDay) {
229
+ const guess = Date.UTC(year, month - 1, day, Math.floor(minutesOfDay / 60), minutesOfDay % 60);
230
+ let instant = guess - getTimeZoneOffsetMs(timezone, guess);
231
+ instant = guess - getTimeZoneOffsetMs(timezone, instant);
232
+ return instant;
233
+ }
234
+ function resolveEconomicsPeriod(policy, at) {
235
+ for (const window of policy.windows) {
236
+ const clock = getZonedWallClock(window.timezone, at);
237
+ if (!window.weekdays.includes(clock.weekday)) continue;
238
+ if (clock.minutesOfDay >= window.startMinute && clock.minutesOfDay < window.endMinute) {
239
+ return "peak";
240
+ }
241
+ }
242
+ return "off_peak";
243
+ }
244
+ function findNextEconomicsBoundary(policy, at) {
245
+ let best;
246
+ for (const window of policy.windows) {
247
+ const anchor = getZonedWallClock(window.timezone, at);
248
+ for (let dayOffset = 0; dayOffset <= 7; dayOffset++) {
249
+ const dayUtc = new Date(Date.UTC(anchor.year, anchor.month - 1, anchor.day + dayOffset));
250
+ const weekday = dayUtc.getUTCDay();
251
+ if (!window.weekdays.includes(weekday)) continue;
252
+ const year = dayUtc.getUTCFullYear();
253
+ const month = dayUtc.getUTCMonth() + 1;
254
+ const day = dayUtc.getUTCDate();
255
+ for (const edge of [window.startMinute, window.endMinute]) {
256
+ const instant = zonedWallClockToEpochMs(window.timezone, year, month, day, edge);
257
+ if (instant > at && (best === void 0 || instant < best)) best = instant;
258
+ }
259
+ }
260
+ }
261
+ return best;
262
+ }
263
+ function selectEconomicsPolicyVersion(policies, sourceId, at) {
264
+ const applicable = policies.filter(
265
+ (policy) => policy.id === sourceId && (policy.effectiveFrom === void 0 || policy.effectiveFrom <= at) && (policy.effectiveUntil === void 0 || at < policy.effectiveUntil)
266
+ );
267
+ if (applicable.length === 0) return null;
268
+ return applicable.reduce(
269
+ (latest, candidate) => (candidate.effectiveFrom ?? -Infinity) >= (latest.effectiveFrom ?? -Infinity) ? candidate : latest
270
+ );
271
+ }
272
+ function findNextPolicyBoundary(policy, at, policies) {
273
+ const boundaries = [
274
+ policy.effectiveUntil,
275
+ ...policies.filter((candidate) => candidate.id === policy.id).map((candidate) => candidate.effectiveFrom).filter((value) => value !== void 0 && value > at)
276
+ ].filter((value) => value !== void 0 && value > at);
277
+ return boundaries.length > 0 ? Math.min(...boundaries) : void 0;
278
+ }
279
+ function resolveEconomicsSnapshot(input, at, policies = ECONOMICS_POLICIES) {
280
+ const sourceId = resolveEconomicsSourceId(input);
281
+ if (!sourceId) return null;
282
+ const policy = selectEconomicsPolicyVersion(policies, sourceId, at);
283
+ if (!policy) return null;
284
+ const period = resolveEconomicsPeriod(policy, at);
285
+ const priceMultiplier = period === "peak" ? policy.peakPriceMultiplier : policy.offPeakPriceMultiplier;
286
+ const quotaMultiplier = period === "peak" ? policy.peakQuotaMultiplier : policy.offPeakQuotaMultiplier;
287
+ const windowBoundary = findNextEconomicsBoundary(policy, at);
288
+ const policyBoundary = findNextPolicyBoundary(policy, at, policies);
289
+ const changesAt = [windowBoundary, policyBoundary].filter((value) => value !== void 0).sort((a, b) => a - b)[0];
290
+ return {
291
+ source: sourceId,
292
+ policyVersion: policy.version,
293
+ period,
294
+ ...priceMultiplier !== void 0 ? { priceMultiplier } : {},
295
+ ...quotaMultiplier !== void 0 ? { quotaMultiplier } : {},
296
+ ...changesAt !== void 0 ? { changesAt } : {}
297
+ };
298
+ }
299
+
300
+ // packages/ai/agent/safeAgentSummary.ts
301
+ function deriveCredentialGroup(ref) {
302
+ if (!ref || typeof ref !== "string") return void 0;
303
+ const trimmed = ref.trim();
304
+ if (!trimmed) return void 0;
305
+ if (isOAuthApiKeyRef(trimmed)) {
306
+ return {
307
+ credentialGroup: trimmed.toLowerCase(),
308
+ credentialKind: "oauth"
309
+ };
310
+ }
311
+ const hash = fnv1a32Hex(trimmed);
312
+ return {
313
+ credentialGroup: `cred-${hash}`,
314
+ credentialKind: "api-key"
315
+ };
316
+ }
317
+ function deriveCustomProviderCredentialGroup(userId, customProviderUrl) {
318
+ if (typeof customProviderUrl !== "string" || !customProviderUrl.trim()) {
319
+ return void 0;
320
+ }
321
+ const basis = `${userId ?? ""}|${customProviderUrl.trim().toLowerCase()}`;
322
+ return {
323
+ credentialGroup: `custom-${fnv1a32Hex(basis)}`,
324
+ credentialKind: "api-key"
325
+ };
326
+ }
327
+ function summarizeCredentialGroups(agents, now = Date.now()) {
328
+ const groups = /* @__PURE__ */ new Map();
329
+ for (const agent of agents) {
330
+ if (!agent.credentialGroup || !agent.credentialKind) continue;
331
+ if (agent.isOwned === false) continue;
332
+ const existing = groups.get(agent.credentialGroup);
333
+ const at = typeof agent.nextAvailableAt === "number" && agent.nextAvailableAt > now ? agent.nextAvailableAt : void 0;
334
+ if (!existing) {
335
+ groups.set(agent.credentialGroup, {
336
+ credentialGroup: agent.credentialGroup,
337
+ credentialKind: agent.credentialKind,
338
+ agentCount: 1,
339
+ ...at !== void 0 ? { availableAt: at } : {}
340
+ });
341
+ } else {
342
+ existing.agentCount += 1;
343
+ if (at !== void 0) {
344
+ existing.availableAt = Math.max(existing.availableAt ?? 0, at);
345
+ }
346
+ }
347
+ }
348
+ return Array.from(groups.values()).sort(
349
+ (a, b) => a.credentialGroup.localeCompare(b.credentialGroup)
350
+ );
351
+ }
352
+ function parseTimestamp(val) {
353
+ if (typeof val === "number" && Number.isFinite(val)) return val;
354
+ if (typeof val === "string") return Date.parse(val) || 0;
355
+ return 0;
356
+ }
357
+ function safeTimestamp(val) {
358
+ if (typeof val === "number" && Number.isFinite(val)) return val;
359
+ if (typeof val === "string") return val;
360
+ return null;
361
+ }
362
+ function parseAgentRecordId(privateKey, explicitId) {
363
+ if (explicitId && typeof explicitId === "string" && explicitId.trim()) {
364
+ return explicitId.trim();
365
+ }
366
+ if (privateKey && typeof privateKey === "string") {
367
+ const match = privateKey.match(/^agent-[^-]+-(.+)$/i);
368
+ if (match?.[1]) return match[1];
369
+ }
370
+ return null;
371
+ }
372
+ function resolveFavoriteStatus(record, options) {
373
+ if (options?.isFavorite !== void 0) {
374
+ return {
375
+ isFavorite: !!options.isFavorite,
376
+ favoritedAt: safeTimestamp(options.favoritedAt)
377
+ };
378
+ }
379
+ if (record?.isFavorite === true) {
380
+ return {
381
+ isFavorite: true,
382
+ favoritedAt: safeTimestamp(record?.favoritedAt)
383
+ };
384
+ }
385
+ const favoritesMap = options?.favoritesMap;
386
+ if (!favoritesMap) {
387
+ return { isFavorite: false, favoritedAt: null };
388
+ }
389
+ const candidateKeys = [];
390
+ if (typeof record?.dbKey === "string" && record.dbKey) candidateKeys.push(record.dbKey);
391
+ if (typeof record?.privateKey === "string" && record.privateKey) candidateKeys.push(record.privateKey);
392
+ if (typeof record?.publicKey === "string" && record.publicKey) candidateKeys.push(record.publicKey);
393
+ if (typeof record?.verifiedAgentKey === "string" && record.verifiedAgentKey) {
394
+ candidateKeys.push(record.verifiedAgentKey);
395
+ }
396
+ if (typeof record?.id === "string" && record.id) {
397
+ candidateKeys.push(record.id);
398
+ candidateKeys.push(publicAgentKey(record.id));
399
+ if (options?.userId) {
400
+ candidateKeys.push(ownedAgentKey(options.userId, record.id));
401
+ }
402
+ }
403
+ let matched = false;
404
+ let highestFavAt = null;
405
+ let highestFavTime = -1;
406
+ for (const key of candidateKeys) {
407
+ const val = favoritesMap instanceof Map ? favoritesMap.get(key) : favoritesMap[key];
408
+ if (val !== void 0 && val !== false && val !== null) {
409
+ const favAt = val === true ? 1 : safeTimestamp(val);
410
+ if (favAt === null) continue;
411
+ matched = true;
412
+ const time = parseTimestamp(favAt);
413
+ if (time > highestFavTime) {
414
+ highestFavTime = time;
415
+ highestFavAt = favAt;
416
+ }
417
+ }
418
+ }
419
+ if (matched) {
420
+ return {
421
+ isFavorite: true,
422
+ favoritedAt: highestFavAt ?? 1
423
+ };
424
+ }
425
+ return { isFavorite: false, favoritedAt: null };
426
+ }
427
+ function isOwnedAgentRecord(record, userId) {
428
+ if (!userId) return false;
429
+ if (typeof record?.userId === "string" && record.userId === userId || typeof record?.ownerId === "string" && record.ownerId === userId) {
430
+ return true;
431
+ }
432
+ return [record?.dbKey, record?.privateKey].some(
433
+ (key) => isOwnedAgentKey(key, userId)
434
+ );
435
+ }
436
+ function subscriptionQuotaChannel(source) {
437
+ if (typeof source !== "string") return void 0;
438
+ const id = source.toLowerCase();
439
+ if (id.includes("fetchavailablemodels:pool:")) return "antigravity";
440
+ const probe = id.match(/(?:^|[^a-z0-9-])(antigravity|codex|anthropic|claude|cursor|devin|xai)-oauth(?=$|[^a-z0-9-])/)?.[1];
441
+ if (probe === "codex") return "chatgpt";
442
+ if (probe === "anthropic") return "claude";
443
+ return probe;
444
+ }
445
+ function toSafeAgentSummary(record, options) {
446
+ const rawId = parseAgentRecordId(
447
+ typeof record?.privateKey === "string" ? record.privateKey : record?.dbKey,
448
+ typeof record?.id === "string" ? record.id : void 0
449
+ );
450
+ const id = rawId ?? (typeof record?.id === "string" ? record.id : null);
451
+ const publicRecordDenied = record?.publicRecordExists === false || options?.publicRecordExists === false;
452
+ const publicRecordConfirmed = record?.publicRecordExists === true || options?.publicRecordExists === true;
453
+ let publicKey;
454
+ if (typeof record?.publicKey === "string" && record.publicKey && !publicRecordDenied) {
455
+ publicKey = record.publicKey;
456
+ } else if (publicRecordConfirmed && id) {
457
+ publicKey = publicAgentKey(id);
458
+ }
459
+ const name = typeof record?.name === "string" && record.name ? record.name : "(unnamed)";
460
+ const handle = typeof record?.handle === "string" && record.handle ? record.handle : null;
461
+ const introduction = typeof record?.introduction === "string" && record.introduction ? record.introduction : typeof record?.description === "string" && record.description ? record.description : null;
462
+ const roleText = typeof record?.introduction === "string" ? record.introduction.trim().replace(/\s+/g, " ") : "";
463
+ const roleChars = Array.from(roleText);
464
+ const roleHint = roleChars.length > 60 ? `${roleChars.slice(0, 59).join("")}\u2026` : roleText;
465
+ const model = typeof record?.model === "string" && record.model ? record.model : null;
466
+ const provider = typeof record?.provider === "string" && record.provider ? record.provider : typeof record?.apiSource === "string" && record.apiSource ? record.apiSource : null;
467
+ const apiSource = typeof record?.apiSource === "string" && record.apiSource ? record.apiSource : null;
468
+ const cliProvider = typeof record?.cliProvider === "string" && record.cliProvider ? record.cliProvider : null;
469
+ const tools = Array.isArray(record?.tools) ? record.tools.filter((t) => typeof t === "string") : [];
470
+ const inputPrice = typeof record?.inputPrice === "number" && Number.isFinite(record.inputPrice) ? record.inputPrice : null;
471
+ const outputPrice = typeof record?.outputPrice === "number" && Number.isFinite(record.outputPrice) ? record.outputPrice : null;
472
+ const favStatus = resolveFavoriteStatus(record, options);
473
+ const isPublic = record?.isPublic === true || record?.isPublicFlag === true || record?.publicRecordExists === true;
474
+ const updatedAt = safeTimestamp(record?.updatedAt ?? record?.createdAt ?? record?.created);
475
+ const nextAvailableAt = typeof record?.nextAvailableAt === "number" && Number.isFinite(record.nextAvailableAt) ? record.nextAvailableAt : void 0;
476
+ const currentUserId = options?.userId;
477
+ const ownedKey = currentUserId ? [record?.dbKey, record?.privateKey].find(
478
+ (key) => isOwnedAgentKey(key, currentUserId)
479
+ ) : void 0;
480
+ const isOwned = isOwnedAgentRecord(record, currentUserId);
481
+ const isOAuth = isOAuthApiKeyRef(record?.apiKeyRef);
482
+ const billingSource = resolveBillingSource({
483
+ ...record,
484
+ isOAuth,
485
+ isOwned,
486
+ apiSource,
487
+ cliProvider,
488
+ provider,
489
+ isPublic
490
+ });
491
+ const economics = resolveEconomicsSnapshot(
492
+ {
493
+ provider,
494
+ apiSource,
495
+ customProviderUrl: typeof record?.customProviderUrl === "string" ? record.customProviderUrl : null
496
+ },
497
+ options?.now ?? Date.now()
498
+ );
499
+ const verifiedSharedKey = typeof record?.verifiedAgentKey === "string" && record.verifiedAgentKey ? record.verifiedAgentKey : void 0;
500
+ let agentKey;
501
+ if (currentUserId) {
502
+ if (isOwned) {
503
+ agentKey = ownedKey ?? (id ? ownedAgentKey(currentUserId, id) : void 0);
504
+ } else if (publicKey) {
505
+ agentKey = publicKey;
506
+ } else {
507
+ agentKey = verifiedSharedKey;
508
+ }
509
+ }
510
+ const rawCredRef = (typeof record?.apiKeyRef === "string" && record.apiKeyRef ? record.apiKeyRef : void 0) ?? (typeof record?.credentialRef === "string" && record.credentialRef ? record.credentialRef : void 0);
511
+ const credInfo = deriveCredentialGroup(record?.credentialGroup ?? rawCredRef);
512
+ const credentialGroup = record?.credentialGroup ?? credInfo?.credentialGroup;
513
+ const credentialKind = record?.credentialKind ?? credInfo?.credentialKind;
514
+ const rawQuota = record?.quota;
515
+ const snapshot = rawQuota && Array.isArray(rawQuota.windows) && Number.isFinite(rawQuota.observedAt) ? rawQuota : void 0;
516
+ const ref = typeof rawCredRef === "string" ? rawCredRef.trim().toLowerCase() : void 0;
517
+ const group = typeof credentialGroup === "string" ? credentialGroup.trim().toLowerCase() : void 0;
518
+ const oauthChannel = isOAuthApiKeyRef(ref) ? ref : isOAuthApiKeyRef(group) ? group : void 0;
519
+ const providerId = provider?.trim().toLowerCase();
520
+ const channel = oauthChannel ?? (providerId === "google-antigravity" ? "antigravity" : providerId);
521
+ const platformChannel = apiSource === "platform" || providerId === "nolo" && !oauthChannel && apiSource !== "custom";
522
+ const windows = snapshot?.windows.filter((window) => {
523
+ const origin = subscriptionQuotaChannel(window?.source);
524
+ return !origin || !platformChannel && (!channel || origin === channel);
525
+ });
526
+ const foreignOnly = Boolean(snapshot?.windows.length && windows?.length === 0);
527
+ const quota = snapshot && windows && !foreignOnly ? { ...snapshot, windows } : void 0;
528
+ const observedAt = record?.quotaExhaustion?.observedAt;
529
+ const quotaExhaustion = !foreignOnly && typeof observedAt === "number" && Number.isFinite(observedAt) ? { observedAt } : void 0;
530
+ const availability = resolveAgentAvailability(
531
+ { nextAvailableAt, quota, quotaExhaustion, model },
532
+ options?.now ?? Date.now()
533
+ );
534
+ return {
535
+ id,
536
+ ...agentKey !== void 0 ? { agentKey } : {},
537
+ ...publicKey !== void 0 ? { publicKey } : {},
538
+ name,
539
+ handle,
540
+ introduction,
541
+ ...roleHint ? { roleHint } : {},
542
+ model,
543
+ modelTier: resolveModelTier(model),
544
+ provider,
545
+ apiSource,
546
+ cliProvider,
547
+ billingSource,
548
+ tools,
549
+ inputPrice,
550
+ outputPrice,
551
+ isFavorite: favStatus.isFavorite,
552
+ favoritedAt: favStatus.favoritedAt,
553
+ isPublic,
554
+ // 复用 platformPaidCall.ts 的唯一判据(该文件头明确它是「谁出钱」的真源):
555
+ // 自己写 billingSource === "platform_credits" 会与 199 门槛口径分叉——
556
+ // 例如 apiSource==="cli" 的本地 CLI Agent 在 resolveBillingSource 里会落到
557
+ // platform_credits,但 isPlatformPaidAgentCall 显式短路为「非平台垫付」。
558
+ requiresPaidApproval: isPlatformPaidAgentCall({
559
+ agentConfig: record ?? void 0,
560
+ callerUserId: currentUserId ?? void 0
561
+ }),
562
+ ...economics ? { economics } : {},
563
+ isOwned,
564
+ isOAuth,
565
+ ...nextAvailableAt !== void 0 ? { nextAvailableAt } : {},
566
+ availabilityStatus: availability.status,
567
+ availabilityReason: availability.reason,
568
+ ...quota !== void 0 ? { quota } : {},
569
+ ...quotaExhaustion ? { quotaExhaustion } : {},
570
+ ...credentialGroup !== void 0 ? { credentialGroup } : {},
571
+ ...credentialKind !== void 0 ? { credentialKind } : {},
572
+ // 「未知 ≠ 独立」:无 credentialGroup 时显式 credentialed:false,调用方
573
+ // 不得把缺失解读成独立凭证(并发扇出守卫依赖这个区分)。
574
+ credentialed: credentialGroup !== void 0,
575
+ updatedAt
576
+ };
577
+ }
578
+ function sortSafeAgentSummaries(agents) {
579
+ return [...agents].sort(compareAgentSelection);
580
+ }
581
+ var AGENT_SUMMARY_FIELDS = [
582
+ // —— 派发决策必需(短字段,必须排最前)——
583
+ // agentKey 是唯一不可推导、必须逐字复制的字段;截断时它首先被保住。
584
+ "agentKey",
585
+ "name",
586
+ "model",
587
+ "modelTier",
588
+ "billingSource",
589
+ // 扣费授权判据:listAgents 默认走 compact 投影,缺了它模型在默认派发
590
+ // 流程里读不到「派它之前要先问用户」(2026-11-15 事故成因)。
591
+ "requiresPaidApproval",
592
+ "availabilityStatus",
593
+ "credentialGroup",
594
+ "isFavorite",
595
+ "isOAuth",
596
+ "isOwned",
597
+ "isPublic",
598
+ // —— 次要身份/来源字段(仍很短)——
599
+ "provider",
600
+ "apiSource",
601
+ "credentialKind",
602
+ "credentialed",
603
+ // 仅限流中的 agent 才会带(可用 agent 上不存在)。额度/冷却只作参考信息,
604
+ // 不参与派发门控:这类 agent 同样在 agents 主列表里(带标注),不做过滤,
605
+ // 所以这两个字段只在确实限流时才占字节。
606
+ "nextAvailableAt",
607
+ "availabilityReason",
608
+ // —— 体积大的说明性字段(排在每条记录最后,截断时先牺牲它们)——
609
+ // Phase 2A economics 快照(period/multipliers/changesAt 等小对象)。
610
+ // 只对 DeepSeek API / BigModel GLM Coding Plan 存在;不含完整 policy/windows。
611
+ "economics"
612
+ ];
613
+ var AGENT_SUMMARY_TRAILING_FIELDS = [
614
+ "tools",
615
+ // 额度快照(windows 数组,体积最大):只有上游真上报过窗口的 agent 才带。
616
+ "quota"
617
+ ];
618
+ var COMPACT_AGENT_SUMMARY_FIELDS = [
619
+ ...AGENT_SUMMARY_FIELDS,
620
+ "roleHint",
621
+ ...AGENT_SUMMARY_TRAILING_FIELDS
622
+ ];
623
+ function omitNullishAgentSummaryFields(summary) {
624
+ const result = {};
625
+ for (const [key, value] of Object.entries(summary)) {
626
+ if (value !== null && value !== void 0) {
627
+ result[key] = value;
628
+ }
629
+ }
630
+ return result;
631
+ }
632
+ function finiteOptionalNumber(value) {
633
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
634
+ }
635
+ function compactQuotaForSummary(quota) {
636
+ if (!quota || !Array.isArray(quota.windows)) return void 0;
637
+ const observedAt = finiteOptionalNumber(quota.observedAt);
638
+ if (observedAt === void 0) return void 0;
639
+ const windows = [];
640
+ for (const window of quota.windows) {
641
+ if (!window || typeof window.scope !== "string" || !window.scope) continue;
642
+ const utilization = finiteOptionalNumber(window.utilization);
643
+ const remaining = finiteOptionalNumber(window.remaining);
644
+ const limit = finiteOptionalNumber(window.limit);
645
+ const resetAt = finiteOptionalNumber(window.resetAt);
646
+ const unit = typeof window.unit === "string" && window.unit ? window.unit : void 0;
647
+ windows.push({
648
+ scope: window.scope,
649
+ ...utilization !== void 0 ? { utilization } : {},
650
+ ...remaining !== void 0 ? { remaining } : {},
651
+ ...limit !== void 0 ? { limit } : {},
652
+ ...unit !== void 0 ? { unit } : {},
653
+ ...resetAt !== void 0 ? { resetAt } : {}
654
+ });
655
+ }
656
+ const rawPlan = quota.plan;
657
+ const planName = rawPlan && typeof rawPlan.name === "string" && rawPlan.name ? rawPlan.name : void 0;
658
+ const monthlyCreditsUsd = finiteOptionalNumber(rawPlan?.monthlyCreditsUsd);
659
+ const plan = planName ? { name: planName, ...monthlyCreditsUsd !== void 0 ? { monthlyCreditsUsd } : {} } : void 0;
660
+ return {
661
+ observedAt,
662
+ windows,
663
+ ...plan ? { plan } : {}
664
+ };
665
+ }
666
+ function promoteSharedCredentialGroupQuota(agents, groups) {
667
+ if (!agents.length || !groups.length) return { agents, groups };
668
+ const groupByName = new Map(groups.map((group) => [group.credentialGroup, group]));
669
+ const restored = agents.map((agent) => {
670
+ const ref = agent.quotaRef;
671
+ if (typeof ref !== "string") return agent;
672
+ const fromGroup = groupByName.get(ref)?.quota;
673
+ const rest = { ...agent };
674
+ delete rest.quotaRef;
675
+ if (fromGroup) rest.quota = fromGroup;
676
+ return rest;
677
+ });
678
+ const bareGroups = groups.map(({ quota: _dropped, ...rest }) => rest);
679
+ const slimQuota = restored.map((agent) => compactQuotaForSummary(agent.quota));
680
+ const byGroup = /* @__PURE__ */ new Map();
681
+ slimQuota.forEach((quota, index) => {
682
+ const agent = restored[index];
683
+ const groupKey = agent.credentialGroup;
684
+ if (!quota || quota.windows.length === 0) return;
685
+ if (agent.isOwned !== true) return;
686
+ if (typeof groupKey !== "string" || !groupKey) return;
687
+ if (!groupByName.has(groupKey)) return;
688
+ const clusters = byGroup.get(groupKey) ?? /* @__PURE__ */ new Map();
689
+ const signature = JSON.stringify([
690
+ quota.windows,
691
+ quota.plan ?? null,
692
+ quota.observedAt ?? null
693
+ ]);
694
+ const indices = clusters.get(signature) ?? [];
695
+ indices.push(index);
696
+ clusters.set(signature, indices);
697
+ byGroup.set(groupKey, clusters);
698
+ });
699
+ const promoted = /* @__PURE__ */ new Map();
700
+ const refFor = /* @__PURE__ */ new Map();
701
+ for (const [groupKey, clusters] of byGroup) {
702
+ let best;
703
+ for (const indices of clusters.values()) {
704
+ if (indices.length < 2) continue;
705
+ if (!best || indices.length > best.length) best = indices;
706
+ }
707
+ if (!best) continue;
708
+ const observedAt = slimQuota[best[0]].observedAt;
709
+ const { plan } = slimQuota[best[0]];
710
+ promoted.set(groupKey, {
711
+ observedAt,
712
+ windows: slimQuota[best[0]].windows,
713
+ ...plan ? { plan } : {}
714
+ });
715
+ for (const index of best) refFor.set(index, groupKey);
716
+ }
717
+ const nextAgents = restored.map((agent, index) => {
718
+ const ref = refFor.get(index);
719
+ if (!ref) return agent;
720
+ const rest = { ...agent };
721
+ delete rest.quota;
722
+ rest.quotaRef = ref;
723
+ return rest;
724
+ });
725
+ const nextGroups = bareGroups.map((group) => {
726
+ const quota = promoted.get(group.credentialGroup);
727
+ return quota ? { ...group, quota } : group;
728
+ });
729
+ return { agents: nextAgents, groups: nextGroups };
730
+ }
731
+ function toCompactAgentSummary(summary) {
732
+ const compact = {};
733
+ for (const field of COMPACT_AGENT_SUMMARY_FIELDS) {
734
+ const value = summary[field];
735
+ if (value !== null && value !== void 0) {
736
+ compact[field] = value;
737
+ }
738
+ }
739
+ return compact;
740
+ }
741
+ var ULTRA_COMPACT_AGENT_SUMMARY_FIELDS = [
742
+ ...AGENT_SUMMARY_FIELDS,
743
+ ...AGENT_SUMMARY_TRAILING_FIELDS
744
+ ];
745
+ function toUltraCompactAgentSummary(summary) {
746
+ const compact = {};
747
+ for (const field of ULTRA_COMPACT_AGENT_SUMMARY_FIELDS) {
748
+ const value = summary[field];
749
+ if (value !== null && value !== void 0) {
750
+ compact[field] = value;
751
+ }
752
+ }
753
+ if (compact.quota !== void 0) {
754
+ const quota = compactQuotaForSummary(compact.quota);
755
+ if (quota) {
756
+ compact.quota = quota;
757
+ } else {
758
+ delete compact.quota;
759
+ }
760
+ }
761
+ return compact;
762
+ }
763
+
764
+ // packages/ai/agent/platformPaidCall.ts
765
+ var asTrimmed = (value) => typeof value === "string" ? value.trim() : "";
766
+ var hasOAuthCredentialShape = (agentConfig) => isOAuthApiKeyRef(agentConfig?.apiKeyRef) || isAntigravityOAuthAgent({
767
+ key: "platform-paid-call-probe",
768
+ apiKeyRef: agentConfig?.apiKeyRef ?? void 0,
769
+ provider: agentConfig?.provider ?? void 0,
770
+ customProviderUrl: agentConfig?.customProviderUrl ?? void 0
771
+ });
772
+ function isPlatformPaidAgentCall(probe) {
773
+ const agentConfig = probe?.agentConfig ?? {};
774
+ const authKind = asTrimmed(probe?.authKind);
775
+ if (authKind) return authKind === "platform-key";
776
+ if (asTrimmed(agentConfig.apiSource) === "cli") return false;
777
+ return resolveBillingSource({
778
+ local: agentConfig.local,
779
+ isLocal: agentConfig.isLocal,
780
+ cliProvider: agentConfig.cliProvider,
781
+ apiSource: agentConfig.apiSource,
782
+ provider: agentConfig.provider,
783
+ billingSource: agentConfig.billingSource,
784
+ // 形态证明而非记录自声明(见文件头):自声明 isOAuth 不足以证明 OAuth 通道归属。
785
+ isOAuth: hasOAuthCredentialShape(agentConfig),
786
+ apiKeyRef: agentConfig.apiKeyRef,
787
+ customProviderUrl: agentConfig.customProviderUrl,
788
+ isOwned: isOwnedAgentRecord(
789
+ agentConfig,
790
+ asTrimmed(probe?.callerUserId) || void 0
791
+ ),
792
+ userId: agentConfig.userId,
793
+ ownerId: agentConfig.ownerId
794
+ }) === "platform_credits";
795
+ }
796
+
797
+ // packages/ai/agent/speedSampleCache.ts
798
+ var SPEED_SAMPLE_DISK_CACHE_TTL_MS = 10 * 6e4;
799
+ var SPEED_SAMPLE_SCAN_BUDGET_MS = 2500;
800
+ var SPEED_SAMPLE_CACHE_VERSION = 4;
801
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
802
+ var sanitizeSample = (value) => {
803
+ if (!value || typeof value !== "object") return null;
804
+ const sample = value;
805
+ const clean = {};
806
+ if (isFiniteNumber(sample.firstOutputMs)) clean.firstOutputMs = sample.firstOutputMs;
807
+ if (isFiniteNumber(sample.callDurationMs)) clean.callDurationMs = sample.callDurationMs;
808
+ if (isFiniteNumber(sample.output_tokens)) clean.output_tokens = sample.output_tokens;
809
+ if (isFiniteNumber(sample.t)) clean.t = sample.t;
810
+ return clean.firstOutputMs === void 0 && clean.callDurationMs === void 0 ? null : clean;
811
+ };
812
+ var SPEED_SAMPLE_STALE_SNAPSHOT_MAX_MS = 7 * 24 * 60 * 6e4;
813
+ async function parseCacheFile(cachePath, userId) {
814
+ try {
815
+ const fs = await import("node:fs/promises");
816
+ const raw = await fs.readFile(cachePath, "utf8");
817
+ const parsed = JSON.parse(raw);
818
+ if (!parsed || typeof parsed !== "object") return null;
819
+ const version = parsed.version;
820
+ if (version !== SPEED_SAMPLE_CACHE_VERSION) {
821
+ return null;
822
+ }
823
+ if (parsed.userId !== userId) return null;
824
+ if (!isFiniteNumber(parsed.at)) return null;
825
+ const source = parsed.samples;
826
+ if (!source || typeof source !== "object") return null;
827
+ const samples = /* @__PURE__ */ new Map();
828
+ for (const [model, list] of Object.entries(source)) {
829
+ if (!model || !Array.isArray(list)) continue;
830
+ const cleaned = [];
831
+ for (const entry of list) {
832
+ const sample = sanitizeSample(entry);
833
+ if (sample) cleaned.push(sample);
834
+ }
835
+ samples.set(model, cleaned);
836
+ }
837
+ const complete = parsed.complete === true;
838
+ const cursor = typeof parsed.cursor === "string" && parsed.cursor.length > 0 ? parsed.cursor : void 0;
839
+ return { samples, at: parsed.at, complete, cursor: complete ? void 0 : cursor };
840
+ } catch {
841
+ return null;
842
+ }
843
+ }
844
+ async function readSpeedSamplesSnapshot(cachePath, options) {
845
+ const maxAgeMs = isFiniteNumber(options.maxAgeMs) ? options.maxAgeMs : SPEED_SAMPLE_STALE_SNAPSHOT_MAX_MS;
846
+ const parsed = await parseCacheFile(cachePath, options.userId);
847
+ if (!parsed || !parsed.complete) return null;
848
+ const age = options.now - parsed.at;
849
+ if (age < 0 || age >= maxAgeMs) return null;
850
+ return { samples: parsed.samples, ageMs: age };
851
+ }
852
+ async function readSpeedSamplesProgress(cachePath, userId) {
853
+ const parsed = await parseCacheFile(cachePath, userId);
854
+ if (!parsed) return null;
855
+ return {
856
+ samples: parsed.samples,
857
+ at: parsed.at,
858
+ complete: parsed.complete,
859
+ ...parsed.cursor === void 0 ? {} : { cursor: parsed.cursor }
860
+ };
861
+ }
862
+ function resolveSpeedSamplesProgressPath(cachePath) {
863
+ return `${cachePath}.progress`;
864
+ }
865
+ async function writeSpeedSamplesCache(cachePath, payload) {
866
+ try {
867
+ const fs = await import("node:fs/promises");
868
+ const path = await import("node:path");
869
+ await fs.mkdir(path.dirname(cachePath), { recursive: true });
870
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
871
+ await fs.writeFile(tmpPath, JSON.stringify(payload), "utf8");
872
+ await fs.rename(tmpPath, cachePath);
873
+ } catch {
874
+ }
875
+ }
876
+
877
+ // packages/ai/agent/candidateSpeedContext.ts
878
+ var OBSERVED_SPEED_WINDOW = 50;
879
+ var MIN_OBSERVED_FIRST_OUTPUT_SAMPLES = 5;
880
+ var SPEED_SAMPLES_CACHE_TTL_MS = 5 * 6e4;
881
+ var SPEED_SAMPLES_CACHE_MAX_ENTRIES = 500;
882
+ function normalizeSpeedModelName(raw) {
883
+ const name = raw.trim().toLowerCase();
884
+ const slash = name.lastIndexOf("/");
885
+ return slash === -1 ? name : name.slice(slash + 1);
886
+ }
887
+ var isFiniteNumber2 = (value) => typeof value === "number" && Number.isFinite(value);
888
+ var REASONING_EFFORT_SUFFIXES = ["minimal", "low", "medium", "high", "xhigh"];
889
+ var REASONING_EFFORT_SUFFIX_RE = new RegExp(`-(?:${REASONING_EFFORT_SUFFIXES.join("|")})$`);
890
+ function stripReasoningEffortSuffix(model) {
891
+ const base = model.replace(REASONING_EFFORT_SUFFIX_RE, "");
892
+ return base && base !== model ? base : null;
893
+ }
894
+ function resolveOneBare(model, samplesByModel) {
895
+ const observed = resolveObservedSpeed(samplesByModel.get(model) ?? [], {
896
+ limit: OBSERVED_SPEED_WINDOW
897
+ });
898
+ if (observed.firstOutputSampleCount >= MIN_OBSERVED_FIRST_OUTPUT_SAMPLES && observed.medianFirstOutputMs !== void 0) {
899
+ return {
900
+ source: "observed",
901
+ firstOutputMs: observed.medianFirstOutputMs,
902
+ ...observed.medianOutputTokensPerSecond !== void 0 ? { outputTps: observed.medianOutputTokensPerSecond } : {},
903
+ firstOutputSamples: observed.firstOutputSampleCount,
904
+ tpsSamples: observed.throughputSampleCount
905
+ };
906
+ }
907
+ return null;
908
+ }
909
+ function resolveOne(model, samplesByModel) {
910
+ const direct = resolveOneBare(model, samplesByModel);
911
+ if (direct) return { model, ...direct };
912
+ const base = stripReasoningEffortSuffix(model);
913
+ if (!base) return null;
914
+ const stripped = resolveOneBare(base, samplesByModel);
915
+ return stripped ? { model, ...stripped } : null;
916
+ }
917
+ function resolveCandidateSpeedFacts(models, samplesByModel) {
918
+ const unique = [
919
+ ...new Set(
920
+ models.filter((model) => typeof model === "string").map(normalizeSpeedModelName).filter(Boolean)
921
+ )
922
+ ];
923
+ return unique.map((model) => resolveOne(model, samplesByModel)).filter((fact) => fact !== null);
924
+ }
925
+ var formatSeconds = (ms) => `${(ms / 1e3).toFixed(1)}s`;
926
+ var formatTps = (tps) => String(Math.round(tps));
927
+ var SPEED_CONTEXT_HEADER = "speed (observed=\u672C\u7528\u6237\u5B9E\u6D4B\u8C03\u7528\u4E2D\u4F4D\u6570, firstOutput \u542B\u63A8\u7406\u8F93\u51FA; tps=generation\uFF08\u4E0D\u542B\u7AEF\u5230\u7AEF\u53E3\u5F84\uFF09, tps=n/a \u8868\u793A\u65E0\u53EF\u4FE1\u541E\u5410\u6837\u672C\u3002\u672A\u5217\u51FA\u7684 model \u8868\u793A\u6CA1\u6709\u5B9E\u6D4B\u6837\u672C\uFF0C\u4E0D\u4EE3\u8868\u6162):";
928
+ function formatSnapshotAge(ageMs) {
929
+ const minutes = Math.floor(ageMs / 6e4);
930
+ if (minutes < 1) return "<1min";
931
+ if (minutes < 60) return `${minutes}min`;
932
+ const hours = Math.floor(minutes / 60);
933
+ if (hours < 24) return `${hours}h`;
934
+ return `${Math.floor(hours / 24)}d`;
935
+ }
936
+ function formatCandidateSpeedFacts(facts, options = {}) {
937
+ if (facts.length === 0) return null;
938
+ const lines = facts.map((fact) => {
939
+ const tps = fact.outputTps !== void 0 ? formatTps(fact.outputTps) : "n/a";
940
+ return ` ${fact.model}: firstOutput=${formatSeconds(fact.firstOutputMs ?? 0)} tps=${tps} [observed n=${fact.firstOutputSamples ?? 0} tpsN=${fact.tpsSamples ?? 0}]`;
941
+ });
942
+ const age = options.snapshotAgeMs;
943
+ const note = typeof age === "number" && age > 0 ? ` (snapshot=${formatSnapshotAge(age)}\u524D\u91C7\u96C6\u7684\u5B8C\u6574\u7A97\u53E3, \u975E\u672C\u6B21\u5B9E\u65F6\u626B\u63CF)` : "";
944
+ return `${SPEED_CONTEXT_HEADER}${note}
945
+ ${lines.join("\n")}`;
946
+ }
947
+ function buildCandidateSpeedContext(models, samplesByModel, options = {}) {
948
+ return formatCandidateSpeedFacts(resolveCandidateSpeedFacts(models, samplesByModel), options);
949
+ }
950
+ var SPEED_SAMPLE_PAGE_SIZE = 2e3;
951
+ var DISPATCH_ENTRY_PATH = "agent-run";
952
+ var eventTime = (value) => {
953
+ if (isFiniteNumber2(value.timestamp)) return value.timestamp;
954
+ if (isFiniteNumber2(value.createdAt)) return value.createdAt;
955
+ return 0;
956
+ };
957
+ function collectSample(collected, value) {
958
+ if (typeof value.model !== "string") return;
959
+ if (!isFiniteNumber2(value.firstOutputMs) && !isFiniteNumber2(value.callDurationMs)) return;
960
+ const model = normalizeSpeedModelName(value.model);
961
+ if (!model) return;
962
+ const list = collected.get(model) ?? [];
963
+ list.push({
964
+ t: eventTime(value),
965
+ firstOutputMs: value.firstOutputMs,
966
+ callDurationMs: value.callDurationMs,
967
+ output_tokens: value.output_tokens
968
+ });
969
+ collected.set(model, list);
970
+ }
971
+ function finalizeSamples(collected, keepTime = false) {
972
+ const result = /* @__PURE__ */ new Map();
973
+ for (const [model, list] of collected) {
974
+ list.sort((a, b) => b.t - a.t);
975
+ const window = list.slice(0, OBSERVED_SPEED_WINDOW);
976
+ result.set(
977
+ model,
978
+ keepTime ? window : window.map(({ t: _t, ...sample }) => sample)
979
+ );
980
+ }
981
+ return result;
982
+ }
983
+ async function collectRecentSpeedSamples(db, userId, options = {}) {
984
+ const pageSize = isFiniteNumber2(options.pageSize) && options.pageSize > 0 ? Math.floor(options.pageSize) : SPEED_SAMPLE_PAGE_SIZE;
985
+ const budgetMs = isFiniteNumber2(options.budgetMs) ? options.budgetMs : Number.POSITIVE_INFINITY;
986
+ const { start, end } = createTokenKey.rangeOfUser(userId);
987
+ const failedPrefix = createKey("token", userId, "failed-call", "");
988
+ const dispatchRunCache = /* @__PURE__ */ new Map();
989
+ const isDispatchSampleRecord = async (record, resolver, cache) => {
990
+ if (record.entry_path !== DISPATCH_ENTRY_PATH && record.entry_path !== "cli-local") return false;
991
+ const runId = typeof record.dialogId === "string" ? record.dialogId.trim() : "";
992
+ if (!runId) return false;
993
+ const cacheKey = `${record.entry_path}:${runId}`;
994
+ const cached = cache.get(cacheKey);
995
+ if (cached !== void 0) return cached;
996
+ let dispatch = false;
997
+ if (resolver) {
998
+ try {
999
+ dispatch = await resolver(runId, record.entry_path) === true;
1000
+ } catch {
1001
+ dispatch = false;
1002
+ }
1003
+ }
1004
+ cache.set(cacheKey, dispatch);
1005
+ return dispatch;
1006
+ };
1007
+ const collected = /* @__PURE__ */ new Map();
1008
+ const startedAt = Date.now();
1009
+ let lastKey = options.startAfter;
1010
+ let budgetExhausted = false;
1011
+ let scanned = 0;
1012
+ while (true) {
1013
+ if (Date.now() - startedAt >= budgetMs) {
1014
+ budgetExhausted = true;
1015
+ break;
1016
+ }
1017
+ const pageOptions = {
1018
+ ...lastKey === void 0 ? { gte: start } : { gt: lastKey },
1019
+ lte: end,
1020
+ limit: pageSize
1021
+ };
1022
+ let accepted = 0;
1023
+ let newestKey = lastKey;
1024
+ for await (const [key, raw] of db.iterator(pageOptions)) {
1025
+ if (typeof key !== "string") continue;
1026
+ if (lastKey !== void 0 && key <= lastKey) continue;
1027
+ accepted += 1;
1028
+ scanned += 1;
1029
+ newestKey = key;
1030
+ if (key.startsWith(failedPrefix)) continue;
1031
+ if (!raw || typeof raw !== "object") continue;
1032
+ const record = raw;
1033
+ const resolver = options.isDispatchRun ?? db.isDispatchRun;
1034
+ if (!await isDispatchSampleRecord(
1035
+ record,
1036
+ resolver ? (runId, entryPath) => resolver.call(db, runId, entryPath) : void 0,
1037
+ dispatchRunCache
1038
+ ))
1039
+ continue;
1040
+ collectSample(collected, record);
1041
+ }
1042
+ if (accepted === 0 || accepted < pageSize) break;
1043
+ lastKey = newestKey;
1044
+ }
1045
+ return {
1046
+ samples: finalizeSamples(collected, options.keepTime === true),
1047
+ budgetExhausted,
1048
+ scanned,
1049
+ ...budgetExhausted && lastKey !== void 0 ? { nextCursor: lastKey } : {}
1050
+ };
1051
+ }
1052
+ function mergeNewestSamples(into, from) {
1053
+ for (const [model, list] of from) {
1054
+ const merged = [...into.get(model) ?? [], ...list];
1055
+ merged.sort(
1056
+ (a, b) => (b.t ?? 0) - (a.t ?? 0)
1057
+ );
1058
+ into.set(model, merged.slice(0, OBSERVED_SPEED_WINDOW));
1059
+ }
1060
+ }
1061
+ async function loadSpeedSamplesWithDiskCache(db, userId, now, cache) {
1062
+ try {
1063
+ const ttlMs = isFiniteNumber2(cache.ttlMs) ? cache.ttlMs : SPEED_SAMPLE_DISK_CACHE_TTL_MS;
1064
+ const snapshot = await readSpeedSamplesSnapshot(cache.cachePath, { userId, now });
1065
+ if (snapshot && snapshot.ageMs < ttlMs) return { samples: snapshot.samples };
1066
+ const progressPath = resolveSpeedSamplesProgressPath(cache.cachePath);
1067
+ const progress = await readSpeedSamplesProgress(progressPath, userId);
1068
+ const resumable = progress && !progress.complete && progress.cursor ? progress : void 0;
1069
+ const collected = new Map(resumable?.samples ?? []);
1070
+ let step;
1071
+ try {
1072
+ step = await collectRecentSpeedSamples(db, userId, {
1073
+ pageSize: cache.pageSize,
1074
+ budgetMs: isFiniteNumber2(cache.budgetMs) ? cache.budgetMs : SPEED_SAMPLE_SCAN_BUDGET_MS,
1075
+ keepTime: true,
1076
+ ...resumable?.cursor ? { startAfter: resumable.cursor } : {}
1077
+ });
1078
+ } catch {
1079
+ return snapshot ? { samples: snapshot.samples, snapshotAgeMs: snapshot.ageMs } : { samples: /* @__PURE__ */ new Map() };
1080
+ }
1081
+ if (!resumable && step.scanned === 0 && !step.budgetExhausted) {
1082
+ return snapshot ? { samples: snapshot.samples, snapshotAgeMs: snapshot.ageMs } : { samples: /* @__PURE__ */ new Map() };
1083
+ }
1084
+ mergeNewestSamples(collected, step.samples);
1085
+ if (!step.budgetExhausted) {
1086
+ await writeSpeedSamplesCache(cache.cachePath, {
1087
+ version: SPEED_SAMPLE_CACHE_VERSION,
1088
+ userId,
1089
+ at: now,
1090
+ complete: true,
1091
+ samples: Object.fromEntries(collected)
1092
+ });
1093
+ await writeSpeedSamplesCache(progressPath, {
1094
+ version: SPEED_SAMPLE_CACHE_VERSION,
1095
+ userId,
1096
+ at: now,
1097
+ complete: true,
1098
+ samples: {}
1099
+ });
1100
+ return { samples: collected };
1101
+ }
1102
+ await writeSpeedSamplesCache(progressPath, {
1103
+ version: SPEED_SAMPLE_CACHE_VERSION,
1104
+ userId,
1105
+ // Progress keeps the cycle's collection start so a later stale label stays honest.
1106
+ at: resumable?.at ?? now,
1107
+ complete: false,
1108
+ samples: Object.fromEntries(collected),
1109
+ ...step.nextCursor ? { cursor: step.nextCursor } : {}
1110
+ });
1111
+ return snapshot ? { samples: snapshot.samples, snapshotAgeMs: snapshot.ageMs } : { samples: /* @__PURE__ */ new Map() };
1112
+ } catch {
1113
+ return { samples: /* @__PURE__ */ new Map() };
1114
+ }
1115
+ }
1116
+ var samplesCache = /* @__PURE__ */ new Map();
1117
+ function writeSamplesCache(userId, now, samples) {
1118
+ for (const [key, entry] of samplesCache) {
1119
+ if (now - entry.at >= SPEED_SAMPLES_CACHE_TTL_MS) samplesCache.delete(key);
1120
+ }
1121
+ samplesCache.delete(userId);
1122
+ samplesCache.set(userId, { at: now, samples });
1123
+ while (samplesCache.size > SPEED_SAMPLES_CACHE_MAX_ENTRIES) {
1124
+ const oldest = samplesCache.keys().next().value;
1125
+ if (oldest === void 0) break;
1126
+ samplesCache.delete(oldest);
1127
+ }
1128
+ }
1129
+ var SPEED_SAMPLE_REFRESH_BUDGET_MS = 6e4;
1130
+ var snapshotRefreshes = /* @__PURE__ */ new Map();
1131
+ function startSpeedSnapshotRefresh(db, userId, now = Date.now()) {
1132
+ const inFlight = snapshotRefreshes.get(userId);
1133
+ if (inFlight) return inFlight;
1134
+ const job = (async () => {
1135
+ try {
1136
+ const { samples, budgetExhausted } = await collectRecentSpeedSamples(db, userId, {
1137
+ budgetMs: SPEED_SAMPLE_REFRESH_BUDGET_MS
1138
+ });
1139
+ if (!budgetExhausted) writeSamplesCache(userId, now, samples);
1140
+ } catch {
1141
+ }
1142
+ })().finally(() => {
1143
+ snapshotRefreshes.delete(userId);
1144
+ });
1145
+ snapshotRefreshes.set(userId, job);
1146
+ return job;
1147
+ }
1148
+ async function loadCachedSpeedSamples(db, userId, now) {
1149
+ const hit = samplesCache.get(userId);
1150
+ if (hit) {
1151
+ const age = now - hit.at;
1152
+ if (age >= 0 && age < SPEED_SAMPLE_STALE_SNAPSHOT_MAX_MS) {
1153
+ if (age >= SPEED_SAMPLES_CACHE_TTL_MS) void startSpeedSnapshotRefresh(db, userId);
1154
+ return age >= SPEED_SAMPLES_CACHE_TTL_MS ? { samples: hit.samples, snapshotAgeMs: age } : { samples: hit.samples };
1155
+ }
1156
+ }
1157
+ void startSpeedSnapshotRefresh(db, userId);
1158
+ return { samples: /* @__PURE__ */ new Map() };
1159
+ }
1160
+ async function injectSpeedContextIntoListAgentsResult(result, options = {}) {
1161
+ try {
1162
+ let parsed;
1163
+ try {
1164
+ parsed = JSON.parse(result);
1165
+ } catch {
1166
+ return result;
1167
+ }
1168
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.agents)) return result;
1169
+ const models = parsed.agents.map((agent) => agent?.model).filter((model) => typeof model === "string");
1170
+ if (models.length === 0 && !options.compactPage) return result;
1171
+ const now = options.now ?? Date.now();
1172
+ let samples = /* @__PURE__ */ new Map();
1173
+ let snapshotAgeMs;
1174
+ const userId = typeof options.userId === "string" ? options.userId.trim() : "";
1175
+ if (options.db && userId) {
1176
+ try {
1177
+ const loaded = options.diskCache ? await loadSpeedSamplesWithDiskCache(options.db, userId, now, options.diskCache) : await loadCachedSpeedSamples(options.db, userId, now);
1178
+ samples = loaded.samples;
1179
+ snapshotAgeMs = loaded.snapshotAgeMs;
1180
+ } catch {
1181
+ samples = /* @__PURE__ */ new Map();
1182
+ }
1183
+ }
1184
+ if (options.compactPage) {
1185
+ return await serializeCompactAgentPage(parsed, samples, snapshotAgeMs, options);
1186
+ }
1187
+ const speedContext = buildCandidateSpeedContext(models, samples, { snapshotAgeMs });
1188
+ return speedContext ? JSON.stringify({ ...parsed, speedContext }) : result;
1189
+ } catch {
1190
+ return options.compactPage ? JSON.stringify({ success: false, error: "LIST_AGENTS_PAGE_SERIALIZATION_FAILED" }) : result;
1191
+ }
1192
+ }
1193
+ async function serializeCompactAgentPage(parsed, samples, snapshotAgeMs, options) {
1194
+ const maxChars = LIST_AGENTS_PAGE_BUDGET;
1195
+ const maxBytes = LIST_AGENTS_PAGE_BUDGET;
1196
+ const fits = (page) => page.length <= maxChars && new TextEncoder().encode(page).length <= maxBytes;
1197
+ const offset = typeof parsed.offset === "number" ? parsed.offset : 0;
1198
+ const candidates = parsed.agents;
1199
+ const availableCount = typeof parsed.availableCount === "number" ? parsed.availableCount : parsed.total;
1200
+ const groups = Array.isArray(parsed.credentialGroups) ? parsed.credentialGroups : [];
1201
+ if (options.fragmentOffset !== void 0) {
1202
+ const fragmentOffset = Number(options.fragmentOffset);
1203
+ const agentKey2 = candidates[0]?.agentKey;
1204
+ if (typeof options.fragmentOffset !== "number" && (typeof options.fragmentOffset !== "string" || !/^\d+$/.test(options.fragmentOffset)) || !Number.isSafeInteger(fragmentOffset) || fragmentOffset < 0 || typeof agentKey2 !== "string" || agentKey2 !== options.fragmentAgentKey) {
1205
+ return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_INVALID", offset });
1206
+ }
1207
+ const agent = candidates[0];
1208
+ const speedContext = buildCandidateSpeedContext(typeof agent.model === "string" ? [agent.model] : [], samples, { snapshotAgeMs });
1209
+ const singleScoped = promoteSharedCredentialGroupQuota(
1210
+ [agent],
1211
+ groups.filter((group) => group.credentialGroup === agent.credentialGroup)
1212
+ );
1213
+ const payload = { agent: singleScoped.agents[0], credentialGroups: singleScoped.groups };
1214
+ let keyCollision = false;
1215
+ const cleanText = (value) => scrubSecrets(sanitizeToolOutputText(value)).cleaned;
1216
+ const sanitize = (value) => {
1217
+ if (typeof value === "string") return cleanText(value);
1218
+ if (Array.isArray(value)) return value.map(sanitize);
1219
+ if (value && typeof value === "object") {
1220
+ const entries = [];
1221
+ const keys = /* @__PURE__ */ new Set();
1222
+ for (const [key, item] of Object.entries(value)) {
1223
+ const cleanedKey = cleanText(key);
1224
+ if (keys.has(cleanedKey)) keyCollision = true;
1225
+ keys.add(cleanedKey);
1226
+ entries.push([cleanedKey, sanitize(item)]);
1227
+ }
1228
+ return Object.fromEntries(entries);
1229
+ }
1230
+ return value;
1231
+ };
1232
+ const safePayload = sanitize(payload);
1233
+ if (keyCollision) return JSON.stringify({ success: false, error: "LIST_AGENTS_SANITIZED_KEY_COLLISION", offset });
1234
+ const serialized = JSON.stringify(safePayload);
1235
+ const bytes = new TextEncoder().encode(serialized);
1236
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1237
+ const digest = Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
1238
+ if (fragmentOffset > 0 && !options.fragmentDigest || options.fragmentDigest && options.fragmentDigest !== digest) {
1239
+ return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_CHANGED", offset });
1240
+ }
1241
+ if (fragmentOffset >= serialized.length) return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_INVALID", offset });
1242
+ if (fragmentOffset > 0 && /[\uDC00-\uDFFF]/.test(serialized[fragmentOffset]) && /[\uD800-\uDBFF]/.test(serialized[fragmentOffset - 1])) return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_INVALID", offset });
1243
+ let end = Math.min(serialized.length, fragmentOffset + 3e3);
1244
+ if (end < serialized.length && /[\uD800-\uDBFF]/.test(serialized[end - 1]) && /[\uDC00-\uDFFF]/.test(serialized[end])) end--;
1245
+ const fragment = serialized.slice(fragmentOffset, end);
1246
+ const result = JSON.stringify({ success: true, agentKey: agentKey2, offset, digest, fragment, fragmentOffset, nextFragmentOffset: end, hasMoreFragments: end < serialized.length, nextOffset: offset + 1, ...speedContext ? { speedContext: cleanText(speedContext) } : {} });
1247
+ return fits(result) ? result : JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_METADATA_TOO_LARGE", offset });
1248
+ }
1249
+ const makePage = (count) => {
1250
+ const scoped = candidates.slice(0, count);
1251
+ const groupKeys = new Set(scoped.map((agent) => agent.credentialGroup).filter(Boolean));
1252
+ const promoted = promoteSharedCredentialGroupQuota(
1253
+ scoped,
1254
+ groups.filter((group) => groupKeys.has(group.credentialGroup))
1255
+ );
1256
+ const agents = promoted.agents;
1257
+ const speedContext = buildCandidateSpeedContext(agents.map((agent) => agent.model).filter((model) => typeof model === "string"), samples, { snapshotAgeMs });
1258
+ const nextOffset = offset + count;
1259
+ const hasMore = nextOffset < availableCount;
1260
+ return JSON.stringify({
1261
+ ...parsed,
1262
+ offset,
1263
+ agents,
1264
+ credentialGroups: promoted.groups,
1265
+ hasMore,
1266
+ ...hasMore ? { nextOffset } : {},
1267
+ ...speedContext ? { speedContext } : {}
1268
+ });
1269
+ };
1270
+ if (!candidates.length) {
1271
+ const empty = makePage(0);
1272
+ if (fits(empty)) return empty;
1273
+ } else {
1274
+ let best;
1275
+ for (let count = 1; count <= candidates.length; count++) {
1276
+ const page = makePage(count);
1277
+ if (!fits(page)) break;
1278
+ best = page;
1279
+ }
1280
+ if (best) return best;
1281
+ }
1282
+ const agentKey = typeof candidates[0]?.agentKey === "string" ? candidates[0].agentKey : void 0;
1283
+ const error = {
1284
+ success: false,
1285
+ error: candidates.length ? "LIST_AGENTS_CANDIDATE_TOO_LARGE" : "LIST_AGENTS_PAGE_METADATA_TOO_LARGE",
1286
+ offset,
1287
+ ...agentKey ? { agentKey, recovery: {
1288
+ tool: "listAgents",
1289
+ arguments: { compact: true, offset, fragmentOffset: 0, fragmentAgentKey: agentKey },
1290
+ note: "Repeat with the same filters and returned digest and nextFragmentOffset; concatenate fragments and parse JSON before continuing at nextOffset."
1291
+ } } : {},
1292
+ ...candidates.length ? { nextOffset: offset + 1, truncated: parsed.truncated === true, poolComplete: parsed.planningRecommendation?.poolComplete === true, hasMore: offset + 1 < availableCount } : {}
1293
+ };
1294
+ const encoded = JSON.stringify(error);
1295
+ return fits(encoded) ? encoded : JSON.stringify({ success: false, error: "LIST_AGENTS_RECOVERY_ID_TOO_LARGE", offset });
1296
+ }
1297
+
1298
+ // packages/ai/agent/defaultReasoningEffort.ts
1299
+ var defaults = {
1300
+ "gpt-6.2-sol": "medium",
1301
+ "gpt-6.2-astra": "high",
1302
+ "gpt-6.1-sol": "medium",
1303
+ "gpt-6.1-terra": "medium",
1304
+ "gpt-6-luna": "medium",
1305
+ "gpt-6-astra": "high",
1306
+ "claude-opus-5-5": "medium",
1307
+ "claude-sonnet-5-5": "high",
1308
+ "deepseek-flash": "high",
1309
+ "deepseek-v4-flash": "high",
1310
+ "deepseek-v4.1-flash": "high"
1311
+ };
1312
+ var deepseekChannels = /* @__PURE__ */ new Set(["opendesign", "ollama-cloud", "lithosai"]);
1313
+ var providers = /* @__PURE__ */ new Set(["nolo", "openai", "openrouter", "anthropic", "deepseek", "commandcode", "opencode-go", "stepfun"]);
1314
+ function resolveDefaultReasoningEffort(input) {
1315
+ const provider = (input.provider ?? "").toLowerCase();
1316
+ const model = (input.model ?? "").toLowerCase().split("/").pop() ?? "";
1317
+ const isDeepseekFlash = ["deepseek-flash", "deepseek-v4-flash", "deepseek-v4.1-flash"].includes(model);
1318
+ const effort = providers.has(provider) || deepseekChannels.has(provider) && isDeepseekFlash ? defaults[model] : void 0;
1319
+ if (!effort) return input.fallback;
1320
+ if (provider === "nolo" && model.startsWith("claude-") && input.model?.startsWith("anthropic/")) return effort;
1321
+ if (provider === "anthropic" && model.startsWith("claude-")) return effort;
1322
+ return resolveModelReasoningCapability(provider, input.model).efforts.includes(effort) ? effort : input.fallback;
1323
+ }
1324
+ function confirmedReasoningEfforts(provider, model) {
1325
+ const capability = resolveModelReasoningCapability(provider, model);
1326
+ if (capability.source === "provider-fallback") return void 0;
1327
+ if (capability.efforts.length === 0) return void 0;
1328
+ return capability.efforts;
1329
+ }
1330
+ var DISPATCH_EFFORT_PREFERENCES = {
1331
+ easy: ["low", "minimal", "medium"],
1332
+ normal: ["medium", "low", "high"],
1333
+ complex: ["high", "medium"],
1334
+ extreme: ["xhigh", "max", "high"]
1335
+ };
1336
+ var DISPATCH_DIFFICULTIES = /* @__PURE__ */ new Set(["easy", "normal", "complex", "extreme"]);
1337
+ function normalizeDifficulty(difficulty) {
1338
+ const normalized = (difficulty ?? "").trim().toLowerCase();
1339
+ return DISPATCH_DIFFICULTIES.has(normalized) ? normalized : "normal";
1340
+ }
1341
+ function asValidAgentEffort(raw) {
1342
+ const normalized = (raw ?? "").trim().toLowerCase();
1343
+ return REASONING_EFFORT_OPTIONS.includes(normalized) ? normalized : void 0;
1344
+ }
1345
+ function hasReasoningEffortSuffix(model) {
1346
+ const normalized = (model ?? "").trim().toLowerCase().split("/").pop() ?? "";
1347
+ return REASONING_EFFORT_SUFFIXES.some((suffix) => normalized.endsWith(`-${suffix}`));
1348
+ }
1349
+ function resolveDispatchReasoningEffort(input) {
1350
+ if (asValidAgentEffort(input.agentReasoningEffort)) return void 0;
1351
+ if (hasReasoningEffortSuffix(input.model)) return void 0;
1352
+ if (!(input.provider ?? "").trim() || !(input.model ?? "").trim()) return void 0;
1353
+ const efforts = confirmedReasoningEfforts(input.provider, input.model);
1354
+ if (!efforts) return void 0;
1355
+ const preferences = DISPATCH_EFFORT_PREFERENCES[normalizeDifficulty(input.difficulty)];
1356
+ return preferences.find((effort) => efforts.includes(effort));
1357
+ }
1358
+ function resolveEffectiveReasoningEffortOverride(input) {
1359
+ const override = asValidAgentEffort(input.override);
1360
+ if (!override) return void 0;
1361
+ if (asValidAgentEffort(input.recordReasoningEffort)) return void 0;
1362
+ if (hasReasoningEffortSuffix(input.model)) return void 0;
1363
+ if (!(input.provider ?? "").trim() || !(input.model ?? "").trim()) return void 0;
1364
+ const efforts = confirmedReasoningEfforts(input.provider, input.model);
1365
+ return efforts?.includes(override) ? override : void 0;
1366
+ }
1367
+ function withReasoningEffortOverride(config, effort) {
1368
+ if (!effort) return config;
1369
+ return {
1370
+ ...config,
1371
+ reasoning_effort: effort,
1372
+ ...config.rawRecord ? { rawRecord: { ...config.rawRecord, reasoning_effort: effort } } : {}
1373
+ };
1374
+ }
1375
+
1376
+ export {
1377
+ isGptProModel,
1378
+ shouldBlockForGptPro,
1379
+ isPlatformPaidAgentCall,
1380
+ deriveCredentialGroup,
1381
+ deriveCustomProviderCredentialGroup,
1382
+ summarizeCredentialGroups,
1383
+ toSafeAgentSummary,
1384
+ sortSafeAgentSummaries,
1385
+ omitNullishAgentSummaryFields,
1386
+ promoteSharedCredentialGroupQuota,
1387
+ toCompactAgentSummary,
1388
+ toUltraCompactAgentSummary,
1389
+ injectSpeedContextIntoListAgentsResult,
1390
+ resolveDefaultReasoningEffort,
1391
+ resolveDispatchReasoningEffort,
1392
+ resolveEffectiveReasoningEffortOverride,
1393
+ withReasoningEffortOverride
1394
+ };