pybao-cli 1.4.83 → 1.4.84

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 (151) hide show
  1. package/dist/REPL-YDQJ4XS3.js +49 -0
  2. package/dist/{acp-5G23YRZD.js → acp-KR2NIRMP.js} +30 -30
  3. package/dist/{agentsValidate-Y3JGFZPX.js → agentsValidate-RP4UMGNT.js} +7 -7
  4. package/dist/{ask-DNEJAFQM.js → ask-AV47M7DZ.js} +29 -29
  5. package/dist/{autoUpdater-NBXSZEKC.js → autoUpdater-KY6NLGJN.js} +3 -3
  6. package/dist/{chunk-MBIKKOOW.js → chunk-2OQK4SGM.js} +1 -1
  7. package/dist/{chunk-FPCH7C5K.js → chunk-2Y6RSLIK.js} +2 -2
  8. package/dist/{chunk-IDJMJZP4.js → chunk-3JI37ZA6.js} +2 -2
  9. package/dist/{chunk-A5LLPMGS.js → chunk-4K65XDFQ.js} +2 -2
  10. package/dist/{chunk-EUHKG6AJ.js → chunk-4T65Y47N.js} +1 -1
  11. package/dist/{chunk-IIZXV4HL.js → chunk-5EJDTTBL.js} +2 -2
  12. package/dist/{chunk-OUOB2RBI.js → chunk-5LRFEGFP.js} +4 -4
  13. package/dist/{chunk-TKPY5LGF.js → chunk-5Z5ZS7IB.js} +1 -1
  14. package/dist/{chunk-7UTUKVKM.js → chunk-6IXLNIBX.js} +4 -4
  15. package/dist/{chunk-RMZABYAD.js → chunk-APXMGUKA.js} +1 -1
  16. package/dist/{chunk-VRRJXBF3.js → chunk-BKU7DKGB.js} +1 -1
  17. package/dist/{chunk-CFX5VEY5.js → chunk-CAPAA2BC.js} +3 -3
  18. package/dist/{chunk-5MZZCUQX.js → chunk-HS5IAPED.js} +2 -2
  19. package/dist/{chunk-53LVQG4V.js → chunk-KELCOTIO.js} +2 -2
  20. package/dist/{chunk-5KEKIQVC.js → chunk-KXHMHPXD.js} +3 -3
  21. package/dist/{chunk-GRQ32HWG.js → chunk-LLNPRFDC.js} +3 -1
  22. package/dist/chunk-LLNPRFDC.js.map +7 -0
  23. package/dist/{chunk-FQL6V43W.js → chunk-NIIT2UQA.js} +1 -1
  24. package/dist/{chunk-WSP4AYLZ.js → chunk-QTPKDLLB.js} +3 -3
  25. package/dist/{chunk-FVR53MZY.js → chunk-QUQAVKTY.js} +3 -3
  26. package/dist/{chunk-DHJEENK5.js → chunk-RIKQVWEQ.js} +2 -2
  27. package/dist/{chunk-LIFJX3UL.js → chunk-RTLO6X7T.js} +3 -3
  28. package/dist/{chunk-EINLEUKA.js → chunk-SELNEWOV.js} +1 -1
  29. package/dist/{chunk-MKSTJEGS.js → chunk-SRT3X6FV.js} +4 -4
  30. package/dist/{chunk-KSCBNFN7.js → chunk-TTMZXWQN.js} +1 -1
  31. package/dist/{chunk-5MEGIDN7.js → chunk-UKCYPF74.js} +1 -1
  32. package/dist/{chunk-V37R5FE5.js → chunk-UTQQ6WYY.js} +16 -16
  33. package/dist/{chunk-WGGELTRR.js → chunk-UZE4M5OS.js} +3 -3
  34. package/dist/{chunk-XHQMUJIS.js → chunk-X2MOC5KR.js} +4 -4
  35. package/dist/{chunk-OCIKBYQ4.js → chunk-X36JZMFM.js} +3 -3
  36. package/dist/{chunk-SUHM4MYA.js → chunk-ZPTG6OYN.js} +1 -1
  37. package/dist/{chunk-GKBRHNMB.js → chunk-ZTGVZNCE.js} +1268 -162
  38. package/dist/{chunk-GKBRHNMB.js.map → chunk-ZTGVZNCE.js.map} +4 -4
  39. package/dist/{cli-7JVEUFE2.js → cli-FHJDO3QF.js} +89 -89
  40. package/dist/commands-KPY2LIJC.js +53 -0
  41. package/dist/{config-YGHZ7OZB.js → config-2K52USGJ.js} +4 -4
  42. package/dist/{context-SNUVPSIW.js → context-3BRWJN5E.js} +6 -6
  43. package/dist/{conversationTracker-IXJWSKYY.js → conversationTracker-QH5XBLEU.js} +3 -3
  44. package/dist/{customCommands-2YZVCPNF.js → customCommands-3PVMTJKU.js} +4 -4
  45. package/dist/{env-SPCTS7IU.js → env-O6FTKEEB.js} +2 -2
  46. package/dist/{file-MRX573XM.js → file-ULFXIDDG.js} +4 -4
  47. package/dist/index.js +3 -3
  48. package/dist/{llm-VAN6WS52.js → llm-WAAV3MBX.js} +270 -180
  49. package/dist/llm-WAAV3MBX.js.map +7 -0
  50. package/dist/{llmLazy-II5PXLQI.js → llmLazy-6V6GNLLC.js} +1 -1
  51. package/dist/{loader-EV4REQWE.js → loader-JF4VIAR6.js} +4 -4
  52. package/dist/{lsp-O2TLN3AD.js → lsp-SANMXODH.js} +6 -6
  53. package/dist/{lspAnchor-BLB7II5Y.js → lspAnchor-A3P4LT3X.js} +6 -6
  54. package/dist/{mcp-OJPHPVNM.js → mcp-U2WNWDDG.js} +7 -7
  55. package/dist/{mentionProcessor-BXCFLUXL.js → mentionProcessor-XZUAAVZX.js} +5 -5
  56. package/dist/{messages-CUNARS37.js → messages-JUZVZDYN.js} +1 -1
  57. package/dist/{model-OUTGOGMR.js → model-JCGDL77F.js} +5 -5
  58. package/dist/{openai-WTOKA74W.js → openai-7OC7CIDJ.js} +5 -5
  59. package/dist/{outputStyles-K5O5RB33.js → outputStyles-RWFKRQCE.js} +4 -4
  60. package/dist/{pluginRuntime-JEJXUSFZ.js → pluginRuntime-BZ3RM5P7.js} +6 -6
  61. package/dist/{pluginValidation-S4VSNYHJ.js → pluginValidation-6DUVMEIK.js} +6 -6
  62. package/dist/prompts-W5GKJOV4.js +55 -0
  63. package/dist/{pybAgentSessionLoad-I7MI2W5O.js → pybAgentSessionLoad-ELD4U4GW.js} +4 -4
  64. package/dist/{pybAgentSessionResume-CMC5D4IX.js → pybAgentSessionResume-B7MQTZPJ.js} +4 -4
  65. package/dist/{pybAgentStreamJsonSession-FUT6NUZG.js → pybAgentStreamJsonSession-R5S6OEAV.js} +1 -1
  66. package/dist/{pybHooks-I4C2HCMR.js → pybHooks-4Y5UPP2F.js} +4 -4
  67. package/dist/query-ZA2CGHOR.js +57 -0
  68. package/dist/{registry-HA4GULY4.js → registry-TQILT7AJ.js} +5 -5
  69. package/dist/{ripgrep-4F2VOLSN.js → ripgrep-B6OHNO36.js} +3 -3
  70. package/dist/{skillMarketplace-73JWYMAT.js → skillMarketplace-M7LOJ7WU.js} +3 -3
  71. package/dist/{state-WVRITIDZ.js → state-YJAFADHA.js} +2 -2
  72. package/dist/{theme-BPZWU5M7.js → theme-W6D4H7FU.js} +5 -5
  73. package/dist/{toolPermissionSettings-UOQTLVV5.js → toolPermissionSettings-IDD5Z57F.js} +6 -6
  74. package/dist/tools-BPMG4PXB.js +54 -0
  75. package/dist/{userInput-TQYQIWBV.js → userInput-PZGDYW45.js} +31 -31
  76. package/package.json +3 -1
  77. package/dist/REPL-KB5JZS6S.js +0 -49
  78. package/dist/chunk-GRQ32HWG.js.map +0 -7
  79. package/dist/commands-FPZREXUW.js +0 -53
  80. package/dist/llm-VAN6WS52.js.map +0 -7
  81. package/dist/prompts-XUL3MGVE.js +0 -55
  82. package/dist/query-HKFFVARD.js +0 -57
  83. package/dist/tools-3OMW2SOR.js +0 -54
  84. /package/dist/{REPL-KB5JZS6S.js.map → REPL-YDQJ4XS3.js.map} +0 -0
  85. /package/dist/{acp-5G23YRZD.js.map → acp-KR2NIRMP.js.map} +0 -0
  86. /package/dist/{agentsValidate-Y3JGFZPX.js.map → agentsValidate-RP4UMGNT.js.map} +0 -0
  87. /package/dist/{ask-DNEJAFQM.js.map → ask-AV47M7DZ.js.map} +0 -0
  88. /package/dist/{autoUpdater-NBXSZEKC.js.map → autoUpdater-KY6NLGJN.js.map} +0 -0
  89. /package/dist/{chunk-MBIKKOOW.js.map → chunk-2OQK4SGM.js.map} +0 -0
  90. /package/dist/{chunk-FPCH7C5K.js.map → chunk-2Y6RSLIK.js.map} +0 -0
  91. /package/dist/{chunk-IDJMJZP4.js.map → chunk-3JI37ZA6.js.map} +0 -0
  92. /package/dist/{chunk-A5LLPMGS.js.map → chunk-4K65XDFQ.js.map} +0 -0
  93. /package/dist/{chunk-EUHKG6AJ.js.map → chunk-4T65Y47N.js.map} +0 -0
  94. /package/dist/{chunk-IIZXV4HL.js.map → chunk-5EJDTTBL.js.map} +0 -0
  95. /package/dist/{chunk-OUOB2RBI.js.map → chunk-5LRFEGFP.js.map} +0 -0
  96. /package/dist/{chunk-TKPY5LGF.js.map → chunk-5Z5ZS7IB.js.map} +0 -0
  97. /package/dist/{chunk-7UTUKVKM.js.map → chunk-6IXLNIBX.js.map} +0 -0
  98. /package/dist/{chunk-RMZABYAD.js.map → chunk-APXMGUKA.js.map} +0 -0
  99. /package/dist/{chunk-VRRJXBF3.js.map → chunk-BKU7DKGB.js.map} +0 -0
  100. /package/dist/{chunk-CFX5VEY5.js.map → chunk-CAPAA2BC.js.map} +0 -0
  101. /package/dist/{chunk-5MZZCUQX.js.map → chunk-HS5IAPED.js.map} +0 -0
  102. /package/dist/{chunk-53LVQG4V.js.map → chunk-KELCOTIO.js.map} +0 -0
  103. /package/dist/{chunk-5KEKIQVC.js.map → chunk-KXHMHPXD.js.map} +0 -0
  104. /package/dist/{chunk-FQL6V43W.js.map → chunk-NIIT2UQA.js.map} +0 -0
  105. /package/dist/{chunk-WSP4AYLZ.js.map → chunk-QTPKDLLB.js.map} +0 -0
  106. /package/dist/{chunk-FVR53MZY.js.map → chunk-QUQAVKTY.js.map} +0 -0
  107. /package/dist/{chunk-DHJEENK5.js.map → chunk-RIKQVWEQ.js.map} +0 -0
  108. /package/dist/{chunk-LIFJX3UL.js.map → chunk-RTLO6X7T.js.map} +0 -0
  109. /package/dist/{chunk-EINLEUKA.js.map → chunk-SELNEWOV.js.map} +0 -0
  110. /package/dist/{chunk-MKSTJEGS.js.map → chunk-SRT3X6FV.js.map} +0 -0
  111. /package/dist/{chunk-KSCBNFN7.js.map → chunk-TTMZXWQN.js.map} +0 -0
  112. /package/dist/{chunk-5MEGIDN7.js.map → chunk-UKCYPF74.js.map} +0 -0
  113. /package/dist/{chunk-V37R5FE5.js.map → chunk-UTQQ6WYY.js.map} +0 -0
  114. /package/dist/{chunk-WGGELTRR.js.map → chunk-UZE4M5OS.js.map} +0 -0
  115. /package/dist/{chunk-XHQMUJIS.js.map → chunk-X2MOC5KR.js.map} +0 -0
  116. /package/dist/{chunk-OCIKBYQ4.js.map → chunk-X36JZMFM.js.map} +0 -0
  117. /package/dist/{chunk-SUHM4MYA.js.map → chunk-ZPTG6OYN.js.map} +0 -0
  118. /package/dist/{cli-7JVEUFE2.js.map → cli-FHJDO3QF.js.map} +0 -0
  119. /package/dist/{commands-FPZREXUW.js.map → commands-KPY2LIJC.js.map} +0 -0
  120. /package/dist/{config-YGHZ7OZB.js.map → config-2K52USGJ.js.map} +0 -0
  121. /package/dist/{context-SNUVPSIW.js.map → context-3BRWJN5E.js.map} +0 -0
  122. /package/dist/{conversationTracker-IXJWSKYY.js.map → conversationTracker-QH5XBLEU.js.map} +0 -0
  123. /package/dist/{customCommands-2YZVCPNF.js.map → customCommands-3PVMTJKU.js.map} +0 -0
  124. /package/dist/{env-SPCTS7IU.js.map → env-O6FTKEEB.js.map} +0 -0
  125. /package/dist/{file-MRX573XM.js.map → file-ULFXIDDG.js.map} +0 -0
  126. /package/dist/{llmLazy-II5PXLQI.js.map → llmLazy-6V6GNLLC.js.map} +0 -0
  127. /package/dist/{loader-EV4REQWE.js.map → loader-JF4VIAR6.js.map} +0 -0
  128. /package/dist/{lsp-O2TLN3AD.js.map → lsp-SANMXODH.js.map} +0 -0
  129. /package/dist/{lspAnchor-BLB7II5Y.js.map → lspAnchor-A3P4LT3X.js.map} +0 -0
  130. /package/dist/{mcp-OJPHPVNM.js.map → mcp-U2WNWDDG.js.map} +0 -0
  131. /package/dist/{mentionProcessor-BXCFLUXL.js.map → mentionProcessor-XZUAAVZX.js.map} +0 -0
  132. /package/dist/{messages-CUNARS37.js.map → messages-JUZVZDYN.js.map} +0 -0
  133. /package/dist/{model-OUTGOGMR.js.map → model-JCGDL77F.js.map} +0 -0
  134. /package/dist/{openai-WTOKA74W.js.map → openai-7OC7CIDJ.js.map} +0 -0
  135. /package/dist/{outputStyles-K5O5RB33.js.map → outputStyles-RWFKRQCE.js.map} +0 -0
  136. /package/dist/{pluginRuntime-JEJXUSFZ.js.map → pluginRuntime-BZ3RM5P7.js.map} +0 -0
  137. /package/dist/{pluginValidation-S4VSNYHJ.js.map → pluginValidation-6DUVMEIK.js.map} +0 -0
  138. /package/dist/{prompts-XUL3MGVE.js.map → prompts-W5GKJOV4.js.map} +0 -0
  139. /package/dist/{pybAgentSessionLoad-I7MI2W5O.js.map → pybAgentSessionLoad-ELD4U4GW.js.map} +0 -0
  140. /package/dist/{pybAgentSessionResume-CMC5D4IX.js.map → pybAgentSessionResume-B7MQTZPJ.js.map} +0 -0
  141. /package/dist/{pybAgentStreamJsonSession-FUT6NUZG.js.map → pybAgentStreamJsonSession-R5S6OEAV.js.map} +0 -0
  142. /package/dist/{pybHooks-I4C2HCMR.js.map → pybHooks-4Y5UPP2F.js.map} +0 -0
  143. /package/dist/{query-HKFFVARD.js.map → query-ZA2CGHOR.js.map} +0 -0
  144. /package/dist/{registry-HA4GULY4.js.map → registry-TQILT7AJ.js.map} +0 -0
  145. /package/dist/{ripgrep-4F2VOLSN.js.map → ripgrep-B6OHNO36.js.map} +0 -0
  146. /package/dist/{skillMarketplace-73JWYMAT.js.map → skillMarketplace-M7LOJ7WU.js.map} +0 -0
  147. /package/dist/{state-WVRITIDZ.js.map → state-YJAFADHA.js.map} +0 -0
  148. /package/dist/{theme-BPZWU5M7.js.map → theme-W6D4H7FU.js.map} +0 -0
  149. /package/dist/{toolPermissionSettings-UOQTLVV5.js.map → toolPermissionSettings-IDD5Z57F.js.map} +0 -0
  150. /package/dist/{tools-3OMW2SOR.js.map → tools-BPMG4PXB.js.map} +0 -0
  151. /package/dist/{userInput-TQYQIWBV.js.map → userInput-PZGDYW45.js.map} +0 -0
@@ -2,11 +2,11 @@ import { createRequire as __pybCreateRequire } from "node:module";
2
2
  const require = __pybCreateRequire(import.meta.url);
3
3
  import {
4
4
  listPybAgentSessions
5
- } from "./chunk-EINLEUKA.js";
5
+ } from "./chunk-SELNEWOV.js";
6
6
  import {
7
7
  formatValidationResult,
8
8
  validatePluginOrMarketplacePath
9
- } from "./chunk-WGGELTRR.js";
9
+ } from "./chunk-UZE4M5OS.js";
10
10
  import {
11
11
  ConversationTracker,
12
12
  appendFinishState,
@@ -14,18 +14,18 @@ import {
14
14
  getConversationTrackerForContext,
15
15
  isFinishComplete,
16
16
  mapFinishReason
17
- } from "./chunk-RMZABYAD.js";
17
+ } from "./chunk-APXMGUKA.js";
18
18
  import {
19
19
  beginReplSessionScope
20
20
  } from "./chunk-F4AXICO7.js";
21
21
  import {
22
22
  loadPybAgentSessionMessages
23
- } from "./chunk-FQL6V43W.js";
23
+ } from "./chunk-NIIT2UQA.js";
24
24
  import {
25
25
  appendSessionCustomTitleRecord,
26
26
  appendSessionJsonlFromMessage,
27
27
  appendSessionTagRecord
28
- } from "./chunk-A5LLPMGS.js";
28
+ } from "./chunk-4K65XDFQ.js";
29
29
  import {
30
30
  drainHookSystemPromptAdditions,
31
31
  getHookTranscriptPath,
@@ -37,7 +37,7 @@ import {
37
37
  runStopHooks,
38
38
  runUserPromptSubmitHooks,
39
39
  updateHookTranscriptForMessages
40
- } from "./chunk-5KEKIQVC.js";
40
+ } from "./chunk-KXHMHPXD.js";
41
41
  import {
42
42
  DEFAULT_OUTPUT_STYLE,
43
43
  getAvailableOutputStyles,
@@ -46,11 +46,11 @@ import {
46
46
  getOutputStyleSystemPromptAdditions,
47
47
  resolveOutputStyleName,
48
48
  setCurrentOutputStyle
49
- } from "./chunk-IDJMJZP4.js";
49
+ } from "./chunk-3JI37ZA6.js";
50
50
  import {
51
51
  fetchCustomModels,
52
52
  getModelFeatures
53
- } from "./chunk-53LVQG4V.js";
53
+ } from "./chunk-KELCOTIO.js";
54
54
  import {
55
55
  getSessionState
56
56
  } from "./chunk-XKYHFZEC.js";
@@ -58,7 +58,7 @@ import {
58
58
  queryLLM,
59
59
  queryQuick,
60
60
  verifyApiKey
61
- } from "./chunk-OUOB2RBI.js";
61
+ } from "./chunk-5LRFEGFP.js";
62
62
  import {
63
63
  DEFAULT_TIMEOUT_MS,
64
64
  FallbackToolUseRejectedMessage,
@@ -72,7 +72,7 @@ import {
72
72
  listMCPServers,
73
73
  loadMergedSettings,
74
74
  normalizeSandboxRuntimeConfigFromSettings
75
- } from "./chunk-7UTUKVKM.js";
75
+ } from "./chunk-6IXLNIBX.js";
76
76
  import {
77
77
  addMarketplace,
78
78
  disableSkillPlugin,
@@ -85,11 +85,11 @@ import {
85
85
  refreshMarketplaceAsync,
86
86
  removeMarketplace,
87
87
  uninstallSkillPlugin
88
- } from "./chunk-SUHM4MYA.js";
88
+ } from "./chunk-ZPTG6OYN.js";
89
89
  import {
90
90
  loadToolPermissionContextFromDisk,
91
91
  persistToolPermissionUpdateToDisk
92
- } from "./chunk-FVR53MZY.js";
92
+ } from "./chunk-QUQAVKTY.js";
93
93
  import {
94
94
  applyToolPermissionContextUpdate,
95
95
  applyToolPermissionContextUpdates,
@@ -100,13 +100,13 @@ import {
100
100
  generateSystemReminders,
101
101
  resetReminderSession,
102
102
  systemReminderService
103
- } from "./chunk-5MZZCUQX.js";
103
+ } from "./chunk-HS5IAPED.js";
104
104
  import {
105
105
  clearAgentCache,
106
106
  getActiveAgents,
107
107
  getAgentByType,
108
108
  getAllAgents
109
- } from "./chunk-DHJEENK5.js";
109
+ } from "./chunk-RIKQVWEQ.js";
110
110
  import {
111
111
  API_ERROR_MESSAGE_PREFIX,
112
112
  CANCEL_MESSAGE,
@@ -137,7 +137,7 @@ import {
137
137
  processUserInput,
138
138
  reorderMessages,
139
139
  stripSystemMessages
140
- } from "./chunk-EUHKG6AJ.js";
140
+ } from "./chunk-4T65Y47N.js";
141
141
  import {
142
142
  getRequestStatus,
143
143
  setRequestStatus,
@@ -167,7 +167,7 @@ import {
167
167
  normalizeFilePath,
168
168
  readTextContent,
169
169
  writeTextContent
170
- } from "./chunk-FPCH7C5K.js";
170
+ } from "./chunk-2Y6RSLIK.js";
171
171
  import {
172
172
  parseBlockEdits
173
173
  } from "./chunk-QWIBSCDN.js";
@@ -177,18 +177,18 @@ import {
177
177
  ParserRegistry,
178
178
  initParser,
179
179
  loadLanguage
180
- } from "./chunk-XHQMUJIS.js";
180
+ } from "./chunk-X2MOC5KR.js";
181
181
  import {
182
182
  getSettingsFileCandidates,
183
183
  loadSettingsWithLegacyFallback,
184
184
  readSettingsFile
185
- } from "./chunk-5MEGIDN7.js";
185
+ } from "./chunk-UKCYPF74.js";
186
186
  import {
187
187
  getCustomCommandDirectories,
188
188
  hasCustomCommands,
189
189
  loadCustomCommands,
190
190
  reloadCustomCommands
191
- } from "./chunk-IIZXV4HL.js";
191
+ } from "./chunk-5EJDTTBL.js";
192
192
  import {
193
193
  getSessionPlugins
194
194
  } from "./chunk-BJSWTHRM.js";
@@ -196,7 +196,7 @@ import {
196
196
  ModelManager,
197
197
  getModelManager,
198
198
  isDefaultSlowAndCapableModel
199
- } from "./chunk-OCIKBYQ4.js";
199
+ } from "./chunk-X36JZMFM.js";
200
200
  import {
201
201
  getCodeStyle,
202
202
  getContext,
@@ -204,13 +204,13 @@ import {
204
204
  getIsGit,
205
205
  getProjectDocs,
206
206
  getProjectStructureStatisticsBlock
207
- } from "./chunk-MKSTJEGS.js";
207
+ } from "./chunk-SRT3X6FV.js";
208
208
  import {
209
209
  ripGrep
210
- } from "./chunk-KSCBNFN7.js";
210
+ } from "./chunk-TTMZXWQN.js";
211
211
  import {
212
212
  getTheme
213
- } from "./chunk-TKPY5LGF.js";
213
+ } from "./chunk-5Z5ZS7IB.js";
214
214
  import {
215
215
  DEFAULT_GLOBAL_CONFIG,
216
216
  enableConfigs,
@@ -223,7 +223,7 @@ import {
223
223
  saveGlobalConfig,
224
224
  setAllPointersToModel,
225
225
  setModelPointer
226
- } from "./chunk-WSP4AYLZ.js";
226
+ } from "./chunk-QTPKDLLB.js";
227
227
  import {
228
228
  AbortError
229
229
  } from "./chunk-RQVLBMP7.js";
@@ -232,7 +232,7 @@ import {
232
232
  getCurrentRequest,
233
233
  logUserFriendly,
234
234
  markPhase
235
- } from "./chunk-MBIKKOOW.js";
235
+ } from "./chunk-2OQK4SGM.js";
236
236
  import {
237
237
  ASCII_LOGO,
238
238
  BunShell,
@@ -266,15 +266,16 @@ import {
266
266
  overwriteLog,
267
267
  renderBackgroundShellStatusAttachment,
268
268
  renderBashNotification,
269
+ resolveXdgCachePath,
269
270
  resolveXdgDataPath,
270
271
  setActivePlanConversationKey,
271
272
  setCwd,
272
273
  shouldApplyToolOutputTruncation,
273
274
  truncateToolOutput
274
- } from "./chunk-VRRJXBF3.js";
275
+ } from "./chunk-BKU7DKGB.js";
275
276
  import {
276
277
  MACRO
277
- } from "./chunk-GRQ32HWG.js";
278
+ } from "./chunk-LLNPRFDC.js";
278
279
  import {
279
280
  __export
280
281
  } from "./chunk-I3J4JYES.js";
@@ -282,9 +283,9 @@ import {
282
283
  // src/tools/system/BashTool/BashTool.tsx
283
284
  import { statSync as statSync13 } from "fs";
284
285
  import { EOL as EOL3 } from "os";
285
- import { isAbsolute as isAbsolute8, relative as relative12, resolve as resolve10 } from "path";
286
+ import { isAbsolute as isAbsolute8, relative as relative12, resolve as resolve11 } from "path";
286
287
  import * as React106 from "react";
287
- import { z as z13 } from "zod";
288
+ import { z as z15 } from "zod";
288
289
 
289
290
  // src/utils/commands/index.ts
290
291
  import { memoize } from "lodash-es";
@@ -455,7 +456,7 @@ var getCommandSubcommandPrefix = memoize(
455
456
  var getCommandPrefix = memoize(
456
457
  async (command4, abortSignal) => {
457
458
  const { systemPrompt, userPrompt } = buildBashCommandPrefixDetectionPrompt(command4);
458
- const { API_ERROR_MESSAGE_PREFIX: API_ERROR_MESSAGE_PREFIX2, queryQuick: queryQuick2 } = await import("./llm-VAN6WS52.js");
459
+ const { API_ERROR_MESSAGE_PREFIX: API_ERROR_MESSAGE_PREFIX2, queryQuick: queryQuick2 } = await import("./llm-WAAV3MBX.js");
459
460
  const response = await queryQuick2({
460
461
  systemPrompt,
461
462
  userPrompt,
@@ -740,8 +741,8 @@ async function shouldAllowNetworkRequest(query2) {
740
741
  }
741
742
  async function serializePermissionPrompt(task) {
742
743
  let release = null;
743
- const next = new Promise((resolve11) => {
744
- release = resolve11;
744
+ const next = new Promise((resolve12) => {
745
+ release = resolve12;
745
746
  });
746
747
  const prev = active.permissionPromptChain;
747
748
  active.permissionPromptChain = prev.then(() => next);
@@ -774,18 +775,18 @@ async function cleanupSandboxNetworkInfrastructure() {
774
775
  active.sessionDeniedHosts.clear();
775
776
  active.inflightPermissionRequests.clear();
776
777
  await Promise.allSettled([
777
- httpServer ? new Promise((resolve11) => {
778
+ httpServer ? new Promise((resolve12) => {
778
779
  try {
779
- httpServer.close(() => resolve11());
780
+ httpServer.close(() => resolve12());
780
781
  } catch {
781
- resolve11();
782
+ resolve12();
782
783
  }
783
784
  }) : Promise.resolve(),
784
- socksServer ? new Promise((resolve11) => {
785
+ socksServer ? new Promise((resolve12) => {
785
786
  try {
786
- socksServer.close(() => resolve11());
787
+ socksServer.close(() => resolve12());
787
788
  } catch {
788
- resolve11();
789
+ resolve12();
789
790
  }
790
791
  }) : Promise.resolve()
791
792
  ]);
@@ -975,7 +976,7 @@ async function startHttpProxy() {
975
976
  clientSocket.on("data", onData);
976
977
  });
977
978
  active.httpProxyServer = server;
978
- return new Promise((resolve11, reject) => {
979
+ return new Promise((resolve12, reject) => {
979
980
  server.once("error", reject);
980
981
  server.once("listening", () => {
981
982
  const addr = server.address();
@@ -984,7 +985,7 @@ async function startHttpProxy() {
984
985
  return;
985
986
  }
986
987
  server.unref();
987
- resolve11(addr.port);
988
+ resolve12(addr.port);
988
989
  });
989
990
  server.listen(0, "127.0.0.1");
990
991
  });
@@ -1094,7 +1095,7 @@ async function startSocks5Proxy() {
1094
1095
  socket.on("data", onData);
1095
1096
  });
1096
1097
  active.socksProxyServer = server;
1097
- return new Promise((resolve11, reject) => {
1098
+ return new Promise((resolve12, reject) => {
1098
1099
  server.once("error", reject);
1099
1100
  server.once("listening", () => {
1100
1101
  const addr = server.address();
@@ -1103,7 +1104,7 @@ async function startSocks5Proxy() {
1103
1104
  return;
1104
1105
  }
1105
1106
  server.unref();
1106
- resolve11(addr.port);
1107
+ resolve12(addr.port);
1107
1108
  });
1108
1109
  server.listen(0, "127.0.0.1");
1109
1110
  });
@@ -2571,7 +2572,7 @@ function findMatchingBashRules(args) {
2571
2572
  args.toolPermissionContext,
2572
2573
  args.behavior
2573
2574
  );
2574
- const matches = [];
2575
+ const matches2 = [];
2575
2576
  for (const ruleString of rules) {
2576
2577
  const parsed = parseToolRuleString(ruleString);
2577
2578
  if (!parsed || parsed.toolName !== "Bash" || !parsed.ruleContent) continue;
@@ -2588,9 +2589,9 @@ function findMatchingBashRules(args) {
2588
2589
  return candidate.startsWith(`${ruleContent.prefix} `);
2589
2590
  }
2590
2591
  });
2591
- if (matched) matches.push(ruleString);
2592
+ if (matched) matches2.push(ruleString);
2592
2593
  }
2593
- return matches;
2594
+ return matches2;
2594
2595
  }
2595
2596
  function buildBashRuleSuggestionExact(command4) {
2596
2597
  return [
@@ -3071,14 +3072,14 @@ function RQ5(command4) {
3071
3072
  if (!HEREDOC_IN_SUBSTITUTION.test(command4)) return false;
3072
3073
  try {
3073
3074
  const re = /\$\(cat\s*<<-?\s*(?:'+([A-Za-z_]\w*)'+|\\([A-Za-z_]\w*))/g;
3074
- const matches = [];
3075
+ const matches2 = [];
3075
3076
  let m;
3076
3077
  while ((m = re.exec(command4)) !== null) {
3077
3078
  const delimiter = m[1] || m[2];
3078
- if (delimiter) matches.push({ start: m.index, delimiter });
3079
+ if (delimiter) matches2.push({ start: m.index, delimiter });
3079
3080
  }
3080
- if (matches.length === 0) return false;
3081
- for (const { start, delimiter } of matches) {
3081
+ if (matches2.length === 0) return false;
3082
+ for (const { start, delimiter } of matches2) {
3082
3083
  const tail = command4.substring(start);
3083
3084
  const escaped = delimiter.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");
3084
3085
  if (!new RegExp(`(?:\\n|^[^\\\\n]*\\n)${escaped}\\\\s*\\\\)`).test(tail))
@@ -3089,7 +3090,7 @@ function RQ5(command4) {
3089
3090
  if (!tail.match(full)) return false;
3090
3091
  }
3091
3092
  let remaining = command4;
3092
- for (const { delimiter } of matches) {
3093
+ for (const { delimiter } of matches2) {
3093
3094
  const escaped = delimiter.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");
3094
3095
  const pattern = new RegExp(
3095
3096
  `\\\\$\\\\(cat\\\\s*<<-?\\\\s*(?:'+${escaped}'+|\\\\\\\\${escaped})[^\\\\n]*\\\\n(?:[\\\\s\\\\S]*?\\\\n)?${escaped}\\\\s*\\\\)`
@@ -4257,7 +4258,7 @@ function formatParseError(error) {
4257
4258
  return error instanceof Error ? error.message : String(error);
4258
4259
  }
4259
4260
  async function defaultGateQuery(args) {
4260
- const { API_ERROR_MESSAGE_PREFIX: API_ERROR_MESSAGE_PREFIX2, queryLLM: queryLLM2 } = await import("./llm-VAN6WS52.js");
4261
+ const { API_ERROR_MESSAGE_PREFIX: API_ERROR_MESSAGE_PREFIX2, queryLLM: queryLLM2 } = await import("./llm-WAAV3MBX.js");
4261
4262
  const queryLLMFn = args.queryLLMOverride ?? queryLLM2;
4262
4263
  const messages = [
4263
4264
  {
@@ -6654,7 +6655,7 @@ var FileEditTool = {
6654
6655
  const originalFileContent = currentFileContent;
6655
6656
  let totalPatch = [];
6656
6657
  const { SmartEdit } = await import("./smart-edit-AWHJDSU6.js");
6657
- const { findLspAnchor } = await import("./lspAnchor-BLB7II5Y.js");
6658
+ const { findLspAnchor } = await import("./lspAnchor-A3P4LT3X.js");
6658
6659
  for (const op of editOperations) {
6659
6660
  const normalizedSearch = normalizeLineEndings(op.search);
6660
6661
  const normalizedReplace = normalizeLineEndings(op.replace);
@@ -8988,7 +8989,7 @@ var WebSearchTool = {
8988
8989
  };
8989
8990
 
8990
8991
  // src/tools/interaction/SlashCommandTool/SlashCommandTool.tsx
8991
- import { z as z11 } from "zod";
8992
+ import { z as z13 } from "zod";
8992
8993
  import * as React103 from "react";
8993
8994
 
8994
8995
  // src/ui/components/Bug.tsx
@@ -10066,9 +10067,9 @@ function setTerminalTitle(title) {
10066
10067
  }
10067
10068
  }
10068
10069
  function clearTerminal() {
10069
- return new Promise((resolve11) => {
10070
+ return new Promise((resolve12) => {
10070
10071
  process.stdout.write("\x1B[2J\x1B[3J\x1B[H", () => {
10071
- resolve11();
10072
+ resolve12();
10072
10073
  });
10073
10074
  });
10074
10075
  }
@@ -11186,8 +11187,8 @@ var OAuthService = class {
11186
11187
  await authURLHandler(manualUrl);
11187
11188
  await openBrowser(autoUrl);
11188
11189
  };
11189
- const { authorizationCode, useManualRedirect } = await new Promise((resolve11, reject) => {
11190
- this.pendingCodePromise = { resolve: resolve11, reject };
11190
+ const { authorizationCode, useManualRedirect } = await new Promise((resolve12, reject) => {
11191
+ this.pendingCodePromise = { resolve: resolve12, reject };
11191
11192
  this.startLocalServer(state, onReady);
11192
11193
  });
11193
11194
  const {
@@ -11358,7 +11359,7 @@ async function createAndStoreApiKey(accessToken) {
11358
11359
  }
11359
11360
  saveGlobalConfig(config2);
11360
11361
  try {
11361
- const { resetAnthropicClient } = await import("./llm-VAN6WS52.js");
11362
+ const { resetAnthropicClient } = await import("./llm-WAAV3MBX.js");
11362
11363
  resetAnthropicClient();
11363
11364
  } catch {
11364
11365
  }
@@ -13798,7 +13799,7 @@ function ModelSelector({
13798
13799
  setModelLoadError(
13799
13800
  `Attempt ${attempt}/${MAX_RETRIES}: Retrying model discovery...`
13800
13801
  );
13801
- await new Promise((resolve11) => setTimeout(resolve11, 1e3));
13802
+ await new Promise((resolve12) => setTimeout(resolve12, 1e3));
13802
13803
  }
13803
13804
  try {
13804
13805
  const models = await fetchModels();
@@ -15725,7 +15726,7 @@ async function refreshPluginRuntimeFromInstalls() {
15725
15726
  const existingRoots = getSessionPlugins().map((p) => p.rootDir);
15726
15727
  const dirs = Array.from(/* @__PURE__ */ new Set([...existingRoots, ...installedRoots]));
15727
15728
  if (dirs.length === 0) return [];
15728
- const { configureSessionPlugins } = await import("./pluginRuntime-JEJXUSFZ.js");
15729
+ const { configureSessionPlugins } = await import("./pluginRuntime-BZ3RM5P7.js");
15729
15730
  const { errors } = await configureSessionPlugins({ pluginDirs: dirs });
15730
15731
  return errors;
15731
15732
  }
@@ -16394,7 +16395,7 @@ async function call(onDone, context) {
16394
16395
  ModelConfig,
16395
16396
  {
16396
16397
  onClose: () => {
16397
- import("./model-OUTGOGMR.js").then(({ reloadModelManager: reloadModelManager2 }) => {
16398
+ import("./model-JCGDL77F.js").then(({ reloadModelManager: reloadModelManager2 }) => {
16398
16399
  reloadModelManager2();
16399
16400
  triggerModelConfigChange();
16400
16401
  onDone();
@@ -22764,8 +22765,8 @@ function generateMentionSuggestions(args) {
22764
22765
  });
22765
22766
  }
22766
22767
  const candidates = allSuggestions.map((s) => s.value);
22767
- const matches = matchCommands(candidates, prefix);
22768
- const fuzzyResults = matches.map((match) => {
22768
+ const matches2 = matchCommands(candidates, prefix);
22769
+ const fuzzyResults = matches2.map((match) => {
22769
22770
  const suggestion = allSuggestions.find((s) => s.value === match.command);
22770
22771
  return {
22771
22772
  ...suggestion,
@@ -23487,8 +23488,8 @@ function generateUnixCommandSuggestions(args) {
23487
23488
  }
23488
23489
  const commonCommands = getCommonSystemCommands(systemCommands);
23489
23490
  const uniqueCommands = Array.from(new Set(commonCommands));
23490
- const matches = matchCommands(uniqueCommands, prefix);
23491
- const boostedMatches = matches.map((match) => {
23491
+ const matches2 = matchCommands(uniqueCommands, prefix);
23492
+ const boostedMatches = matches2.map((match) => {
23492
23493
  const priority = getCommandPriority(match.command);
23493
23494
  return {
23494
23495
  ...match,
@@ -24140,13 +24141,13 @@ function useUnifiedCompletion({
24140
24141
  }
24141
24142
  if (context.type === "command") {
24142
24143
  const fullCommand = `/${suggestion.value}`;
24143
- const matches = currentInput === fullCommand;
24144
- return matches;
24144
+ const matches2 = currentInput === fullCommand;
24145
+ return matches2;
24145
24146
  }
24146
24147
  if (context.type === "agent") {
24147
24148
  const fullAgent = `@${suggestion.value}`;
24148
- const matches = currentInput === fullAgent;
24149
- return matches;
24149
+ const matches2 = currentInput === fullAgent;
24150
+ return matches2;
24150
24151
  }
24151
24152
  return false;
24152
24153
  },
@@ -24310,7 +24311,7 @@ async function launchExternalEditor(initialText) {
24310
24311
  }
24311
24312
  }
24312
24313
  try {
24313
- await new Promise((resolve11, reject) => {
24314
+ await new Promise((resolve12, reject) => {
24314
24315
  const child = spawn(
24315
24316
  editorCommand.command,
24316
24317
  [...editorCommand.args, filePath],
@@ -24322,7 +24323,7 @@ async function launchExternalEditor(initialText) {
24322
24323
  child.on("error", reject);
24323
24324
  child.on("exit", (code, signal) => {
24324
24325
  if (code === 0 || code === null) {
24325
- resolve11();
24326
+ resolve12();
24326
24327
  } else {
24327
24328
  reject(
24328
24329
  new Error(
@@ -24598,7 +24599,7 @@ function useStatusLine() {
24598
24599
  // src/ui/components/PromptInput.tsx
24599
24600
  async function interpretHashCommand(input) {
24600
24601
  try {
24601
- const { queryQuick: queryQuick2 } = await import("./llm-VAN6WS52.js");
24602
+ const { queryQuick: queryQuick2 } = await import("./llm-WAAV3MBX.js");
24602
24603
  const systemPrompt = [
24603
24604
  "You're helping the user structure notes that will be added to their PYB.md file.",
24604
24605
  "Format the user's input into a well-structured note that will be useful for later reference.",
@@ -24803,7 +24804,7 @@ function PromptInput({
24803
24804
  abortController.abort();
24804
24805
  }
24805
24806
  setIsLoading(false);
24806
- await new Promise((resolve11) => setTimeout(resolve11, 0));
24807
+ await new Promise((resolve12) => setTimeout(resolve12, 0));
24807
24808
  setIsLoading(true);
24808
24809
  let finalInput2 = cleanInput;
24809
24810
  for (const { placeholder: placeholder2, text } of pastedTexts) {
@@ -24911,7 +24912,7 @@ function PromptInput({
24911
24912
  if (messages2.length) {
24912
24913
  if (mode === "bash") {
24913
24914
  onQuery(messages2, newAbortController).then(async () => {
24914
- const { getCwd: getCwd2 } = await import("./state-WVRITIDZ.js");
24915
+ const { getCwd: getCwd2 } = await import("./state-YJAFADHA.js");
24915
24916
  setCurrentPwd(getCwd2());
24916
24917
  });
24917
24918
  } else {
@@ -25271,11 +25272,11 @@ import { useCallback as useCallback14 } from "react";
25271
25272
  function useCanUseTool(setToolUseConfirm) {
25272
25273
  return useCallback14(
25273
25274
  async (tool, input, toolUseContext, assistantMessage) => {
25274
- return new Promise((resolve11) => {
25275
+ return new Promise((resolve12) => {
25275
25276
  function logCancelledEvent() {
25276
25277
  }
25277
25278
  function resolveWithCancelledAndAbortAllToolCalls(message) {
25278
- resolve11({
25279
+ resolve12({
25279
25280
  result: false,
25280
25281
  message: message ? `${REJECT_MESSAGE_WITH_FEEDBACK_PREFIX}${message}` : REJECT_MESSAGE
25281
25282
  });
@@ -25293,12 +25294,12 @@ function useCanUseTool(setToolUseConfirm) {
25293
25294
  assistantMessage
25294
25295
  ).then(async (result) => {
25295
25296
  if (result.result === true) {
25296
- resolve11({ result: true });
25297
+ resolve12({ result: true });
25297
25298
  return;
25298
25299
  }
25299
25300
  const deniedResult = result;
25300
25301
  if (deniedResult.shouldPromptUser === false) {
25301
- resolve11({ result: false, message: deniedResult.message });
25302
+ resolve12({ result: false, message: deniedResult.message });
25302
25303
  return;
25303
25304
  }
25304
25305
  const [description3, commandPrefix] = await Promise.all([
@@ -25330,7 +25331,7 @@ function useCanUseTool(setToolUseConfirm) {
25330
25331
  if (type3 === "permanent") {
25331
25332
  } else {
25332
25333
  }
25333
- resolve11({ result: true });
25334
+ resolve12({ result: true });
25334
25335
  },
25335
25336
  onReject(rejectionMessage) {
25336
25337
  resolveWithCancelledAndAbortAllToolCalls(rejectionMessage);
@@ -25928,6 +25929,794 @@ async function selectAndReadFiles() {
25928
25929
  return results;
25929
25930
  }
25930
25931
 
25932
+ // src/services/telemetry/eventBus.ts
25933
+ var listeners2 = /* @__PURE__ */ new Map();
25934
+ function registerTelemetryListener(listenerId, listener) {
25935
+ listeners2.set(listenerId, listener);
25936
+ }
25937
+ function emitTelemetryEvent(event) {
25938
+ for (const listener of listeners2.values()) {
25939
+ listener(event);
25940
+ }
25941
+ }
25942
+
25943
+ // src/utils/session/autoCompactMetrics.ts
25944
+ function safeDivide(numerator, denominator) {
25945
+ if (denominator <= 0) return 0;
25946
+ return numerator / denominator;
25947
+ }
25948
+ function computeAutoCompactMetrics(events) {
25949
+ const failedEvents = events.filter((event) => event.phase === "AUTO_COMPACT_FAILED");
25950
+ const retryEvents = events.filter((event) => event.phase === "AUTO_COMPACT_RETRY");
25951
+ const fallbackEvents = events.filter((event) => event.phase === "AUTO_COMPACT_FALLBACK");
25952
+ const invalidShapeFailures = failedEvents.filter(
25953
+ (event) => event.data?.failureType === "invalid_content_shape"
25954
+ ).length;
25955
+ const compact_invalid_shape_rate = safeDivide(
25956
+ invalidShapeFailures,
25957
+ failedEvents.length
25958
+ );
25959
+ const retrySuccessSignals = fallbackEvents.length;
25960
+ const compact_retry_success_rate = safeDivide(
25961
+ retrySuccessSignals,
25962
+ retryEvents.length + fallbackEvents.length
25963
+ );
25964
+ const transformAppliedEvents = events.filter(
25965
+ (event) => event.phase === "MESSAGE_TRANSFORM_APPLIED"
25966
+ );
25967
+ const thinkingFirstCount = transformAppliedEvents.filter((event) => {
25968
+ const stats = event.data?.outputBlockStats || {};
25969
+ const thinking = Number(stats.thinking ?? 0);
25970
+ const text = Number(stats.text ?? 0);
25971
+ return thinking > 0 && text > 0;
25972
+ }).length;
25973
+ const thinking_first_ratio = safeDivide(
25974
+ thinkingFirstCount,
25975
+ transformAppliedEvents.length
25976
+ );
25977
+ const crossReplayTagged = events.filter(
25978
+ (event) => event.phase === "AUTO_COMPACT_FAILED" || event.phase === "AUTO_COMPACT_RETRY" || event.phase === "AUTO_COMPACT_FALLBACK"
25979
+ );
25980
+ const crossReplayErrors = crossReplayTagged.filter(
25981
+ (event) => event.data?.crossModelReplay === true && event.phase === "AUTO_COMPACT_FAILED"
25982
+ ).length;
25983
+ const crossReplayTotal = crossReplayTagged.filter(
25984
+ (event) => event.data?.crossModelReplay === true
25985
+ ).length;
25986
+ const cross_model_replay_error_rate = safeDivide(
25987
+ crossReplayErrors,
25988
+ crossReplayTotal
25989
+ );
25990
+ return {
25991
+ compact_invalid_shape_rate,
25992
+ compact_retry_success_rate,
25993
+ thinking_first_ratio,
25994
+ cross_model_replay_error_rate
25995
+ };
25996
+ }
25997
+
25998
+ // src/utils/session/autoCompactMetricsSink.ts
25999
+ function createAutoCompactMetricsSink() {
26000
+ const events = [];
26001
+ return {
26002
+ push(event) {
26003
+ events.push(event);
26004
+ },
26005
+ snapshot() {
26006
+ return {
26007
+ eventCount: events.length,
26008
+ metrics: computeAutoCompactMetrics(events)
26009
+ };
26010
+ },
26011
+ clear() {
26012
+ events.length = 0;
26013
+ }
26014
+ };
26015
+ }
26016
+
26017
+ // src/services/telemetry/autoCompactTelemetry.ts
26018
+ var AUTO_COMPACT_TELEMETRY_PHASES = /* @__PURE__ */ new Set([
26019
+ "AUTO_COMPACT_FAILED",
26020
+ "AUTO_COMPACT_RETRY",
26021
+ "AUTO_COMPACT_FALLBACK",
26022
+ "MESSAGE_TRANSFORM_APPLIED"
26023
+ ]);
26024
+ var AUTO_COMPACT_SINK_LISTENER_ID = "auto-compact-metrics-sink";
26025
+ var autoCompactSink = createAutoCompactMetricsSink();
26026
+ var sinkRegistered = false;
26027
+ function ensureAutoCompactTelemetryRegistered() {
26028
+ if (sinkRegistered) return;
26029
+ registerTelemetryListener(AUTO_COMPACT_SINK_LISTENER_ID, (event) => {
26030
+ if (!AUTO_COMPACT_TELEMETRY_PHASES.has(event.phase)) return;
26031
+ autoCompactSink.push({
26032
+ phase: event.phase,
26033
+ data: event.data
26034
+ });
26035
+ });
26036
+ sinkRegistered = true;
26037
+ }
26038
+ function emitAutoCompactTelemetryEvent(phase, data) {
26039
+ ensureAutoCompactTelemetryRegistered();
26040
+ emitTelemetryEvent({
26041
+ channel: "auto_compact",
26042
+ phase,
26043
+ data,
26044
+ timestamp: Date.now()
26045
+ });
26046
+ }
26047
+ function getAutoCompactMetricsSnapshot() {
26048
+ ensureAutoCompactTelemetryRegistered();
26049
+ return autoCompactSink.snapshot();
26050
+ }
26051
+ function resetAutoCompactTelemetry() {
26052
+ autoCompactSink.clear();
26053
+ }
26054
+ ensureAutoCompactTelemetryRegistered();
26055
+
26056
+ // src/services/ai/canonicalResponse/index.ts
26057
+ function normalizeModelResponseContent(content, context) {
26058
+ const textBlocks = [];
26059
+ const reasoningBlocks = [];
26060
+ const blockTypes = [];
26061
+ if (typeof content === "string") {
26062
+ const normalized = content.trim();
26063
+ if (normalized.length > 0) {
26064
+ textBlocks.push(normalized);
26065
+ blockTypes.push("string");
26066
+ }
26067
+ } else if (Array.isArray(content)) {
26068
+ for (const block of content) {
26069
+ if (!block || typeof block !== "object") {
26070
+ blockTypes.push(typeof block);
26071
+ continue;
26072
+ }
26073
+ const type3 = String(block.type ?? "unknown");
26074
+ blockTypes.push(type3);
26075
+ if (type3 === "text") {
26076
+ const text = String(block.text ?? "").trim();
26077
+ if (text.length > 0) {
26078
+ textBlocks.push(text);
26079
+ }
26080
+ continue;
26081
+ }
26082
+ if (type3 === "thinking" || type3 === "reasoning") {
26083
+ const reasoning = String(
26084
+ block.thinking ?? block.reasoning ?? ""
26085
+ ).trim();
26086
+ if (reasoning.length > 0) {
26087
+ reasoningBlocks.push(reasoning);
26088
+ }
26089
+ }
26090
+ }
26091
+ } else {
26092
+ blockTypes.push(typeof content);
26093
+ }
26094
+ const summaryText = textBlocks.length > 0 ? textBlocks.join("\n") : null;
26095
+ const fallbackSummary = summaryText === null && context.reasoningPolicy === "flatten_to_text_fallback" && reasoningBlocks.length > 0 ? reasoningBlocks.join("\n") : null;
26096
+ const finalSummaryText = summaryText ?? fallbackSummary;
26097
+ const result = {
26098
+ isValid: finalSummaryText !== null,
26099
+ summaryText: finalSummaryText,
26100
+ textBlocks,
26101
+ reasoningBlocks,
26102
+ blockTypes,
26103
+ ...finalSummaryText === null ? { failureType: "invalid_content_shape" } : {}
26104
+ };
26105
+ const payload = {
26106
+ source: context.source,
26107
+ model: context.model,
26108
+ provider: context.provider ?? "openai",
26109
+ isValid: result.isValid,
26110
+ failureType: result.failureType,
26111
+ reasoningPolicy: context.reasoningPolicy,
26112
+ policySource: context.policySource,
26113
+ textBlockCount: textBlocks.length,
26114
+ reasoningBlockCount: reasoningBlocks.length,
26115
+ blockTypes
26116
+ };
26117
+ debug.state("CANONICAL_RESPONSE_APPLIED", payload);
26118
+ emitTelemetryEvent({
26119
+ channel: "canonical_response",
26120
+ phase: "CANONICAL_RESPONSE_APPLIED",
26121
+ data: payload,
26122
+ timestamp: Date.now()
26123
+ });
26124
+ return result;
26125
+ }
26126
+
26127
+ // src/constants/modelCapabilities.ts
26128
+ var GPT5_CAPABILITIES = {
26129
+ apiArchitecture: {
26130
+ primary: "responses_api",
26131
+ fallback: "chat_completions"
26132
+ },
26133
+ parameters: {
26134
+ maxTokensField: "max_output_tokens",
26135
+ supportsReasoningEffort: true,
26136
+ supportsVerbosity: true,
26137
+ temperatureMode: "fixed_one"
26138
+ },
26139
+ toolCalling: {
26140
+ mode: "custom_tools",
26141
+ supportsFreeform: true,
26142
+ supportsAllowedTools: true,
26143
+ supportsParallelCalls: true
26144
+ },
26145
+ stateManagement: {
26146
+ supportsResponseId: true,
26147
+ supportsConversationChaining: true,
26148
+ supportsPreviousResponseId: true
26149
+ },
26150
+ streaming: {
26151
+ supported: true,
26152
+ includesUsage: true
26153
+ }
26154
+ };
26155
+ var CHAT_COMPLETIONS_CAPABILITIES = {
26156
+ apiArchitecture: {
26157
+ primary: "chat_completions"
26158
+ },
26159
+ parameters: {
26160
+ maxTokensField: "max_tokens",
26161
+ supportsReasoningEffort: false,
26162
+ supportsVerbosity: false,
26163
+ temperatureMode: "flexible"
26164
+ },
26165
+ toolCalling: {
26166
+ mode: "function_calling",
26167
+ supportsFreeform: false,
26168
+ supportsAllowedTools: false,
26169
+ supportsParallelCalls: true
26170
+ },
26171
+ stateManagement: {
26172
+ supportsResponseId: false,
26173
+ supportsConversationChaining: false,
26174
+ supportsPreviousResponseId: false
26175
+ },
26176
+ streaming: {
26177
+ supported: true,
26178
+ includesUsage: true
26179
+ }
26180
+ };
26181
+ var MODEL_CAPABILITIES_REGISTRY = {
26182
+ "gpt-5": GPT5_CAPABILITIES,
26183
+ "gpt-5-mini": GPT5_CAPABILITIES,
26184
+ "gpt-5-nano": GPT5_CAPABILITIES,
26185
+ "gpt-5-chat-latest": GPT5_CAPABILITIES,
26186
+ "gpt-5-codex": GPT5_CAPABILITIES,
26187
+ "gpt-4o": CHAT_COMPLETIONS_CAPABILITIES,
26188
+ "gpt-4o-mini": CHAT_COMPLETIONS_CAPABILITIES,
26189
+ "gpt-4-turbo": CHAT_COMPLETIONS_CAPABILITIES,
26190
+ "gpt-4": CHAT_COMPLETIONS_CAPABILITIES,
26191
+ "claude-3-5-sonnet-20241022": CHAT_COMPLETIONS_CAPABILITIES,
26192
+ "claude-3-5-haiku-20241022": CHAT_COMPLETIONS_CAPABILITIES,
26193
+ "claude-3-opus-20240229": CHAT_COMPLETIONS_CAPABILITIES,
26194
+ o1: {
26195
+ ...CHAT_COMPLETIONS_CAPABILITIES,
26196
+ parameters: {
26197
+ ...CHAT_COMPLETIONS_CAPABILITIES.parameters,
26198
+ maxTokensField: "max_completion_tokens",
26199
+ temperatureMode: "fixed_one"
26200
+ }
26201
+ },
26202
+ "o1-mini": {
26203
+ ...CHAT_COMPLETIONS_CAPABILITIES,
26204
+ parameters: {
26205
+ ...CHAT_COMPLETIONS_CAPABILITIES.parameters,
26206
+ maxTokensField: "max_completion_tokens",
26207
+ temperatureMode: "fixed_one"
26208
+ }
26209
+ },
26210
+ "o1-preview": {
26211
+ ...CHAT_COMPLETIONS_CAPABILITIES,
26212
+ parameters: {
26213
+ ...CHAT_COMPLETIONS_CAPABILITIES.parameters,
26214
+ maxTokensField: "max_completion_tokens",
26215
+ temperatureMode: "fixed_one"
26216
+ }
26217
+ }
26218
+ };
26219
+ function inferModelCapabilities(modelName) {
26220
+ if (!modelName) return null;
26221
+ const lowerName = modelName.toLowerCase();
26222
+ if (lowerName.includes("gpt-5") || lowerName.includes("gpt5")) {
26223
+ return GPT5_CAPABILITIES;
26224
+ }
26225
+ if (lowerName.includes("gpt-6") || lowerName.includes("gpt6")) {
26226
+ return {
26227
+ ...GPT5_CAPABILITIES,
26228
+ streaming: { supported: true, includesUsage: true }
26229
+ };
26230
+ }
26231
+ if (lowerName.includes("glm-5") || lowerName.includes("glm5")) {
26232
+ return {
26233
+ ...CHAT_COMPLETIONS_CAPABILITIES,
26234
+ toolCalling: {
26235
+ ...CHAT_COMPLETIONS_CAPABILITIES.toolCalling,
26236
+ supportsAllowedTools: false
26237
+ }
26238
+ };
26239
+ }
26240
+ if (lowerName.startsWith("o1") || lowerName.includes("o1-")) {
26241
+ return {
26242
+ ...CHAT_COMPLETIONS_CAPABILITIES,
26243
+ parameters: {
26244
+ ...CHAT_COMPLETIONS_CAPABILITIES.parameters,
26245
+ maxTokensField: "max_completion_tokens",
26246
+ temperatureMode: "fixed_one"
26247
+ }
26248
+ };
26249
+ }
26250
+ return null;
26251
+ }
26252
+ var capabilityCache = /* @__PURE__ */ new Map();
26253
+ function getModelCapabilities(modelName) {
26254
+ if (capabilityCache.has(modelName)) {
26255
+ return capabilityCache.get(modelName);
26256
+ }
26257
+ if (MODEL_CAPABILITIES_REGISTRY[modelName]) {
26258
+ const capabilities = MODEL_CAPABILITIES_REGISTRY[modelName];
26259
+ capabilityCache.set(modelName, capabilities);
26260
+ return capabilities;
26261
+ }
26262
+ const inferred = inferModelCapabilities(modelName);
26263
+ if (inferred) {
26264
+ capabilityCache.set(modelName, inferred);
26265
+ return inferred;
26266
+ }
26267
+ const defaultCapabilities = CHAT_COMPLETIONS_CAPABILITIES;
26268
+ capabilityCache.set(modelName, defaultCapabilities);
26269
+ return defaultCapabilities;
26270
+ }
26271
+
26272
+ // src/services/ai/policyDispatch/policyConfigLoader.ts
26273
+ import { existsSync as existsSync15, readFileSync as readFileSync11 } from "fs";
26274
+ import { join as join12, resolve as resolve9 } from "path";
26275
+
26276
+ // src/services/ai/policyDispatch/policyConfigSchema.ts
26277
+ import { z as z11 } from "zod";
26278
+ var policyConfigSchema = z11.object({
26279
+ version: z11.string().min(1),
26280
+ defaults: z11.object({
26281
+ reasoningPolicy: z11.enum([
26282
+ "preserve_reasoning_blocks",
26283
+ "map_to_provider_options",
26284
+ "flatten_to_text_fallback"
26285
+ ]).optional(),
26286
+ normalizeProviderContent: z11.boolean().optional(),
26287
+ trimCrossModelMetadata: z11.boolean().optional()
26288
+ }).optional(),
26289
+ overrides: z11.array(
26290
+ z11.object({
26291
+ model: z11.string().min(1).optional(),
26292
+ modelFamily: z11.string().min(1).optional(),
26293
+ provider: z11.string().min(1).optional(),
26294
+ scenario: z11.enum(["query", "auto_compact", "other"]).optional(),
26295
+ reasoningPolicy: z11.enum([
26296
+ "preserve_reasoning_blocks",
26297
+ "map_to_provider_options",
26298
+ "flatten_to_text_fallback"
26299
+ ]).optional(),
26300
+ normalizeProviderContent: z11.boolean().optional(),
26301
+ trimCrossModelMetadata: z11.boolean().optional()
26302
+ })
26303
+ ).optional().default([])
26304
+ });
26305
+
26306
+ // src/services/ai/policyDispatch/policyConfigLoader.ts
26307
+ function getModelFamily(model) {
26308
+ const normalized = String(model || "").toLowerCase();
26309
+ if (normalized.startsWith("gpt-5")) return "gpt-5";
26310
+ if (normalized.startsWith("gpt-4o")) return "gpt-4o";
26311
+ if (!normalized) return "unknown";
26312
+ const segments = normalized.split("-");
26313
+ return segments.length >= 2 ? `${segments[0]}-${segments[1]}` : normalized;
26314
+ }
26315
+ function getDefaultPolicyConfigPath() {
26316
+ return resolve9(join12(process.cwd(), "config/auto-compact-policy.config.json"));
26317
+ }
26318
+ function loadAutoCompactPolicyConfig(options) {
26319
+ const filePath = resolve9(options?.filePath ?? getDefaultPolicyConfigPath());
26320
+ if (!existsSync15(filePath)) return null;
26321
+ try {
26322
+ const raw = readFileSync11(filePath, "utf8");
26323
+ const parsed = JSON.parse(raw);
26324
+ return policyConfigSchema.parse(parsed);
26325
+ } catch {
26326
+ return null;
26327
+ }
26328
+ }
26329
+ function matches(input, override) {
26330
+ if (override.model && override.model !== input.model) return false;
26331
+ if (override.modelFamily && override.modelFamily !== getModelFamily(input.model))
26332
+ return false;
26333
+ if (override.provider && override.provider !== input.provider) return false;
26334
+ if (override.scenario && override.scenario !== input.source) return false;
26335
+ return true;
26336
+ }
26337
+ function selectPolicyOverride(input, config2) {
26338
+ const matched = [...config2.overrides ?? []].reverse().find((item) => matches(input, item));
26339
+ if (matched) {
26340
+ return {
26341
+ reasoningPolicy: matched.reasoningPolicy,
26342
+ normalizeProviderContent: matched.normalizeProviderContent,
26343
+ trimCrossModelMetadata: matched.trimCrossModelMetadata
26344
+ };
26345
+ }
26346
+ if (config2.defaults) {
26347
+ return {
26348
+ reasoningPolicy: config2.defaults.reasoningPolicy,
26349
+ normalizeProviderContent: config2.defaults.normalizeProviderContent,
26350
+ trimCrossModelMetadata: config2.defaults.trimCrossModelMetadata
26351
+ };
26352
+ }
26353
+ return null;
26354
+ }
26355
+
26356
+ // src/services/ai/policyDispatch/index.ts
26357
+ function resolveDefaultReasoningPolicy(model) {
26358
+ const capabilities = getModelCapabilities(model);
26359
+ if (capabilities.apiArchitecture.primary === "responses_api") {
26360
+ return "map_to_provider_options";
26361
+ }
26362
+ return "preserve_reasoning_blocks";
26363
+ }
26364
+ function resolveDefaultNormalizeProviderContent(model) {
26365
+ const capabilities = getModelCapabilities(model);
26366
+ return capabilities.apiArchitecture.primary === "responses_api";
26367
+ }
26368
+ function resolveDefaultTrimCrossModelMetadata(model) {
26369
+ const capabilities = getModelCapabilities(model);
26370
+ return capabilities.apiArchitecture.primary === "responses_api";
26371
+ }
26372
+ function resolveCapabilityDefaults(model) {
26373
+ return {
26374
+ reasoningPolicy: resolveDefaultReasoningPolicy(model),
26375
+ normalizeProviderContent: resolveDefaultNormalizeProviderContent(model),
26376
+ trimCrossModelMetadata: resolveDefaultTrimCrossModelMetadata(model)
26377
+ };
26378
+ }
26379
+ function resolveModelResponsePolicy(input) {
26380
+ const defaults = resolveCapabilityDefaults(input.model);
26381
+ const hasOverride = input.reasoningPolicy !== void 0 || input.normalizeProviderContent !== void 0 || input.trimCrossModelMetadata !== void 0;
26382
+ if (hasOverride) {
26383
+ return {
26384
+ reasoningPolicy: input.reasoningPolicy ?? defaults.reasoningPolicy,
26385
+ normalizeProviderContent: input.normalizeProviderContent ?? defaults.normalizeProviderContent,
26386
+ trimCrossModelMetadata: input.trimCrossModelMetadata ?? defaults.trimCrossModelMetadata,
26387
+ policySource: "context_override"
26388
+ };
26389
+ }
26390
+ const config2 = loadAutoCompactPolicyConfig();
26391
+ const selection = config2 ? selectPolicyOverride(input, config2) : null;
26392
+ if (selection && (selection.reasoningPolicy !== void 0 || selection.normalizeProviderContent !== void 0 || selection.trimCrossModelMetadata !== void 0)) {
26393
+ return {
26394
+ reasoningPolicy: selection.reasoningPolicy ?? defaults.reasoningPolicy,
26395
+ normalizeProviderContent: selection.normalizeProviderContent ?? defaults.normalizeProviderContent,
26396
+ trimCrossModelMetadata: selection.trimCrossModelMetadata ?? defaults.trimCrossModelMetadata,
26397
+ policySource: "policy_config"
26398
+ };
26399
+ }
26400
+ return {
26401
+ reasoningPolicy: defaults.reasoningPolicy,
26402
+ normalizeProviderContent: defaults.normalizeProviderContent,
26403
+ trimCrossModelMetadata: defaults.trimCrossModelMetadata,
26404
+ policySource: "model_capabilities"
26405
+ };
26406
+ }
26407
+
26408
+ // src/services/ai/streamTyped/partTypes.ts
26409
+ import { z as z12 } from "zod";
26410
+ var SOURCE_VALUES = ["auto_compact"];
26411
+ var TOOL_STATUS_VALUES = ["pending", "running", "completed", "failed", "interrupted"];
26412
+ var textPayloadSchema = z12.object({
26413
+ text: z12.string().min(1)
26414
+ });
26415
+ var reasoningPayloadSchema = z12.object({
26416
+ text: z12.string().min(1)
26417
+ });
26418
+ var toolPayloadSchema = z12.object({
26419
+ toolName: z12.string().min(1),
26420
+ toolCallId: z12.string().min(1),
26421
+ status: z12.enum(TOOL_STATUS_VALUES),
26422
+ outputText: z12.string().optional()
26423
+ });
26424
+ var streamTypedPartBaseSchema = z12.object({
26425
+ id: z12.string().min(1),
26426
+ requestId: z12.string().min(1),
26427
+ source: z12.enum(SOURCE_VALUES),
26428
+ timestamp: z12.number().int().positive()
26429
+ });
26430
+ var streamTypedPartSchema = z12.discriminatedUnion("partType", [
26431
+ streamTypedPartBaseSchema.extend({
26432
+ partType: z12.literal("text"),
26433
+ payload: textPayloadSchema
26434
+ }),
26435
+ streamTypedPartBaseSchema.extend({
26436
+ partType: z12.literal("reasoning"),
26437
+ payload: reasoningPayloadSchema
26438
+ }),
26439
+ streamTypedPartBaseSchema.extend({
26440
+ partType: z12.literal("tool"),
26441
+ payload: toolPayloadSchema
26442
+ })
26443
+ ]);
26444
+ function createId() {
26445
+ return `stp_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
26446
+ }
26447
+ function createBase(input) {
26448
+ return {
26449
+ id: createId(),
26450
+ requestId: input.requestId,
26451
+ source: "auto_compact",
26452
+ timestamp: Date.now()
26453
+ };
26454
+ }
26455
+ function createTextPart(input) {
26456
+ return streamTypedPartSchema.parse({
26457
+ ...createBase(input),
26458
+ partType: "text",
26459
+ payload: {
26460
+ text: input.text.trim()
26461
+ }
26462
+ });
26463
+ }
26464
+ function createReasoningPart(input) {
26465
+ return streamTypedPartSchema.parse({
26466
+ ...createBase(input),
26467
+ partType: "reasoning",
26468
+ payload: {
26469
+ text: input.text.trim()
26470
+ }
26471
+ });
26472
+ }
26473
+ function createToolPart(input) {
26474
+ return streamTypedPartSchema.parse({
26475
+ ...createBase(input),
26476
+ partType: "tool",
26477
+ payload: {
26478
+ toolName: input.toolName,
26479
+ toolCallId: input.toolCallId,
26480
+ status: input.status,
26481
+ ...input.outputText ? { outputText: input.outputText } : {}
26482
+ }
26483
+ });
26484
+ }
26485
+
26486
+ // src/services/ai/streamTyped/eventAssembler.ts
26487
+ function createAssemblerState(requestId) {
26488
+ return {
26489
+ requestId,
26490
+ parts: [],
26491
+ textBuffer: {},
26492
+ reasoningBuffer: {},
26493
+ toolMap: {}
26494
+ };
26495
+ }
26496
+ function onTextStart(event, state) {
26497
+ state.textBuffer[event.textId] = "";
26498
+ }
26499
+ function onTextDelta(event, state) {
26500
+ const current = state.textBuffer[event.textId] ?? "";
26501
+ state.textBuffer[event.textId] = `${current}${event.text}`;
26502
+ }
26503
+ function onTextEnd(event, state) {
26504
+ const text = String(state.textBuffer[event.textId] ?? "").trim();
26505
+ delete state.textBuffer[event.textId];
26506
+ if (!text) return;
26507
+ state.parts.push(
26508
+ createTextPart({
26509
+ requestId: state.requestId,
26510
+ text
26511
+ })
26512
+ );
26513
+ }
26514
+ function onReasoningStart(event, state) {
26515
+ state.reasoningBuffer[event.reasoningId] = "";
26516
+ }
26517
+ function onReasoningDelta(event, state) {
26518
+ const current = state.reasoningBuffer[event.reasoningId] ?? "";
26519
+ state.reasoningBuffer[event.reasoningId] = `${current}${event.text}`;
26520
+ }
26521
+ function onReasoningEnd(event, state) {
26522
+ const text = String(state.reasoningBuffer[event.reasoningId] ?? "").trim();
26523
+ delete state.reasoningBuffer[event.reasoningId];
26524
+ if (!text) return;
26525
+ state.parts.push(
26526
+ createReasoningPart({
26527
+ requestId: state.requestId,
26528
+ text
26529
+ })
26530
+ );
26531
+ }
26532
+ function onToolCall(event, state) {
26533
+ state.toolMap[event.toolCallId] = { toolName: event.toolName };
26534
+ }
26535
+ function onToolResult(event, state) {
26536
+ const toolName = state.toolMap[event.toolCallId]?.toolName ?? "unknown";
26537
+ state.parts.push(
26538
+ createToolPart({
26539
+ requestId: state.requestId,
26540
+ toolName,
26541
+ toolCallId: event.toolCallId,
26542
+ status: event.status,
26543
+ outputText: event.outputText
26544
+ })
26545
+ );
26546
+ delete state.toolMap[event.toolCallId];
26547
+ }
26548
+ function flushTypedParts(state) {
26549
+ const parts = state.parts.slice();
26550
+ state.parts.length = 0;
26551
+ return parts;
26552
+ }
26553
+
26554
+ // src/services/ai/streamTyped/partStore.ts
26555
+ import { appendFileSync, existsSync as existsSync16, mkdirSync as mkdirSync7, readFileSync as readFileSync12 } from "fs";
26556
+ import { dirname as dirname9 } from "path";
26557
+ function getStreamTypedOutputFilePath() {
26558
+ return resolveXdgCachePath("telemetry/stream-typed-parts.jsonl");
26559
+ }
26560
+ function validateTypedPartRecord(record) {
26561
+ return streamTypedPartSchema.safeParse(record).success;
26562
+ }
26563
+ function readAllValidParts(outputFilePath) {
26564
+ if (!existsSync16(outputFilePath)) return [];
26565
+ const raw = readFileSync12(outputFilePath, "utf8");
26566
+ const lines = raw.split("\n").map((line) => line.trim()).filter(Boolean);
26567
+ const parts = [];
26568
+ for (const line of lines) {
26569
+ try {
26570
+ const parsed = JSON.parse(line);
26571
+ if (!validateTypedPartRecord(parsed)) continue;
26572
+ parts.push(parsed);
26573
+ } catch {
26574
+ continue;
26575
+ }
26576
+ }
26577
+ return parts;
26578
+ }
26579
+ function appendTypedParts(options) {
26580
+ if (!Array.isArray(options.parts) || options.parts.length === 0) {
26581
+ return { appended: 0 };
26582
+ }
26583
+ const outputFilePath = options.outputFilePath ?? getStreamTypedOutputFilePath();
26584
+ if (!existsSync16(dirname9(outputFilePath))) {
26585
+ mkdirSync7(dirname9(outputFilePath), { recursive: true });
26586
+ }
26587
+ const existingIds = new Set(readAllValidParts(outputFilePath).map((item) => item.id));
26588
+ const toAppend = options.parts.filter(
26589
+ (item) => validateTypedPartRecord(item) && !existingIds.has(item.id)
26590
+ );
26591
+ if (toAppend.length === 0) return { appended: 0 };
26592
+ appendFileSync(
26593
+ outputFilePath,
26594
+ `${toAppend.map((item) => JSON.stringify(item)).join("\n")}
26595
+ `
26596
+ );
26597
+ return { appended: toAppend.length };
26598
+ }
26599
+
26600
+ // src/services/ai/streamTyped/index.ts
26601
+ var streamTypedBuffer = /* @__PURE__ */ new Map();
26602
+ function emitTypedPart(event) {
26603
+ const requestId = String(event.requestId || "").trim();
26604
+ if (!requestId) return;
26605
+ const current = streamTypedBuffer.get(requestId) ?? [];
26606
+ current.push(event.part);
26607
+ streamTypedBuffer.set(requestId, current);
26608
+ }
26609
+ function flushTypedPartBuffer(options) {
26610
+ const requestId = String(options.requestId || "").trim();
26611
+ if (!requestId) return { appended: 0 };
26612
+ const parts = streamTypedBuffer.get(requestId) ?? [];
26613
+ streamTypedBuffer.delete(requestId);
26614
+ return appendTypedParts({
26615
+ outputFilePath: options.outputFilePath,
26616
+ parts
26617
+ });
26618
+ }
26619
+
26620
+ // src/services/ai/streamTyped/replay.ts
26621
+ function toNonEmptyText(value) {
26622
+ const text = String(value ?? "").trim();
26623
+ return text.length > 0 ? text : null;
26624
+ }
26625
+ function buildSummaryFromTypedParts(parts) {
26626
+ const textBlocks = [];
26627
+ let reasoningPartCount = 0;
26628
+ for (const part of parts) {
26629
+ if (!part || typeof part !== "object") continue;
26630
+ if (part.partType === "reasoning") {
26631
+ reasoningPartCount += 1;
26632
+ continue;
26633
+ }
26634
+ if (part.partType !== "text") continue;
26635
+ const text = toNonEmptyText(part.payload?.text);
26636
+ if (text) textBlocks.push(text);
26637
+ }
26638
+ if (textBlocks.length === 0) {
26639
+ return {
26640
+ isComplete: false,
26641
+ summaryText: null,
26642
+ reason: "no_text_parts",
26643
+ textPartCount: 0,
26644
+ reasoningPartCount
26645
+ };
26646
+ }
26647
+ return {
26648
+ isComplete: true,
26649
+ summaryText: textBlocks.join("\n"),
26650
+ reason: "typed_text_joined",
26651
+ textPartCount: textBlocks.length,
26652
+ reasoningPartCount
26653
+ };
26654
+ }
26655
+ function resolveTypedReplayResult(input) {
26656
+ if (!input.enabled) {
26657
+ return {
26658
+ isComplete: false,
26659
+ summaryText: null,
26660
+ reason: "typed_read_disabled",
26661
+ textPartCount: 0,
26662
+ reasoningPartCount: 0
26663
+ };
26664
+ }
26665
+ return buildSummaryFromTypedParts(input.parts ?? []);
26666
+ }
26667
+
26668
+ // src/utils/session/autoCompactFailurePolicy.ts
26669
+ var AUTO_COMPACT_CLASSIFICATION_VERSION = "c1-v1";
26670
+ function getFailureStatus(error) {
26671
+ const status = error?.status;
26672
+ if (typeof status === "number") return status;
26673
+ return void 0;
26674
+ }
26675
+ function classifyAutoCompactFailure(error) {
26676
+ const message = error instanceof Error ? error.message : String(error ?? "Unknown error");
26677
+ const status = getFailureStatus(error);
26678
+ const lower = message.toLowerCase();
26679
+ if (lower.includes("did not contain valid text content") || lower.includes("invalid content shape")) {
26680
+ return { failureType: "invalid_content_shape", message, status };
26681
+ }
26682
+ if (typeof status === "number" && status >= 500 || /\bhttp\s+5\d\d\b/i.test(message)) {
26683
+ return { failureType: "provider_5xx", message, status };
26684
+ }
26685
+ if (lower.includes("not configured") || lower.includes("misconfigured") || lower.includes("fallback failed")) {
26686
+ return { failureType: "model_misconfigured", message, status };
26687
+ }
26688
+ return { failureType: "unknown", message, status };
26689
+ }
26690
+ function decideAutoCompactRecovery(params) {
26691
+ const hasNextAttempt = params.attempt < params.maxAttempts;
26692
+ if (!hasNextAttempt) return "abort";
26693
+ if (params.failureType === "invalid_content_shape") return "retry_reextract";
26694
+ if (params.failureType === "provider_5xx") return "retry_backoff";
26695
+ if (params.failureType === "model_misconfigured" && params.activeModelPointer === "compact" && params.hasMainModelProfile) {
26696
+ return "fallback_main";
26697
+ }
26698
+ return "abort";
26699
+ }
26700
+ function getStatusBucket(status) {
26701
+ if (typeof status !== "number") return "none";
26702
+ if (status >= 500 && status <= 599) return "5xx";
26703
+ if (status >= 400 && status <= 499) return "4xx";
26704
+ return "other";
26705
+ }
26706
+ function buildAutoCompactAggregationFields(params) {
26707
+ const statusBucket = getStatusBucket(params.status);
26708
+ const modelPointer = params.modelPointer ?? "unknown";
26709
+ return {
26710
+ source: "auto_compact",
26711
+ classificationVersion: AUTO_COMPACT_CLASSIFICATION_VERSION,
26712
+ failureType: params.failureType,
26713
+ status: params.status,
26714
+ statusBucket,
26715
+ modelPointer,
26716
+ aggregateKey: `auto_compact:${params.failureType}:${modelPointer}:${statusBucket}`
26717
+ };
26718
+ }
26719
+
25931
26720
  // src/utils/session/autoCompactCore.ts
25932
26721
  async function getMainConversationContextLimit() {
25933
26722
  try {
@@ -25977,6 +26766,10 @@ var CONVERSATION_SUMMARY_LIMITS = {
25977
26766
  maxTotalChars: 2e3
25978
26767
  };
25979
26768
  var MAX_COMPACTED_QUERY_IDS = 10;
26769
+ var AUTO_COMPACT_CHAIN_RETRY_DELAY_MS = 250;
26770
+ function wait(ms) {
26771
+ return new Promise((resolve12) => setTimeout(resolve12, ms));
26772
+ }
25980
26773
  function getMessageText(message) {
25981
26774
  if (!message || typeof message !== "object") return null;
25982
26775
  if (message.type !== "user" && message.type !== "assistant") return null;
@@ -26049,6 +26842,94 @@ function getSummaryContentDiagnostics(content) {
26049
26842
  value: content
26050
26843
  };
26051
26844
  }
26845
+ function extractToolResultText(content) {
26846
+ if (typeof content === "string") return content;
26847
+ if (!Array.isArray(content)) return "";
26848
+ return content.filter((block) => block && typeof block === "object" && block.type === "text").map((block) => String(block.text ?? "")).join("\n");
26849
+ }
26850
+ function parseBooleanFlag(value) {
26851
+ const raw = String(value ?? "").trim().toLowerCase();
26852
+ if (["1", "true", "yes", "on"].includes(raw)) return true;
26853
+ if (["0", "false", "no", "off"].includes(raw)) return false;
26854
+ return null;
26855
+ }
26856
+ function resolveTypedReadPathConfig(toolUseContext) {
26857
+ const envValue = parseBooleanFlag(
26858
+ process.env.PYB_AUTO_COMPACT_TYPED_READ_PATH_ENABLED
26859
+ );
26860
+ if (envValue !== null) {
26861
+ return {
26862
+ enabled: envValue,
26863
+ source: "env"
26864
+ };
26865
+ }
26866
+ if (typeof toolUseContext?.typedPathEnabled === "boolean") {
26867
+ return {
26868
+ enabled: toolUseContext.typedPathEnabled,
26869
+ source: "context"
26870
+ };
26871
+ }
26872
+ return {
26873
+ enabled: false,
26874
+ source: "default"
26875
+ };
26876
+ }
26877
+ function normalizeSummaryForComparison(summary) {
26878
+ return String(summary ?? "").replace(/\r\n/g, "\n").replace(/[ \t]+/g, " ").split("\n").map((line) => line.trim()).join("\n").trim();
26879
+ }
26880
+ function emitStreamTypedPartsFromContent(content, requestId) {
26881
+ const state = createAssemblerState(requestId);
26882
+ if (typeof content === "string") {
26883
+ onTextStart({ textId: "text-0" }, state);
26884
+ onTextDelta({ textId: "text-0", text: content }, state);
26885
+ onTextEnd({ textId: "text-0" }, state);
26886
+ } else if (Array.isArray(content)) {
26887
+ for (let i = 0; i < content.length; i += 1) {
26888
+ const block = content[i];
26889
+ if (!block || typeof block !== "object") continue;
26890
+ const type3 = String(block.type ?? "");
26891
+ if (type3 === "text") {
26892
+ const text = String(block.text ?? "");
26893
+ onTextStart({ textId: `text-${i}` }, state);
26894
+ onTextDelta({ textId: `text-${i}`, text }, state);
26895
+ onTextEnd({ textId: `text-${i}` }, state);
26896
+ continue;
26897
+ }
26898
+ if (type3 === "thinking" || type3 === "reasoning") {
26899
+ const text = String(
26900
+ block.thinking ?? block.reasoning ?? ""
26901
+ );
26902
+ onReasoningStart({ reasoningId: `reasoning-${i}` }, state);
26903
+ onReasoningDelta({ reasoningId: `reasoning-${i}`, text }, state);
26904
+ onReasoningEnd({ reasoningId: `reasoning-${i}` }, state);
26905
+ continue;
26906
+ }
26907
+ if (type3 === "tool_use") {
26908
+ const toolCallId = String(block.id ?? `tool-${i}`);
26909
+ const toolName = String(block.name ?? "unknown");
26910
+ onToolCall({ toolCallId, toolName }, state);
26911
+ continue;
26912
+ }
26913
+ if (type3 === "tool_result") {
26914
+ const toolCallId = String(block.tool_use_id ?? `tool-${i}`);
26915
+ const outputText = extractToolResultText(block.content);
26916
+ onToolResult(
26917
+ {
26918
+ toolCallId,
26919
+ status: block.is_error ? "failed" : "completed",
26920
+ outputText
26921
+ },
26922
+ state
26923
+ );
26924
+ }
26925
+ }
26926
+ }
26927
+ const emittedParts = flushTypedParts(state);
26928
+ for (const part of emittedParts) {
26929
+ emitTypedPart({ requestId, part });
26930
+ }
26931
+ return emittedParts;
26932
+ }
26052
26933
  async function checkAutoCompact(messages, toolUseContext) {
26053
26934
  if (!await shouldAutoCompact(messages)) {
26054
26935
  return { messages, wasCompacted: false };
@@ -26070,14 +26951,28 @@ async function checkAutoCompact(messages, toolUseContext) {
26070
26951
  wasCompacted: true
26071
26952
  };
26072
26953
  } catch (error) {
26073
- logError(error);
26074
- debug.warn("AUTO_COMPACT_FAILED", {
26075
- error: error instanceof Error ? error.message : String(error)
26954
+ const classified = classifyAutoCompactFailure(error);
26955
+ const aggregation = buildAutoCompactAggregationFields({
26956
+ failureType: classified.failureType,
26957
+ status: classified.status,
26958
+ modelPointer: error?.modelPointer
26076
26959
  });
26960
+ const failurePayload = {
26961
+ error: classified.message,
26962
+ failureType: classified.failureType,
26963
+ status: classified.status,
26964
+ modelPointer: error?.modelPointer,
26965
+ attempts: error?.attempts,
26966
+ ...aggregation
26967
+ };
26968
+ logError(error);
26969
+ debug.warn("AUTO_COMPACT_FAILED", failurePayload);
26970
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_FAILED", failurePayload);
26077
26971
  return { messages, wasCompacted: false };
26078
26972
  }
26079
26973
  }
26080
26974
  async function executeAutoCompact(messages, toolUseContext, options) {
26975
+ const typedRequestId = `auto_compact_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
26081
26976
  const previousSummary = findLatestAutoCompactSummary(messages);
26082
26977
  const summaryRequestContent = previousSummary ? `We already have an existing conversation summary:
26083
26978
 
@@ -26113,30 +27008,201 @@ ${COMPRESSION_PROMPT2}` : COMPRESSION_PROMPT2;
26113
27008
  mainResolution.error || "Compression fallback failed: model pointer 'main' is not configured."
26114
27009
  );
26115
27010
  }
26116
- const summaryResponse = await queryLLM(
26117
- normalizeMessagesForAPI([...messagesForSummary, summaryRequest]),
26118
- [
26119
- "You are a helpful AI assistant tasked with creating comprehensive conversation summaries that preserve all essential context for continuing development work."
26120
- ],
26121
- 0,
26122
- [],
26123
- toolUseContext.abortController.signal,
26124
- {
26125
- safeMode: false,
26126
- model: compressionModelPointer,
26127
- prependCLISysprompt: true
27011
+ let summaryResponse = null;
27012
+ let attempts = 0;
27013
+ let activeModelPointer = compressionModelPointer;
27014
+ const typedPath = resolveTypedReadPathConfig(toolUseContext);
27015
+ while (attempts < 2) {
27016
+ attempts += 1;
27017
+ try {
27018
+ const summaryCandidate = await queryLLM(
27019
+ normalizeMessagesForAPI([...messagesForSummary, summaryRequest]),
27020
+ [
27021
+ "You are a helpful AI assistant tasked with creating comprehensive conversation summaries that preserve all essential context for continuing development work."
27022
+ ],
27023
+ 0,
27024
+ [],
27025
+ toolUseContext.abortController.signal,
27026
+ {
27027
+ safeMode: false,
27028
+ model: activeModelPointer,
27029
+ prependCLISysprompt: true,
27030
+ firstMode: toolUseContext?.firstMode
27031
+ }
27032
+ );
27033
+ const content = summaryCandidate.message.content;
27034
+ const activeModelName = activeModelPointer === "compact" ? compactResolution.success && compactResolution.profile ? compactResolution.profile.name : "compact" : mainResolution.success && mainResolution.profile ? mainResolution.profile.name : "main";
27035
+ const resolvedPolicy = resolveModelResponsePolicy({
27036
+ source: "auto_compact",
27037
+ model: activeModelName,
27038
+ provider: "openai"
27039
+ });
27040
+ const canonicalResult = normalizeModelResponseContent(content, {
27041
+ source: "auto_compact",
27042
+ model: activeModelName,
27043
+ provider: "openai",
27044
+ reasoningPolicy: resolvedPolicy.reasoningPolicy,
27045
+ policySource: resolvedPolicy.policySource
27046
+ });
27047
+ let emittedTypedParts = [];
27048
+ try {
27049
+ emittedTypedParts = emitStreamTypedPartsFromContent(content, typedRequestId);
27050
+ } catch {
27051
+ }
27052
+ const typedReplay = resolveTypedReplayResult({
27053
+ enabled: typedPath.enabled,
27054
+ parts: emittedTypedParts
27055
+ });
27056
+ const canonicalSummary = canonicalResult.summaryText;
27057
+ let summary = canonicalSummary;
27058
+ if (typedPath.enabled && typedReplay.isComplete && typedReplay.summaryText) {
27059
+ summary = typedReplay.summaryText;
27060
+ const typedAppliedPayload = {
27061
+ mode: "typed",
27062
+ pathSource: typedPath.source,
27063
+ reason: typedReplay.reason,
27064
+ textPartCount: typedReplay.textPartCount,
27065
+ reasoningPartCount: typedReplay.reasoningPartCount
27066
+ };
27067
+ debug.warn("AUTO_COMPACT_TYPED_PATH_APPLIED", typedAppliedPayload);
27068
+ emitAutoCompactTelemetryEvent(
27069
+ "AUTO_COMPACT_TYPED_PATH_APPLIED",
27070
+ typedAppliedPayload
27071
+ );
27072
+ if (normalizeSummaryForComparison(canonicalSummary) !== normalizeSummaryForComparison(summary)) {
27073
+ const divergencePayload = {
27074
+ canonicalLength: String(canonicalSummary ?? "").length,
27075
+ typedLength: String(summary ?? "").length
27076
+ };
27077
+ debug.warn(
27078
+ "AUTO_COMPACT_TYPED_SUMMARY_DIVERGENCE",
27079
+ divergencePayload
27080
+ );
27081
+ emitAutoCompactTelemetryEvent(
27082
+ "AUTO_COMPACT_TYPED_SUMMARY_DIVERGENCE",
27083
+ divergencePayload
27084
+ );
27085
+ }
27086
+ } else if (typedPath.enabled) {
27087
+ const typedAppliedPayload = {
27088
+ mode: "canonical_fallback",
27089
+ pathSource: typedPath.source,
27090
+ reason: typedReplay.reason,
27091
+ textPartCount: typedReplay.textPartCount,
27092
+ reasoningPartCount: typedReplay.reasoningPartCount
27093
+ };
27094
+ debug.warn("AUTO_COMPACT_TYPED_PATH_APPLIED", typedAppliedPayload);
27095
+ emitAutoCompactTelemetryEvent(
27096
+ "AUTO_COMPACT_TYPED_PATH_APPLIED",
27097
+ typedAppliedPayload
27098
+ );
27099
+ } else {
27100
+ const typedAppliedPayload = {
27101
+ mode: "canonical_disabled",
27102
+ pathSource: typedPath.source
27103
+ };
27104
+ debug.warn("AUTO_COMPACT_TYPED_PATH_APPLIED", typedAppliedPayload);
27105
+ emitAutoCompactTelemetryEvent(
27106
+ "AUTO_COMPACT_TYPED_PATH_APPLIED",
27107
+ typedAppliedPayload
27108
+ );
27109
+ }
27110
+ if (!summary) {
27111
+ debug.warn("AUTO_COMPACT_SUMMARY_CONTENT_INVALID", {
27112
+ model: activeModelPointer,
27113
+ diagnostics: getSummaryContentDiagnostics(content),
27114
+ canonicalDiagnostics: {
27115
+ textBlockCount: canonicalResult.textBlocks.length,
27116
+ reasoningBlockCount: canonicalResult.reasoningBlocks.length,
27117
+ blockTypes: canonicalResult.blockTypes,
27118
+ failureType: canonicalResult.failureType
27119
+ },
27120
+ attempt: attempts
27121
+ });
27122
+ throw new Error(
27123
+ "Failed to generate conversation summary - response did not contain valid text content"
27124
+ );
27125
+ }
27126
+ summaryResponse = summaryCandidate;
27127
+ break;
27128
+ } catch (error) {
27129
+ const classified = classifyAutoCompactFailure(error);
27130
+ const recoveryAction = decideAutoCompactRecovery({
27131
+ failureType: classified.failureType,
27132
+ attempt: attempts,
27133
+ maxAttempts: 2,
27134
+ activeModelPointer,
27135
+ hasMainModelProfile: Boolean(mainResolution.success && mainResolution.profile)
27136
+ });
27137
+ if (recoveryAction === "retry_reextract") {
27138
+ const aggregation = buildAutoCompactAggregationFields({
27139
+ failureType: classified.failureType,
27140
+ status: classified.status,
27141
+ modelPointer: activeModelPointer
27142
+ });
27143
+ const retryPayload = {
27144
+ failureType: classified.failureType,
27145
+ attempt: attempts,
27146
+ strategy: "reextract_once",
27147
+ ...aggregation
27148
+ };
27149
+ debug.warn("AUTO_COMPACT_RETRY", retryPayload);
27150
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_RETRY", retryPayload);
27151
+ continue;
27152
+ }
27153
+ if (recoveryAction === "retry_backoff") {
27154
+ const aggregation = buildAutoCompactAggregationFields({
27155
+ failureType: classified.failureType,
27156
+ status: classified.status,
27157
+ modelPointer: activeModelPointer
27158
+ });
27159
+ const retryPayload = {
27160
+ failureType: classified.failureType,
27161
+ attempt: attempts,
27162
+ status: classified.status,
27163
+ strategy: "retry_with_backoff",
27164
+ ...aggregation
27165
+ };
27166
+ debug.warn("AUTO_COMPACT_RETRY", retryPayload);
27167
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_RETRY", retryPayload);
27168
+ await wait(AUTO_COMPACT_CHAIN_RETRY_DELAY_MS);
27169
+ continue;
27170
+ }
27171
+ if (recoveryAction === "fallback_main") {
27172
+ activeModelPointer = "main";
27173
+ if (!compressionNotice) {
27174
+ compressionNotice = "Compression fallback applied: compact model unavailable, switched to 'main'.";
27175
+ }
27176
+ const aggregation = buildAutoCompactAggregationFields({
27177
+ failureType: classified.failureType,
27178
+ status: classified.status,
27179
+ modelPointer: "compact"
27180
+ });
27181
+ const fallbackPayload = {
27182
+ failureType: classified.failureType,
27183
+ attempt: attempts,
27184
+ fromModel: "compact",
27185
+ toModel: "main",
27186
+ ...aggregation
27187
+ };
27188
+ debug.warn("AUTO_COMPACT_FALLBACK", fallbackPayload);
27189
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_FALLBACK", fallbackPayload);
27190
+ continue;
27191
+ }
27192
+ const toThrow = error instanceof Error ? error : new Error(String(error));
27193
+ toThrow.failureType = classified.failureType;
27194
+ toThrow.status = classified.status;
27195
+ toThrow.attempts = attempts;
27196
+ toThrow.modelPointer = activeModelPointer;
27197
+ throw toThrow;
26128
27198
  }
26129
- );
26130
- const content = summaryResponse.message.content;
26131
- const summary = typeof content === "string" ? content : content.length > 0 && content[0]?.type === "text" ? content[0].text : null;
26132
- if (!summary) {
26133
- debug.warn("AUTO_COMPACT_SUMMARY_CONTENT_INVALID", {
26134
- model: compressionModelPointer,
26135
- diagnostics: getSummaryContentDiagnostics(content)
26136
- });
26137
- throw new Error(
26138
- "Failed to generate conversation summary - response did not contain valid text content"
26139
- );
27199
+ }
27200
+ if (!summaryResponse) {
27201
+ const exhausted = new Error("Auto compact retries exhausted");
27202
+ exhausted.failureType = "unknown";
27203
+ exhausted.attempts = attempts;
27204
+ exhausted.modelPointer = activeModelPointer;
27205
+ throw exhausted;
26140
27206
  }
26141
27207
  summaryResponse.message.usage = {
26142
27208
  input_tokens: 0,
@@ -26147,7 +27213,7 @@ ${COMPRESSION_PROMPT2}` : COMPRESSION_PROMPT2;
26147
27213
  const recoveredFiles = await selectAndReadFiles();
26148
27214
  const compactedMessages = [
26149
27215
  createUserMessage(
26150
- compressionNotice ? `Context automatically compressed due to token limit. ${compressionNotice} Using '${compressionModelPointer}' for compression.` : `Context automatically compressed due to token limit. Using '${compressionModelPointer}' for compression.`
27216
+ compressionNotice ? `Context automatically compressed due to token limit. ${compressionNotice} Using '${activeModelPointer}' for compression.` : `Context automatically compressed due to token limit. Using '${activeModelPointer}' for compression.`
26151
27217
  ),
26152
27218
  summaryResponse
26153
27219
  ];
@@ -26190,9 +27256,40 @@ ${contentWithLines}
26190
27256
  getContext.cache.clear?.();
26191
27257
  getCodeStyle.cache.clear?.();
26192
27258
  resetFileFreshnessSession();
27259
+ try {
27260
+ flushTypedPartBuffer({ requestId: typedRequestId });
27261
+ } catch {
27262
+ }
26193
27263
  return compactedMessages;
26194
27264
  }
26195
27265
 
27266
+ // src/services/telemetry/autoCompactTelemetryPersistence.ts
27267
+ import { appendFileSync as appendFileSync2, existsSync as existsSync17, mkdirSync as mkdirSync8 } from "fs";
27268
+ import { dirname as dirname10 } from "path";
27269
+ function getAutoCompactTelemetryOutputFilePath() {
27270
+ return resolveXdgCachePath("telemetry/auto-compact-metrics.jsonl");
27271
+ }
27272
+ function flushAutoCompactTelemetrySnapshot(options = {}) {
27273
+ const snapshot = getAutoCompactMetricsSnapshot();
27274
+ if (snapshot.eventCount <= 0) return null;
27275
+ const outputFilePath = options.outputFilePath ?? getAutoCompactTelemetryOutputFilePath();
27276
+ const record = {
27277
+ timestamp: Date.now(),
27278
+ requestId: options.requestId,
27279
+ agentId: options.agentId ?? "main",
27280
+ eventCount: snapshot.eventCount,
27281
+ metrics: snapshot.metrics
27282
+ };
27283
+ if (!existsSync17(dirname10(outputFilePath))) {
27284
+ mkdirSync8(dirname10(outputFilePath), { recursive: true });
27285
+ }
27286
+ appendFileSync2(outputFilePath, JSON.stringify(record) + "\n");
27287
+ if (options.resetAfterFlush !== false) {
27288
+ resetAutoCompactTelemetry();
27289
+ }
27290
+ return record;
27291
+ }
27292
+
26196
27293
  // src/app/query.ts
26197
27294
  function isToolUseLikeBlock(block) {
26198
27295
  return block && typeof block === "object" && (block.type === "tool_use" || block.type === "server_tool_use" || block.type === "mcp_tool_use");
@@ -26419,8 +27516,8 @@ var ToolUseQueue = class {
26419
27516
  }
26420
27517
  if (this.hasExecutingTools() && !this.hasCompletedResults() && !this.hasPendingProgress()) {
26421
27518
  const promises = this.tools.filter((t) => t.status === "executing" && t.promise).map((t) => t.promise);
26422
- const progressPromise = new Promise((resolve11) => {
26423
- this.progressAvailableResolve = resolve11;
27519
+ const progressPromise = new Promise((resolve12) => {
27520
+ this.progressAvailableResolve = resolve12;
26424
27521
  });
26425
27522
  if (promises.length > 0) {
26426
27523
  await Promise.race([...promises, progressPromise]);
@@ -26482,6 +27579,7 @@ async function* queryCore(messages, systemPrompt, context, canUseTool, toolUseCo
26482
27579
  setRequestStatus({ kind: "thinking" });
26483
27580
  try {
26484
27581
  let getAssistantResponse = function() {
27582
+ const modelPointer = toolUseContext.options.model || "main";
26485
27583
  return queryLLM(
26486
27584
  normalizeMessagesForAPI(messages),
26487
27585
  fullSystemPrompt,
@@ -26490,7 +27588,7 @@ async function* queryCore(messages, systemPrompt, context, canUseTool, toolUseCo
26490
27588
  toolUseContext.abortController.signal,
26491
27589
  {
26492
27590
  safeMode: toolUseContext.options.safeMode ?? false,
26493
- model: toolUseContext.options.model || "main",
27591
+ model: modelPointer,
26494
27592
  prependCLISysprompt: true,
26495
27593
  toolUseContext
26496
27594
  }
@@ -26771,6 +27869,11 @@ async function* queryCore(messages, systemPrompt, context, canUseTool, toolUseCo
26771
27869
  throw error;
26772
27870
  }
26773
27871
  } finally {
27872
+ const currentRequest = getCurrentRequest();
27873
+ flushAutoCompactTelemetrySnapshot({
27874
+ requestId: currentRequest?.id,
27875
+ agentId: toolUseContext?.agentId
27876
+ });
26774
27877
  setRequestStatus({ kind: "idle" });
26775
27878
  }
26776
27879
  }
@@ -27404,7 +28507,7 @@ function BinaryFeedbackView({
27404
28507
  function BinaryFeedback({
27405
28508
  m1,
27406
28509
  m2,
27407
- resolve: resolve11,
28510
+ resolve: resolve12,
27408
28511
  debug: debug2,
27409
28512
  erroredToolUseIDs,
27410
28513
  inProgressToolUseIDs,
@@ -27416,9 +28519,9 @@ function BinaryFeedback({
27416
28519
  const onChoose = useCallback15(
27417
28520
  (choice) => {
27418
28521
  logBinaryFeedbackEvent(m1, m2, choice);
27419
- resolve11(getBinaryFeedbackResultForChoice(m1, m2, choice));
28522
+ resolve12(getBinaryFeedbackResultForChoice(m1, m2, choice));
27420
28523
  },
27421
- [m1, m2, resolve11]
28524
+ [m1, m2, resolve12]
27422
28525
  );
27423
28526
  useNotifyAfterTimeout(
27424
28527
  `${PRODUCT_NAME} needs your input on a response comparison`
@@ -28232,7 +29335,7 @@ import React101, { useCallback as useCallback17, useEffect as useEffect26, useMe
28232
29335
  import { Box as Box74, Text as Text78, useInput as useInput28 } from "ink";
28233
29336
  import figures9 from "figures";
28234
29337
  import chalk15 from "chalk";
28235
- import { join as join13 } from "path";
29338
+ import { join as join14 } from "path";
28236
29339
  import { spawn as spawn2 } from "child_process";
28237
29340
 
28238
29341
  // src/commands/agents/tooling.ts
@@ -28287,19 +29390,19 @@ async function getAvailableTools() {
28287
29390
 
28288
29391
  // src/commands/agents/storage.ts
28289
29392
  import {
28290
- existsSync as existsSync15,
28291
- mkdirSync as mkdirSync7,
29393
+ existsSync as existsSync18,
29394
+ mkdirSync as mkdirSync9,
28292
29395
  renameSync as renameSync3,
28293
29396
  unlinkSync as unlinkSync2,
28294
29397
  writeFileSync as writeFileSync6
28295
29398
  } from "fs";
28296
- import { join as join12 } from "path";
29399
+ import { join as join13 } from "path";
28297
29400
  import { homedir as homedir8 } from "os";
28298
29401
 
28299
29402
  // src/commands/agents/generation.ts
28300
29403
  import { randomUUID as randomUUID6 } from "crypto";
28301
29404
  async function generateAgentWithClaude(prompt) {
28302
- const { queryModel } = await import("./llm-VAN6WS52.js");
29405
+ const { queryModel } = await import("./llm-WAAV3MBX.js");
28303
29406
  const systemPrompt = `You are an expert at creating AI agent configurations. Based on the user's description, generate a specialized agent configuration.
28304
29407
 
28305
29408
  Return your response as a JSON object with exactly these fields:
@@ -28483,26 +29586,26 @@ var LEGACY_FOLDER = ".claude";
28483
29586
  var AGENTS_DIR = "agents";
28484
29587
  function getAgentDirectory(location) {
28485
29588
  if (location === "user") {
28486
- return join12(homedir8(), PRIMARY_FOLDER, AGENTS_DIR);
29589
+ return join13(homedir8(), PRIMARY_FOLDER, AGENTS_DIR);
28487
29590
  }
28488
- return join12(getCwd(), PRIMARY_FOLDER, AGENTS_DIR);
29591
+ return join13(getCwd(), PRIMARY_FOLDER, AGENTS_DIR);
28489
29592
  }
28490
29593
  function getLegacyAgentDirectory(location) {
28491
29594
  if (location === "user") {
28492
- return join12(homedir8(), LEGACY_FOLDER, AGENTS_DIR);
29595
+ return join13(homedir8(), LEGACY_FOLDER, AGENTS_DIR);
28493
29596
  }
28494
- return join12(getCwd(), LEGACY_FOLDER, AGENTS_DIR);
29597
+ return join13(getCwd(), LEGACY_FOLDER, AGENTS_DIR);
28495
29598
  }
28496
29599
  function getPrimaryAgentFilePath(location, agentType) {
28497
- return join12(getAgentDirectory(location), `${agentType}.md`);
29600
+ return join13(getAgentDirectory(location), `${agentType}.md`);
28498
29601
  }
28499
29602
  function getLegacyAgentFilePath(location, agentType) {
28500
- return join12(getLegacyAgentDirectory(location), `${agentType}.md`);
29603
+ return join13(getLegacyAgentDirectory(location), `${agentType}.md`);
28501
29604
  }
28502
29605
  function ensureDirectoryExists(location) {
28503
29606
  const dir = getAgentDirectory(location);
28504
- if (!existsSync15(dir)) {
28505
- mkdirSync7(dir, { recursive: true });
29607
+ if (!existsSync18(dir)) {
29608
+ mkdirSync9(dir, { recursive: true });
28506
29609
  }
28507
29610
  return dir;
28508
29611
  }
@@ -28510,7 +29613,7 @@ async function saveAgent(location, agentType, description3, tools, systemPrompt,
28510
29613
  ensureDirectoryExists(location);
28511
29614
  const filePath = getPrimaryAgentFilePath(location, agentType);
28512
29615
  const legacyPath = getLegacyAgentFilePath(location, agentType);
28513
- if (throwIfExists && (existsSync15(filePath) || existsSync15(legacyPath))) {
29616
+ if (throwIfExists && (existsSync18(filePath) || existsSync18(legacyPath))) {
28514
29617
  throw new Error(`Agent file already exists: ${filePath}`);
28515
29618
  }
28516
29619
  const tempFile = `${filePath}.tmp.${Date.now()}.${Math.random().toString(36).substr(2, 9)}`;
@@ -28525,7 +29628,7 @@ async function saveAgent(location, agentType, description3, tools, systemPrompt,
28525
29628
  );
28526
29629
  try {
28527
29630
  writeFileSync6(tempFile, content, { encoding: "utf-8", flag: "wx" });
28528
- if (throwIfExists && (existsSync15(filePath) || existsSync15(legacyPath))) {
29631
+ if (throwIfExists && (existsSync18(filePath) || existsSync18(legacyPath))) {
28529
29632
  try {
28530
29633
  unlinkSync2(tempFile);
28531
29634
  } catch {
@@ -28535,7 +29638,7 @@ async function saveAgent(location, agentType, description3, tools, systemPrompt,
28535
29638
  renameSync3(tempFile, filePath);
28536
29639
  } catch (error) {
28537
29640
  try {
28538
- if (existsSync15(tempFile)) {
29641
+ if (existsSync18(tempFile)) {
28539
29642
  unlinkSync2(tempFile);
28540
29643
  }
28541
29644
  } catch (cleanupError) {
@@ -28563,7 +29666,7 @@ async function updateAgent(agent, description3, tools, systemPrompt, color, mode
28563
29666
  const location = agent.location;
28564
29667
  const primaryPath = getPrimaryAgentFilePath(location, agent.agentType);
28565
29668
  const legacyPath = getLegacyAgentFilePath(location, agent.agentType);
28566
- const filePath = existsSync15(primaryPath) ? primaryPath : existsSync15(legacyPath) ? legacyPath : primaryPath;
29669
+ const filePath = existsSync18(primaryPath) ? primaryPath : existsSync18(legacyPath) ? legacyPath : primaryPath;
28567
29670
  ensureDirectoryExists(location);
28568
29671
  writeFileSync6(filePath, content, { encoding: "utf-8", flag: "w" });
28569
29672
  }
@@ -28574,10 +29677,10 @@ async function deleteAgent(agent) {
28574
29677
  const location = agent.location;
28575
29678
  const primaryPath = getPrimaryAgentFilePath(location, agent.agentType);
28576
29679
  const legacyPath = getLegacyAgentFilePath(location, agent.agentType);
28577
- if (existsSync15(primaryPath)) {
29680
+ if (existsSync18(primaryPath)) {
28578
29681
  unlinkSync2(primaryPath);
28579
29682
  }
28580
- if (existsSync15(legacyPath)) {
29683
+ if (existsSync18(legacyPath)) {
28581
29684
  unlinkSync2(legacyPath);
28582
29685
  }
28583
29686
  }
@@ -28596,7 +29699,7 @@ var COLOR_OPTIONS = [
28596
29699
  "cyan"
28597
29700
  ];
28598
29701
  function openInEditor(filePath) {
28599
- return new Promise((resolve11, reject) => {
29702
+ return new Promise((resolve12, reject) => {
28600
29703
  const platform = process.platform;
28601
29704
  let command4;
28602
29705
  let args;
@@ -28619,7 +29722,7 @@ function openInEditor(filePath) {
28619
29722
  child.on("error", (err) => reject(err));
28620
29723
  child.on(
28621
29724
  "exit",
28622
- (code) => code === 0 ? resolve11() : reject(new Error(`Editor exited with ${code}`))
29725
+ (code) => code === 0 ? resolve12() : reject(new Error(`Editor exited with ${code}`))
28623
29726
  );
28624
29727
  });
28625
29728
  }
@@ -29595,8 +30698,8 @@ function ViewAgent(props) {
29595
30698
  if (props.agent.source === "plugin") return `Plugin: ${props.agent.baseDir ?? "Unknown"}`;
29596
30699
  const baseDir = props.agent.baseDir;
29597
30700
  const file = `${props.agent.filename ?? props.agent.agentType}.md`;
29598
- if (props.agent.source === "projectSettings") return join13(".claude", "agents", file);
29599
- if (baseDir) return join13(baseDir, file);
30701
+ if (props.agent.source === "projectSettings") return join14(".claude", "agents", file);
30702
+ if (baseDir) return join14(baseDir, file);
29600
30703
  return props.agent.source;
29601
30704
  })();
29602
30705
  const toolsSummary = () => {
@@ -29981,8 +31084,8 @@ function getCommand(commandName, commands) {
29981
31084
  var TOOL_NAME_FOR_PROMPT7 = "SlashCommand";
29982
31085
 
29983
31086
  // src/tools/interaction/SlashCommandTool/SlashCommandTool.tsx
29984
- var inputSchema12 = z11.strictObject({
29985
- command: z11.string().describe(
31087
+ var inputSchema12 = z13.strictObject({
31088
+ command: z13.string().describe(
29986
31089
  'The slash command to execute with its arguments, e.g., "/review-pr 123"'
29987
31090
  )
29988
31091
  });
@@ -30228,7 +31331,7 @@ function parseMcpToolName2(name3) {
30228
31331
  // src/tools/system/KillShellTool/KillShellTool.tsx
30229
31332
  import { Box as Box75, Text as Text79 } from "ink";
30230
31333
  import React104 from "react";
30231
- import { z as z12 } from "zod";
31334
+ import { z as z14 } from "zod";
30232
31335
 
30233
31336
  // src/tools/system/KillShellTool/prompt.ts
30234
31337
  var TOOL_NAME_FOR_PROMPT8 = "KillShell";
@@ -30242,8 +31345,8 @@ var PROMPT7 = `
30242
31345
  `;
30243
31346
 
30244
31347
  // src/tools/system/KillShellTool/KillShellTool.tsx
30245
- var inputSchema13 = z12.strictObject({
30246
- shell_id: z12.string().describe("The ID of the background shell to kill")
31348
+ var inputSchema13 = z14.strictObject({
31349
+ shell_id: z14.string().describe("The ID of the background shell to kill")
30247
31350
  });
30248
31351
  var KillShellTool = {
30249
31352
  name: TOOL_NAME_FOR_PROMPT8,
@@ -31112,7 +32215,7 @@ var BashParser = class {
31112
32215
  };
31113
32216
 
31114
32217
  // src/utils/bash-parser/validator.ts
31115
- import { resolve as resolve9 } from "path";
32218
+ import { resolve as resolve10 } from "path";
31116
32219
  async function validateSafety(script, cwd = process.cwd()) {
31117
32220
  const tree = await BashParser.parse(script);
31118
32221
  const root = tree.rootNode;
@@ -31163,7 +32266,7 @@ function checkCommand(node, script, cwd) {
31163
32266
  const targetsCritical = args.some((arg) => {
31164
32267
  if (arg.startsWith("-") || arg.startsWith("$")) return false;
31165
32268
  try {
31166
- const absPath = resolve9(cwd, arg).replace(/\\/g, "/");
32269
+ const absPath = resolve10(cwd, arg).replace(/\\/g, "/");
31167
32270
  return criticalPaths.some((critical) => {
31168
32271
  const normalizedCritical = critical.endsWith("/") ? critical : critical + "/";
31169
32272
  if (absPath === critical || absPath === critical.replace(/\/$/, "")) return true;
@@ -31181,7 +32284,7 @@ function checkCommand(node, script, cwd) {
31181
32284
  const targetsRoot = args.some((arg) => {
31182
32285
  if (arg.startsWith("-") || arg.startsWith("$")) return false;
31183
32286
  try {
31184
- const absPath = resolve9(cwd, arg).replace(/\\/g, "/");
32287
+ const absPath = resolve10(cwd, arg).replace(/\\/g, "/");
31185
32288
  return absPath === "/" || /^[a-z]:\/?$/i.test(absPath);
31186
32289
  } catch {
31187
32290
  return arg === "/" || /^[a-z]:\/?$/i.test(arg);
@@ -31225,13 +32328,13 @@ function countNewlines(text) {
31225
32328
  }
31226
32329
  return count;
31227
32330
  }
31228
- var inputSchema11 = z13.strictObject({
31229
- command: z13.string().describe("The command to execute"),
31230
- cwd: z13.string().optional().describe(
32331
+ var inputSchema11 = z15.strictObject({
32332
+ command: z15.string().describe("The command to execute"),
32333
+ cwd: z15.string().optional().describe(
31231
32334
  "The directory to execute the command in. Use absolute path or path relative to the project root."
31232
32335
  ),
31233
- timeout: z13.number().optional().describe("Optional timeout in milliseconds (max 600000)"),
31234
- description: z13.string().optional().describe(
32336
+ timeout: z15.number().optional().describe("Optional timeout in milliseconds (max 600000)"),
32337
+ description: z15.string().optional().describe(
31235
32338
  `Clear, concise description of what this command does in 5-10 words, in active voice. Examples:
31236
32339
  Input: ls
31237
32340
  Output: List files in current directory
@@ -31245,10 +32348,10 @@ Output: Install package dependencies
31245
32348
  Input: mkdir foo
31246
32349
  Output: Create directory 'foo'`
31247
32350
  ),
31248
- run_in_background: z13.boolean().optional().describe(
32351
+ run_in_background: z15.boolean().optional().describe(
31249
32352
  "Set to true to run this command in the background. Use TaskOutput to read the output later."
31250
32353
  ),
31251
- dangerouslyDisableSandbox: z13.boolean().optional().describe(
32354
+ dangerouslyDisableSandbox: z15.boolean().optional().describe(
31252
32355
  "Set this to true to dangerously override sandbox mode and run commands without sandboxing."
31253
32356
  )
31254
32357
  });
@@ -31289,7 +32392,7 @@ var BashTool = {
31289
32392
  async validateInput({ command: command4, timeout, dangerouslyDisableSandbox, cwd }, context) {
31290
32393
  const trimmed = command4.trim();
31291
32394
  try {
31292
- await validateSafety(trimmed, cwd ? resolve10(getCwd(), cwd) : getCwd());
32395
+ await validateSafety(trimmed, cwd ? resolve11(getCwd(), cwd) : getCwd());
31293
32396
  } catch (e) {
31294
32397
  return {
31295
32398
  result: false,
@@ -31329,7 +32432,7 @@ var BashTool = {
31329
32432
  };
31330
32433
  }
31331
32434
  if (cwd) {
31332
- const fullTargetDir = isAbsolute8(cwd) ? cwd : resolve10(getCwd(), cwd);
32435
+ const fullTargetDir = isAbsolute8(cwd) ? cwd : resolve11(getCwd(), cwd);
31333
32436
  if (!isInDirectory(
31334
32437
  relative12(getOriginalCwd(), fullTargetDir),
31335
32438
  relative12(getCwd(), getOriginalCwd())
@@ -31349,7 +32452,7 @@ var BashTool = {
31349
32452
  continue;
31350
32453
  }
31351
32454
  const targetDir = parts[1].replace(/^['"]|['"]$/g, "");
31352
- const fullTargetDir = isAbsolute8(targetDir) ? targetDir : resolve10(getCwd(), targetDir);
32455
+ const fullTargetDir = isAbsolute8(targetDir) ? targetDir : resolve11(getCwd(), targetDir);
31353
32456
  if (!isInDirectory(
31354
32457
  relative12(getOriginalCwd(), fullTargetDir),
31355
32458
  relative12(getCwd(), getOriginalCwd())
@@ -31460,7 +32563,7 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31460
32563
  const safeMode = Boolean(context?.safeMode ?? context?.options?.safeMode);
31461
32564
  const userPrompt = typeof context?.options?.lastUserPrompt === "string" ? context.options.lastUserPrompt.trim() : "";
31462
32565
  const commandDescription = typeof description3 === "string" ? description3.trim() : "";
31463
- const effectiveCwd = cwd ? isAbsolute8(cwd) ? cwd : resolve10(getCwd(), cwd) : getCwd();
32566
+ const effectiveCwd = cwd ? isAbsolute8(cwd) ? cwd : resolve11(getCwd(), cwd) : getCwd();
31464
32567
  try {
31465
32568
  await validateSafety(command4, effectiveCwd);
31466
32569
  } catch (error) {
@@ -31610,7 +32713,7 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31610
32713
  if (abortController.signal.aborted) return false;
31611
32714
  const hostForUrl = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
31612
32715
  const url2 = `http://${hostForUrl}:${port}/`;
31613
- return await new Promise((resolve11) => {
32716
+ return await new Promise((resolve12) => {
31614
32717
  const assistantMessage = createAssistantMessage("");
31615
32718
  if (context.messageId) {
31616
32719
  ;
@@ -31626,13 +32729,13 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31626
32729
  suggestions: void 0,
31627
32730
  riskScore: null,
31628
32731
  onAbort() {
31629
- resolve11(false);
32732
+ resolve12(false);
31630
32733
  },
31631
32734
  onAllow() {
31632
- resolve11(true);
32735
+ resolve12(true);
31633
32736
  },
31634
32737
  onReject() {
31635
- resolve11(false);
32738
+ resolve12(false);
31636
32739
  }
31637
32740
  };
31638
32741
  setToolJSX({
@@ -31726,8 +32829,8 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31726
32829
  );
31727
32830
  let backgroundRequested = false;
31728
32831
  let resolveBackground = null;
31729
- const backgroundPromise = new Promise((resolve11) => {
31730
- resolveBackground = resolve11;
32832
+ const backgroundPromise = new Promise((resolve12) => {
32833
+ resolveBackground = resolve12;
31731
32834
  });
31732
32835
  const requestBackground = () => {
31733
32836
  if (backgroundRequested) return;
@@ -31770,7 +32873,7 @@ ${footerParts.join(" ")}`;
31770
32873
  bashId
31771
32874
  })),
31772
32875
  new Promise(
31773
- (resolve11) => setTimeout(() => resolve11({ kind: "tick" }), waitMs)
32876
+ (resolve12) => setTimeout(() => resolve12({ kind: "tick" }), waitMs)
31774
32877
  )
31775
32878
  ]);
31776
32879
  if (race.kind === "background") {
@@ -31804,7 +32907,7 @@ ${footerParts.join(" ")}`;
31804
32907
  if (process.env.NODE_ENV !== "test") {
31805
32908
  getCommandFilePaths(command4, stdout).then((filePaths) => {
31806
32909
  for (const filePath of filePaths) {
31807
- const fullFilePath = isAbsolute8(filePath) ? filePath : resolve10(getCwd(), filePath);
32910
+ const fullFilePath = isAbsolute8(filePath) ? filePath : resolve11(getCwd(), filePath);
31808
32911
  try {
31809
32912
  readFileTimestamps[fullFilePath] = statSync13(fullFilePath).mtimeMs;
31810
32913
  } catch (e) {
@@ -32118,6 +33221,7 @@ export {
32118
33221
  KillShellTool,
32119
33222
  hasPermissionsToUseTool,
32120
33223
  BashTool,
33224
+ getModelCapabilities,
32121
33225
  getCLISyspromptPrefix,
32122
33226
  getSystemPrompt,
32123
33227
  getEnvInfo,
@@ -32126,6 +33230,8 @@ export {
32126
33230
  getReasoningEffort,
32127
33231
  generatePybContext,
32128
33232
  refreshPybContext,
33233
+ emitTelemetryEvent,
33234
+ resolveModelResponsePolicy,
32129
33235
  formatSystemPromptWithContext,
32130
33236
  useExitOnCtrlCD,
32131
33237
  clearTerminal,