pybao-cli 1.4.83 → 1.4.85

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-FY7QKVS6.js +49 -0
  2. package/dist/{acp-5G23YRZD.js → acp-2GSHX77R.js} +30 -30
  3. package/dist/{agentsValidate-Y3JGFZPX.js → agentsValidate-UXGO75BF.js} +7 -7
  4. package/dist/{ask-DNEJAFQM.js → ask-ELUL4HKQ.js} +29 -29
  5. package/dist/{autoUpdater-NBXSZEKC.js → autoUpdater-6YER62IR.js} +3 -3
  6. package/dist/{chunk-5KEKIQVC.js → chunk-2SOOZG7K.js} +3 -3
  7. package/dist/{chunk-MBIKKOOW.js → chunk-3Q5CIAL2.js} +1 -1
  8. package/dist/{chunk-5MEGIDN7.js → chunk-4DWNCIQY.js} +1 -1
  9. package/dist/{chunk-RMZABYAD.js → chunk-4UJCKYAC.js} +1 -1
  10. package/dist/{chunk-EINLEUKA.js → chunk-5572LEVQ.js} +1 -1
  11. package/dist/{chunk-FQL6V43W.js → chunk-76J7Y54N.js} +1 -1
  12. package/dist/{chunk-OUOB2RBI.js → chunk-7ODD4XBU.js} +4 -4
  13. package/dist/{chunk-GRQ32HWG.js → chunk-7PMREV7X.js} +3 -1
  14. package/dist/chunk-7PMREV7X.js.map +7 -0
  15. package/dist/{chunk-KSCBNFN7.js → chunk-AG7FFH3Y.js} +1 -1
  16. package/dist/{chunk-A5LLPMGS.js → chunk-AS2KQTUT.js} +2 -2
  17. package/dist/{chunk-GKBRHNMB.js → chunk-AXZ27RH4.js} +1244 -162
  18. package/dist/{chunk-GKBRHNMB.js.map → chunk-AXZ27RH4.js.map} +4 -4
  19. package/dist/{chunk-MKSTJEGS.js → chunk-CDCF77UJ.js} +4 -4
  20. package/dist/{chunk-EUHKG6AJ.js → chunk-EVEFJGBJ.js} +1 -1
  21. package/dist/{chunk-V37R5FE5.js → chunk-JC7FH7WU.js} +16 -16
  22. package/dist/{chunk-WGGELTRR.js → chunk-JMYBBKHV.js} +3 -3
  23. package/dist/{chunk-DHJEENK5.js → chunk-OHC5TYFI.js} +2 -2
  24. package/dist/{chunk-OCIKBYQ4.js → chunk-QMBDLOEI.js} +3 -3
  25. package/dist/{chunk-FPCH7C5K.js → chunk-QUQ6IULP.js} +2 -2
  26. package/dist/{chunk-VRRJXBF3.js → chunk-TCQ5GGG3.js} +1 -1
  27. package/dist/{chunk-7UTUKVKM.js → chunk-TQR5RQJV.js} +4 -4
  28. package/dist/{chunk-FVR53MZY.js → chunk-TVGG7PIY.js} +3 -3
  29. package/dist/{chunk-WSP4AYLZ.js → chunk-TWE7DDOR.js} +3 -3
  30. package/dist/{chunk-IDJMJZP4.js → chunk-U7K2VUAB.js} +2 -2
  31. package/dist/{chunk-LIFJX3UL.js → chunk-UYLH4OHE.js} +3 -3
  32. package/dist/{chunk-53LVQG4V.js → chunk-V2N7TGUM.js} +2 -2
  33. package/dist/{chunk-SUHM4MYA.js → chunk-VMLR2LP6.js} +1 -1
  34. package/dist/{chunk-CFX5VEY5.js → chunk-VNULUWD6.js} +3 -3
  35. package/dist/{chunk-XHQMUJIS.js → chunk-W4I3CWEF.js} +4 -4
  36. package/dist/{chunk-IIZXV4HL.js → chunk-WCDVJOOC.js} +2 -2
  37. package/dist/{chunk-5MZZCUQX.js → chunk-XXIVEBHI.js} +2 -2
  38. package/dist/{chunk-TKPY5LGF.js → chunk-Z2HICQWZ.js} +1 -1
  39. package/dist/{cli-7JVEUFE2.js → cli-4GGW2PEE.js} +89 -89
  40. package/dist/commands-SOPDFP4V.js +53 -0
  41. package/dist/{config-YGHZ7OZB.js → config-ACK7KZQC.js} +4 -4
  42. package/dist/{context-SNUVPSIW.js → context-B57NHDV3.js} +6 -6
  43. package/dist/{conversationTracker-IXJWSKYY.js → conversationTracker-KGCUMWX3.js} +3 -3
  44. package/dist/{customCommands-2YZVCPNF.js → customCommands-EJUGLB7U.js} +4 -4
  45. package/dist/{env-SPCTS7IU.js → env-VWBGS2CV.js} +2 -2
  46. package/dist/{file-MRX573XM.js → file-2J6HXITM.js} +4 -4
  47. package/dist/index.js +3 -3
  48. package/dist/{llm-VAN6WS52.js → llm-2K46QQUI.js} +270 -180
  49. package/dist/llm-2K46QQUI.js.map +7 -0
  50. package/dist/{llmLazy-II5PXLQI.js → llmLazy-7XXVUTUF.js} +1 -1
  51. package/dist/{loader-EV4REQWE.js → loader-PRQCWGJK.js} +4 -4
  52. package/dist/{lsp-O2TLN3AD.js → lsp-Q4XRD6Q5.js} +6 -6
  53. package/dist/{lspAnchor-BLB7II5Y.js → lspAnchor-PEH2Y2UI.js} +6 -6
  54. package/dist/{mcp-OJPHPVNM.js → mcp-KOCYADSE.js} +7 -7
  55. package/dist/{mentionProcessor-BXCFLUXL.js → mentionProcessor-UVN23ZJN.js} +5 -5
  56. package/dist/{messages-CUNARS37.js → messages-FHBY2DUS.js} +1 -1
  57. package/dist/{model-OUTGOGMR.js → model-WYZSVA7P.js} +5 -5
  58. package/dist/{openai-WTOKA74W.js → openai-VH262CSK.js} +5 -5
  59. package/dist/{outputStyles-K5O5RB33.js → outputStyles-2GFONEXE.js} +4 -4
  60. package/dist/{pluginRuntime-JEJXUSFZ.js → pluginRuntime-PVJC4OS6.js} +6 -6
  61. package/dist/{pluginValidation-S4VSNYHJ.js → pluginValidation-BW4FRXA3.js} +6 -6
  62. package/dist/prompts-5SQE4V5S.js +55 -0
  63. package/dist/{pybAgentSessionLoad-I7MI2W5O.js → pybAgentSessionLoad-ESLYSABF.js} +4 -4
  64. package/dist/{pybAgentSessionResume-CMC5D4IX.js → pybAgentSessionResume-RV4GKC77.js} +4 -4
  65. package/dist/{pybAgentStreamJsonSession-FUT6NUZG.js → pybAgentStreamJsonSession-RAYEEMAE.js} +1 -1
  66. package/dist/{pybHooks-I4C2HCMR.js → pybHooks-ZUMVL4EI.js} +4 -4
  67. package/dist/query-JSS7HQZT.js +57 -0
  68. package/dist/{registry-HA4GULY4.js → registry-QBSW2S73.js} +5 -5
  69. package/dist/{ripgrep-4F2VOLSN.js → ripgrep-6SAEPSK7.js} +3 -3
  70. package/dist/{skillMarketplace-73JWYMAT.js → skillMarketplace-DY5FZ4ZG.js} +3 -3
  71. package/dist/{state-WVRITIDZ.js → state-W2FZAYHT.js} +2 -2
  72. package/dist/{theme-BPZWU5M7.js → theme-HMUA7M76.js} +5 -5
  73. package/dist/{toolPermissionSettings-UOQTLVV5.js → toolPermissionSettings-M3V4WFMZ.js} +6 -6
  74. package/dist/tools-U6CMUHMT.js +54 -0
  75. package/dist/{userInput-TQYQIWBV.js → userInput-VVCSGVQW.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-FY7QKVS6.js.map} +0 -0
  85. /package/dist/{acp-5G23YRZD.js.map → acp-2GSHX77R.js.map} +0 -0
  86. /package/dist/{agentsValidate-Y3JGFZPX.js.map → agentsValidate-UXGO75BF.js.map} +0 -0
  87. /package/dist/{ask-DNEJAFQM.js.map → ask-ELUL4HKQ.js.map} +0 -0
  88. /package/dist/{autoUpdater-NBXSZEKC.js.map → autoUpdater-6YER62IR.js.map} +0 -0
  89. /package/dist/{chunk-5KEKIQVC.js.map → chunk-2SOOZG7K.js.map} +0 -0
  90. /package/dist/{chunk-MBIKKOOW.js.map → chunk-3Q5CIAL2.js.map} +0 -0
  91. /package/dist/{chunk-5MEGIDN7.js.map → chunk-4DWNCIQY.js.map} +0 -0
  92. /package/dist/{chunk-RMZABYAD.js.map → chunk-4UJCKYAC.js.map} +0 -0
  93. /package/dist/{chunk-EINLEUKA.js.map → chunk-5572LEVQ.js.map} +0 -0
  94. /package/dist/{chunk-FQL6V43W.js.map → chunk-76J7Y54N.js.map} +0 -0
  95. /package/dist/{chunk-OUOB2RBI.js.map → chunk-7ODD4XBU.js.map} +0 -0
  96. /package/dist/{chunk-KSCBNFN7.js.map → chunk-AG7FFH3Y.js.map} +0 -0
  97. /package/dist/{chunk-A5LLPMGS.js.map → chunk-AS2KQTUT.js.map} +0 -0
  98. /package/dist/{chunk-MKSTJEGS.js.map → chunk-CDCF77UJ.js.map} +0 -0
  99. /package/dist/{chunk-EUHKG6AJ.js.map → chunk-EVEFJGBJ.js.map} +0 -0
  100. /package/dist/{chunk-V37R5FE5.js.map → chunk-JC7FH7WU.js.map} +0 -0
  101. /package/dist/{chunk-WGGELTRR.js.map → chunk-JMYBBKHV.js.map} +0 -0
  102. /package/dist/{chunk-DHJEENK5.js.map → chunk-OHC5TYFI.js.map} +0 -0
  103. /package/dist/{chunk-OCIKBYQ4.js.map → chunk-QMBDLOEI.js.map} +0 -0
  104. /package/dist/{chunk-FPCH7C5K.js.map → chunk-QUQ6IULP.js.map} +0 -0
  105. /package/dist/{chunk-VRRJXBF3.js.map → chunk-TCQ5GGG3.js.map} +0 -0
  106. /package/dist/{chunk-7UTUKVKM.js.map → chunk-TQR5RQJV.js.map} +0 -0
  107. /package/dist/{chunk-FVR53MZY.js.map → chunk-TVGG7PIY.js.map} +0 -0
  108. /package/dist/{chunk-WSP4AYLZ.js.map → chunk-TWE7DDOR.js.map} +0 -0
  109. /package/dist/{chunk-IDJMJZP4.js.map → chunk-U7K2VUAB.js.map} +0 -0
  110. /package/dist/{chunk-LIFJX3UL.js.map → chunk-UYLH4OHE.js.map} +0 -0
  111. /package/dist/{chunk-53LVQG4V.js.map → chunk-V2N7TGUM.js.map} +0 -0
  112. /package/dist/{chunk-SUHM4MYA.js.map → chunk-VMLR2LP6.js.map} +0 -0
  113. /package/dist/{chunk-CFX5VEY5.js.map → chunk-VNULUWD6.js.map} +0 -0
  114. /package/dist/{chunk-XHQMUJIS.js.map → chunk-W4I3CWEF.js.map} +0 -0
  115. /package/dist/{chunk-IIZXV4HL.js.map → chunk-WCDVJOOC.js.map} +0 -0
  116. /package/dist/{chunk-5MZZCUQX.js.map → chunk-XXIVEBHI.js.map} +0 -0
  117. /package/dist/{chunk-TKPY5LGF.js.map → chunk-Z2HICQWZ.js.map} +0 -0
  118. /package/dist/{cli-7JVEUFE2.js.map → cli-4GGW2PEE.js.map} +0 -0
  119. /package/dist/{commands-FPZREXUW.js.map → commands-SOPDFP4V.js.map} +0 -0
  120. /package/dist/{config-YGHZ7OZB.js.map → config-ACK7KZQC.js.map} +0 -0
  121. /package/dist/{context-SNUVPSIW.js.map → context-B57NHDV3.js.map} +0 -0
  122. /package/dist/{conversationTracker-IXJWSKYY.js.map → conversationTracker-KGCUMWX3.js.map} +0 -0
  123. /package/dist/{customCommands-2YZVCPNF.js.map → customCommands-EJUGLB7U.js.map} +0 -0
  124. /package/dist/{env-SPCTS7IU.js.map → env-VWBGS2CV.js.map} +0 -0
  125. /package/dist/{file-MRX573XM.js.map → file-2J6HXITM.js.map} +0 -0
  126. /package/dist/{llmLazy-II5PXLQI.js.map → llmLazy-7XXVUTUF.js.map} +0 -0
  127. /package/dist/{loader-EV4REQWE.js.map → loader-PRQCWGJK.js.map} +0 -0
  128. /package/dist/{lsp-O2TLN3AD.js.map → lsp-Q4XRD6Q5.js.map} +0 -0
  129. /package/dist/{lspAnchor-BLB7II5Y.js.map → lspAnchor-PEH2Y2UI.js.map} +0 -0
  130. /package/dist/{mcp-OJPHPVNM.js.map → mcp-KOCYADSE.js.map} +0 -0
  131. /package/dist/{mentionProcessor-BXCFLUXL.js.map → mentionProcessor-UVN23ZJN.js.map} +0 -0
  132. /package/dist/{messages-CUNARS37.js.map → messages-FHBY2DUS.js.map} +0 -0
  133. /package/dist/{model-OUTGOGMR.js.map → model-WYZSVA7P.js.map} +0 -0
  134. /package/dist/{openai-WTOKA74W.js.map → openai-VH262CSK.js.map} +0 -0
  135. /package/dist/{outputStyles-K5O5RB33.js.map → outputStyles-2GFONEXE.js.map} +0 -0
  136. /package/dist/{pluginRuntime-JEJXUSFZ.js.map → pluginRuntime-PVJC4OS6.js.map} +0 -0
  137. /package/dist/{pluginValidation-S4VSNYHJ.js.map → pluginValidation-BW4FRXA3.js.map} +0 -0
  138. /package/dist/{prompts-XUL3MGVE.js.map → prompts-5SQE4V5S.js.map} +0 -0
  139. /package/dist/{pybAgentSessionLoad-I7MI2W5O.js.map → pybAgentSessionLoad-ESLYSABF.js.map} +0 -0
  140. /package/dist/{pybAgentSessionResume-CMC5D4IX.js.map → pybAgentSessionResume-RV4GKC77.js.map} +0 -0
  141. /package/dist/{pybAgentStreamJsonSession-FUT6NUZG.js.map → pybAgentStreamJsonSession-RAYEEMAE.js.map} +0 -0
  142. /package/dist/{pybHooks-I4C2HCMR.js.map → pybHooks-ZUMVL4EI.js.map} +0 -0
  143. /package/dist/{query-HKFFVARD.js.map → query-JSS7HQZT.js.map} +0 -0
  144. /package/dist/{registry-HA4GULY4.js.map → registry-QBSW2S73.js.map} +0 -0
  145. /package/dist/{ripgrep-4F2VOLSN.js.map → ripgrep-6SAEPSK7.js.map} +0 -0
  146. /package/dist/{skillMarketplace-73JWYMAT.js.map → skillMarketplace-DY5FZ4ZG.js.map} +0 -0
  147. /package/dist/{state-WVRITIDZ.js.map → state-W2FZAYHT.js.map} +0 -0
  148. /package/dist/{theme-BPZWU5M7.js.map → theme-HMUA7M76.js.map} +0 -0
  149. /package/dist/{toolPermissionSettings-UOQTLVV5.js.map → toolPermissionSettings-M3V4WFMZ.js.map} +0 -0
  150. /package/dist/{tools-3OMW2SOR.js.map → tools-U6CMUHMT.js.map} +0 -0
  151. /package/dist/{userInput-TQYQIWBV.js.map → userInput-VVCSGVQW.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-5572LEVQ.js";
6
6
  import {
7
7
  formatValidationResult,
8
8
  validatePluginOrMarketplacePath
9
- } from "./chunk-WGGELTRR.js";
9
+ } from "./chunk-JMYBBKHV.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-4UJCKYAC.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-76J7Y54N.js";
24
24
  import {
25
25
  appendSessionCustomTitleRecord,
26
26
  appendSessionJsonlFromMessage,
27
27
  appendSessionTagRecord
28
- } from "./chunk-A5LLPMGS.js";
28
+ } from "./chunk-AS2KQTUT.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-2SOOZG7K.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-U7K2VUAB.js";
50
50
  import {
51
51
  fetchCustomModels,
52
52
  getModelFeatures
53
- } from "./chunk-53LVQG4V.js";
53
+ } from "./chunk-V2N7TGUM.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-7ODD4XBU.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-TQR5RQJV.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-VMLR2LP6.js";
89
89
  import {
90
90
  loadToolPermissionContextFromDisk,
91
91
  persistToolPermissionUpdateToDisk
92
- } from "./chunk-FVR53MZY.js";
92
+ } from "./chunk-TVGG7PIY.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-XXIVEBHI.js";
104
104
  import {
105
105
  clearAgentCache,
106
106
  getActiveAgents,
107
107
  getAgentByType,
108
108
  getAllAgents
109
- } from "./chunk-DHJEENK5.js";
109
+ } from "./chunk-OHC5TYFI.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-EVEFJGBJ.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-QUQ6IULP.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-W4I3CWEF.js";
181
181
  import {
182
182
  getSettingsFileCandidates,
183
183
  loadSettingsWithLegacyFallback,
184
184
  readSettingsFile
185
- } from "./chunk-5MEGIDN7.js";
185
+ } from "./chunk-4DWNCIQY.js";
186
186
  import {
187
187
  getCustomCommandDirectories,
188
188
  hasCustomCommands,
189
189
  loadCustomCommands,
190
190
  reloadCustomCommands
191
- } from "./chunk-IIZXV4HL.js";
191
+ } from "./chunk-WCDVJOOC.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-QMBDLOEI.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-CDCF77UJ.js";
208
208
  import {
209
209
  ripGrep
210
- } from "./chunk-KSCBNFN7.js";
210
+ } from "./chunk-AG7FFH3Y.js";
211
211
  import {
212
212
  getTheme
213
- } from "./chunk-TKPY5LGF.js";
213
+ } from "./chunk-Z2HICQWZ.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-TWE7DDOR.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-3Q5CIAL2.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-TCQ5GGG3.js";
275
276
  import {
276
277
  MACRO
277
- } from "./chunk-GRQ32HWG.js";
278
+ } from "./chunk-7PMREV7X.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-2K46QQUI.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-2K46QQUI.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-PEH2Y2UI.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-2K46QQUI.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-PVJC4OS6.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-WYZSVA7P.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-2K46QQUI.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-W2FZAYHT.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,91 @@ 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: true,
26874
+ source: "default"
26875
+ };
26876
+ }
26877
+ function emitStreamTypedPartsFromContent(content, requestId) {
26878
+ const state = createAssemblerState(requestId);
26879
+ if (typeof content === "string") {
26880
+ onTextStart({ textId: "text-0" }, state);
26881
+ onTextDelta({ textId: "text-0", text: content }, state);
26882
+ onTextEnd({ textId: "text-0" }, state);
26883
+ } else if (Array.isArray(content)) {
26884
+ for (let i = 0; i < content.length; i += 1) {
26885
+ const block = content[i];
26886
+ if (!block || typeof block !== "object") continue;
26887
+ const type3 = String(block.type ?? "");
26888
+ if (type3 === "text") {
26889
+ const text = String(block.text ?? "");
26890
+ onTextStart({ textId: `text-${i}` }, state);
26891
+ onTextDelta({ textId: `text-${i}`, text }, state);
26892
+ onTextEnd({ textId: `text-${i}` }, state);
26893
+ continue;
26894
+ }
26895
+ if (type3 === "thinking" || type3 === "reasoning") {
26896
+ const text = String(
26897
+ block.thinking ?? block.reasoning ?? ""
26898
+ );
26899
+ onReasoningStart({ reasoningId: `reasoning-${i}` }, state);
26900
+ onReasoningDelta({ reasoningId: `reasoning-${i}`, text }, state);
26901
+ onReasoningEnd({ reasoningId: `reasoning-${i}` }, state);
26902
+ continue;
26903
+ }
26904
+ if (type3 === "tool_use") {
26905
+ const toolCallId = String(block.id ?? `tool-${i}`);
26906
+ const toolName = String(block.name ?? "unknown");
26907
+ onToolCall({ toolCallId, toolName }, state);
26908
+ continue;
26909
+ }
26910
+ if (type3 === "tool_result") {
26911
+ const toolCallId = String(block.tool_use_id ?? `tool-${i}`);
26912
+ const outputText = extractToolResultText(block.content);
26913
+ onToolResult(
26914
+ {
26915
+ toolCallId,
26916
+ status: block.is_error ? "failed" : "completed",
26917
+ outputText
26918
+ },
26919
+ state
26920
+ );
26921
+ }
26922
+ }
26923
+ }
26924
+ const emittedParts = flushTypedParts(state);
26925
+ for (const part of emittedParts) {
26926
+ emitTypedPart({ requestId, part });
26927
+ }
26928
+ return emittedParts;
26929
+ }
26052
26930
  async function checkAutoCompact(messages, toolUseContext) {
26053
26931
  if (!await shouldAutoCompact(messages)) {
26054
26932
  return { messages, wasCompacted: false };
@@ -26070,14 +26948,28 @@ async function checkAutoCompact(messages, toolUseContext) {
26070
26948
  wasCompacted: true
26071
26949
  };
26072
26950
  } catch (error) {
26073
- logError(error);
26074
- debug.warn("AUTO_COMPACT_FAILED", {
26075
- error: error instanceof Error ? error.message : String(error)
26951
+ const classified = classifyAutoCompactFailure(error);
26952
+ const aggregation = buildAutoCompactAggregationFields({
26953
+ failureType: classified.failureType,
26954
+ status: classified.status,
26955
+ modelPointer: error?.modelPointer
26076
26956
  });
26957
+ const failurePayload = {
26958
+ error: classified.message,
26959
+ failureType: classified.failureType,
26960
+ status: classified.status,
26961
+ modelPointer: error?.modelPointer,
26962
+ attempts: error?.attempts,
26963
+ ...aggregation
26964
+ };
26965
+ logError(error);
26966
+ debug.warn("AUTO_COMPACT_FAILED", failurePayload);
26967
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_FAILED", failurePayload);
26077
26968
  return { messages, wasCompacted: false };
26078
26969
  }
26079
26970
  }
26080
26971
  async function executeAutoCompact(messages, toolUseContext, options) {
26972
+ const typedRequestId = `auto_compact_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
26081
26973
  const previousSummary = findLatestAutoCompactSummary(messages);
26082
26974
  const summaryRequestContent = previousSummary ? `We already have an existing conversation summary:
26083
26975
 
@@ -26113,30 +27005,180 @@ ${COMPRESSION_PROMPT2}` : COMPRESSION_PROMPT2;
26113
27005
  mainResolution.error || "Compression fallback failed: model pointer 'main' is not configured."
26114
27006
  );
26115
27007
  }
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
27008
+ let summaryResponse = null;
27009
+ let attempts = 0;
27010
+ let activeModelPointer = compressionModelPointer;
27011
+ const typedPath = resolveTypedReadPathConfig(toolUseContext);
27012
+ while (attempts < 2) {
27013
+ attempts += 1;
27014
+ try {
27015
+ const summaryCandidate = await queryLLM(
27016
+ normalizeMessagesForAPI([...messagesForSummary, summaryRequest]),
27017
+ [
27018
+ "You are a helpful AI assistant tasked with creating comprehensive conversation summaries that preserve all essential context for continuing development work."
27019
+ ],
27020
+ 0,
27021
+ [],
27022
+ toolUseContext.abortController.signal,
27023
+ {
27024
+ safeMode: false,
27025
+ model: activeModelPointer,
27026
+ prependCLISysprompt: true,
27027
+ firstMode: toolUseContext?.firstMode
27028
+ }
27029
+ );
27030
+ const content = summaryCandidate.message.content;
27031
+ const activeModelName = activeModelPointer === "compact" ? compactResolution.success && compactResolution.profile ? compactResolution.profile.name : "compact" : mainResolution.success && mainResolution.profile ? mainResolution.profile.name : "main";
27032
+ const resolvedPolicy = resolveModelResponsePolicy({
27033
+ source: "auto_compact",
27034
+ model: activeModelName,
27035
+ provider: "openai"
27036
+ });
27037
+ let emittedTypedParts = [];
27038
+ try {
27039
+ emittedTypedParts = emitStreamTypedPartsFromContent(content, typedRequestId);
27040
+ } catch {
27041
+ }
27042
+ const typedReplay = resolveTypedReplayResult({
27043
+ enabled: typedPath.enabled,
27044
+ parts: emittedTypedParts
27045
+ });
27046
+ let canonicalResult = null;
27047
+ let summary = null;
27048
+ if (typedPath.enabled && typedReplay.isComplete && typedReplay.summaryText) {
27049
+ summary = typedReplay.summaryText;
27050
+ const typedAppliedPayload = {
27051
+ mode: "typed",
27052
+ pathSource: typedPath.source,
27053
+ reason: typedReplay.reason,
27054
+ textPartCount: typedReplay.textPartCount,
27055
+ reasoningPartCount: typedReplay.reasoningPartCount
27056
+ };
27057
+ debug.warn("AUTO_COMPACT_TYPED_PATH_APPLIED", typedAppliedPayload);
27058
+ emitAutoCompactTelemetryEvent(
27059
+ "AUTO_COMPACT_TYPED_PATH_APPLIED",
27060
+ typedAppliedPayload
27061
+ );
27062
+ } else {
27063
+ canonicalResult = normalizeModelResponseContent(content, {
27064
+ source: "auto_compact",
27065
+ model: activeModelName,
27066
+ provider: "openai",
27067
+ reasoningPolicy: resolvedPolicy.reasoningPolicy,
27068
+ policySource: resolvedPolicy.policySource
27069
+ });
27070
+ summary = canonicalResult.summaryText;
27071
+ const typedAppliedPayload = {
27072
+ mode: typedPath.enabled ? "canonical_fallback" : "canonical_disabled",
27073
+ pathSource: typedPath.source,
27074
+ ...typedPath.enabled ? {
27075
+ reason: typedReplay.reason,
27076
+ textPartCount: typedReplay.textPartCount,
27077
+ reasoningPartCount: typedReplay.reasoningPartCount
27078
+ } : {}
27079
+ };
27080
+ debug.warn("AUTO_COMPACT_TYPED_PATH_APPLIED", typedAppliedPayload);
27081
+ emitAutoCompactTelemetryEvent(
27082
+ "AUTO_COMPACT_TYPED_PATH_APPLIED",
27083
+ typedAppliedPayload
27084
+ );
27085
+ }
27086
+ if (!summary) {
27087
+ debug.warn("AUTO_COMPACT_SUMMARY_CONTENT_INVALID", {
27088
+ model: activeModelPointer,
27089
+ diagnostics: getSummaryContentDiagnostics(content),
27090
+ canonicalDiagnostics: canonicalResult ? {
27091
+ textBlockCount: canonicalResult.textBlocks.length,
27092
+ reasoningBlockCount: canonicalResult.reasoningBlocks.length,
27093
+ blockTypes: canonicalResult.blockTypes,
27094
+ failureType: canonicalResult.failureType
27095
+ } : void 0,
27096
+ attempt: attempts
27097
+ });
27098
+ throw new Error(
27099
+ "Failed to generate conversation summary - response did not contain valid text content"
27100
+ );
27101
+ }
27102
+ summaryResponse = summaryCandidate;
27103
+ break;
27104
+ } catch (error) {
27105
+ const classified = classifyAutoCompactFailure(error);
27106
+ const recoveryAction = decideAutoCompactRecovery({
27107
+ failureType: classified.failureType,
27108
+ attempt: attempts,
27109
+ maxAttempts: 2,
27110
+ activeModelPointer,
27111
+ hasMainModelProfile: Boolean(mainResolution.success && mainResolution.profile)
27112
+ });
27113
+ if (recoveryAction === "retry_reextract") {
27114
+ const aggregation = buildAutoCompactAggregationFields({
27115
+ failureType: classified.failureType,
27116
+ status: classified.status,
27117
+ modelPointer: activeModelPointer
27118
+ });
27119
+ const retryPayload = {
27120
+ failureType: classified.failureType,
27121
+ attempt: attempts,
27122
+ strategy: "reextract_once",
27123
+ ...aggregation
27124
+ };
27125
+ debug.warn("AUTO_COMPACT_RETRY", retryPayload);
27126
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_RETRY", retryPayload);
27127
+ continue;
27128
+ }
27129
+ if (recoveryAction === "retry_backoff") {
27130
+ const aggregation = buildAutoCompactAggregationFields({
27131
+ failureType: classified.failureType,
27132
+ status: classified.status,
27133
+ modelPointer: activeModelPointer
27134
+ });
27135
+ const retryPayload = {
27136
+ failureType: classified.failureType,
27137
+ attempt: attempts,
27138
+ status: classified.status,
27139
+ strategy: "retry_with_backoff",
27140
+ ...aggregation
27141
+ };
27142
+ debug.warn("AUTO_COMPACT_RETRY", retryPayload);
27143
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_RETRY", retryPayload);
27144
+ await wait(AUTO_COMPACT_CHAIN_RETRY_DELAY_MS);
27145
+ continue;
27146
+ }
27147
+ if (recoveryAction === "fallback_main") {
27148
+ activeModelPointer = "main";
27149
+ if (!compressionNotice) {
27150
+ compressionNotice = "Compression fallback applied: compact model unavailable, switched to 'main'.";
27151
+ }
27152
+ const aggregation = buildAutoCompactAggregationFields({
27153
+ failureType: classified.failureType,
27154
+ status: classified.status,
27155
+ modelPointer: "compact"
27156
+ });
27157
+ const fallbackPayload = {
27158
+ failureType: classified.failureType,
27159
+ attempt: attempts,
27160
+ fromModel: "compact",
27161
+ toModel: "main",
27162
+ ...aggregation
27163
+ };
27164
+ debug.warn("AUTO_COMPACT_FALLBACK", fallbackPayload);
27165
+ emitAutoCompactTelemetryEvent("AUTO_COMPACT_FALLBACK", fallbackPayload);
27166
+ continue;
27167
+ }
27168
+ const toThrow = error instanceof Error ? error : new Error(String(error));
27169
+ toThrow.failureType = classified.failureType;
27170
+ toThrow.status = classified.status;
27171
+ toThrow.attempts = attempts;
27172
+ toThrow.modelPointer = activeModelPointer;
27173
+ throw toThrow;
26128
27174
  }
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
- );
27175
+ }
27176
+ if (!summaryResponse) {
27177
+ const exhausted = new Error("Auto compact retries exhausted");
27178
+ exhausted.failureType = "unknown";
27179
+ exhausted.attempts = attempts;
27180
+ exhausted.modelPointer = activeModelPointer;
27181
+ throw exhausted;
26140
27182
  }
26141
27183
  summaryResponse.message.usage = {
26142
27184
  input_tokens: 0,
@@ -26147,7 +27189,7 @@ ${COMPRESSION_PROMPT2}` : COMPRESSION_PROMPT2;
26147
27189
  const recoveredFiles = await selectAndReadFiles();
26148
27190
  const compactedMessages = [
26149
27191
  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.`
27192
+ 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
27193
  ),
26152
27194
  summaryResponse
26153
27195
  ];
@@ -26190,9 +27232,40 @@ ${contentWithLines}
26190
27232
  getContext.cache.clear?.();
26191
27233
  getCodeStyle.cache.clear?.();
26192
27234
  resetFileFreshnessSession();
27235
+ try {
27236
+ flushTypedPartBuffer({ requestId: typedRequestId });
27237
+ } catch {
27238
+ }
26193
27239
  return compactedMessages;
26194
27240
  }
26195
27241
 
27242
+ // src/services/telemetry/autoCompactTelemetryPersistence.ts
27243
+ import { appendFileSync as appendFileSync2, existsSync as existsSync17, mkdirSync as mkdirSync8 } from "fs";
27244
+ import { dirname as dirname10 } from "path";
27245
+ function getAutoCompactTelemetryOutputFilePath() {
27246
+ return resolveXdgCachePath("telemetry/auto-compact-metrics.jsonl");
27247
+ }
27248
+ function flushAutoCompactTelemetrySnapshot(options = {}) {
27249
+ const snapshot = getAutoCompactMetricsSnapshot();
27250
+ if (snapshot.eventCount <= 0) return null;
27251
+ const outputFilePath = options.outputFilePath ?? getAutoCompactTelemetryOutputFilePath();
27252
+ const record = {
27253
+ timestamp: Date.now(),
27254
+ requestId: options.requestId,
27255
+ agentId: options.agentId ?? "main",
27256
+ eventCount: snapshot.eventCount,
27257
+ metrics: snapshot.metrics
27258
+ };
27259
+ if (!existsSync17(dirname10(outputFilePath))) {
27260
+ mkdirSync8(dirname10(outputFilePath), { recursive: true });
27261
+ }
27262
+ appendFileSync2(outputFilePath, JSON.stringify(record) + "\n");
27263
+ if (options.resetAfterFlush !== false) {
27264
+ resetAutoCompactTelemetry();
27265
+ }
27266
+ return record;
27267
+ }
27268
+
26196
27269
  // src/app/query.ts
26197
27270
  function isToolUseLikeBlock(block) {
26198
27271
  return block && typeof block === "object" && (block.type === "tool_use" || block.type === "server_tool_use" || block.type === "mcp_tool_use");
@@ -26419,8 +27492,8 @@ var ToolUseQueue = class {
26419
27492
  }
26420
27493
  if (this.hasExecutingTools() && !this.hasCompletedResults() && !this.hasPendingProgress()) {
26421
27494
  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;
27495
+ const progressPromise = new Promise((resolve12) => {
27496
+ this.progressAvailableResolve = resolve12;
26424
27497
  });
26425
27498
  if (promises.length > 0) {
26426
27499
  await Promise.race([...promises, progressPromise]);
@@ -26482,6 +27555,7 @@ async function* queryCore(messages, systemPrompt, context, canUseTool, toolUseCo
26482
27555
  setRequestStatus({ kind: "thinking" });
26483
27556
  try {
26484
27557
  let getAssistantResponse = function() {
27558
+ const modelPointer = toolUseContext.options.model || "main";
26485
27559
  return queryLLM(
26486
27560
  normalizeMessagesForAPI(messages),
26487
27561
  fullSystemPrompt,
@@ -26490,7 +27564,7 @@ async function* queryCore(messages, systemPrompt, context, canUseTool, toolUseCo
26490
27564
  toolUseContext.abortController.signal,
26491
27565
  {
26492
27566
  safeMode: toolUseContext.options.safeMode ?? false,
26493
- model: toolUseContext.options.model || "main",
27567
+ model: modelPointer,
26494
27568
  prependCLISysprompt: true,
26495
27569
  toolUseContext
26496
27570
  }
@@ -26771,6 +27845,11 @@ async function* queryCore(messages, systemPrompt, context, canUseTool, toolUseCo
26771
27845
  throw error;
26772
27846
  }
26773
27847
  } finally {
27848
+ const currentRequest = getCurrentRequest();
27849
+ flushAutoCompactTelemetrySnapshot({
27850
+ requestId: currentRequest?.id,
27851
+ agentId: toolUseContext?.agentId
27852
+ });
26774
27853
  setRequestStatus({ kind: "idle" });
26775
27854
  }
26776
27855
  }
@@ -27404,7 +28483,7 @@ function BinaryFeedbackView({
27404
28483
  function BinaryFeedback({
27405
28484
  m1,
27406
28485
  m2,
27407
- resolve: resolve11,
28486
+ resolve: resolve12,
27408
28487
  debug: debug2,
27409
28488
  erroredToolUseIDs,
27410
28489
  inProgressToolUseIDs,
@@ -27416,9 +28495,9 @@ function BinaryFeedback({
27416
28495
  const onChoose = useCallback15(
27417
28496
  (choice) => {
27418
28497
  logBinaryFeedbackEvent(m1, m2, choice);
27419
- resolve11(getBinaryFeedbackResultForChoice(m1, m2, choice));
28498
+ resolve12(getBinaryFeedbackResultForChoice(m1, m2, choice));
27420
28499
  },
27421
- [m1, m2, resolve11]
28500
+ [m1, m2, resolve12]
27422
28501
  );
27423
28502
  useNotifyAfterTimeout(
27424
28503
  `${PRODUCT_NAME} needs your input on a response comparison`
@@ -28232,7 +29311,7 @@ import React101, { useCallback as useCallback17, useEffect as useEffect26, useMe
28232
29311
  import { Box as Box74, Text as Text78, useInput as useInput28 } from "ink";
28233
29312
  import figures9 from "figures";
28234
29313
  import chalk15 from "chalk";
28235
- import { join as join13 } from "path";
29314
+ import { join as join14 } from "path";
28236
29315
  import { spawn as spawn2 } from "child_process";
28237
29316
 
28238
29317
  // src/commands/agents/tooling.ts
@@ -28287,19 +29366,19 @@ async function getAvailableTools() {
28287
29366
 
28288
29367
  // src/commands/agents/storage.ts
28289
29368
  import {
28290
- existsSync as existsSync15,
28291
- mkdirSync as mkdirSync7,
29369
+ existsSync as existsSync18,
29370
+ mkdirSync as mkdirSync9,
28292
29371
  renameSync as renameSync3,
28293
29372
  unlinkSync as unlinkSync2,
28294
29373
  writeFileSync as writeFileSync6
28295
29374
  } from "fs";
28296
- import { join as join12 } from "path";
29375
+ import { join as join13 } from "path";
28297
29376
  import { homedir as homedir8 } from "os";
28298
29377
 
28299
29378
  // src/commands/agents/generation.ts
28300
29379
  import { randomUUID as randomUUID6 } from "crypto";
28301
29380
  async function generateAgentWithClaude(prompt) {
28302
- const { queryModel } = await import("./llm-VAN6WS52.js");
29381
+ const { queryModel } = await import("./llm-2K46QQUI.js");
28303
29382
  const systemPrompt = `You are an expert at creating AI agent configurations. Based on the user's description, generate a specialized agent configuration.
28304
29383
 
28305
29384
  Return your response as a JSON object with exactly these fields:
@@ -28483,26 +29562,26 @@ var LEGACY_FOLDER = ".claude";
28483
29562
  var AGENTS_DIR = "agents";
28484
29563
  function getAgentDirectory(location) {
28485
29564
  if (location === "user") {
28486
- return join12(homedir8(), PRIMARY_FOLDER, AGENTS_DIR);
29565
+ return join13(homedir8(), PRIMARY_FOLDER, AGENTS_DIR);
28487
29566
  }
28488
- return join12(getCwd(), PRIMARY_FOLDER, AGENTS_DIR);
29567
+ return join13(getCwd(), PRIMARY_FOLDER, AGENTS_DIR);
28489
29568
  }
28490
29569
  function getLegacyAgentDirectory(location) {
28491
29570
  if (location === "user") {
28492
- return join12(homedir8(), LEGACY_FOLDER, AGENTS_DIR);
29571
+ return join13(homedir8(), LEGACY_FOLDER, AGENTS_DIR);
28493
29572
  }
28494
- return join12(getCwd(), LEGACY_FOLDER, AGENTS_DIR);
29573
+ return join13(getCwd(), LEGACY_FOLDER, AGENTS_DIR);
28495
29574
  }
28496
29575
  function getPrimaryAgentFilePath(location, agentType) {
28497
- return join12(getAgentDirectory(location), `${agentType}.md`);
29576
+ return join13(getAgentDirectory(location), `${agentType}.md`);
28498
29577
  }
28499
29578
  function getLegacyAgentFilePath(location, agentType) {
28500
- return join12(getLegacyAgentDirectory(location), `${agentType}.md`);
29579
+ return join13(getLegacyAgentDirectory(location), `${agentType}.md`);
28501
29580
  }
28502
29581
  function ensureDirectoryExists(location) {
28503
29582
  const dir = getAgentDirectory(location);
28504
- if (!existsSync15(dir)) {
28505
- mkdirSync7(dir, { recursive: true });
29583
+ if (!existsSync18(dir)) {
29584
+ mkdirSync9(dir, { recursive: true });
28506
29585
  }
28507
29586
  return dir;
28508
29587
  }
@@ -28510,7 +29589,7 @@ async function saveAgent(location, agentType, description3, tools, systemPrompt,
28510
29589
  ensureDirectoryExists(location);
28511
29590
  const filePath = getPrimaryAgentFilePath(location, agentType);
28512
29591
  const legacyPath = getLegacyAgentFilePath(location, agentType);
28513
- if (throwIfExists && (existsSync15(filePath) || existsSync15(legacyPath))) {
29592
+ if (throwIfExists && (existsSync18(filePath) || existsSync18(legacyPath))) {
28514
29593
  throw new Error(`Agent file already exists: ${filePath}`);
28515
29594
  }
28516
29595
  const tempFile = `${filePath}.tmp.${Date.now()}.${Math.random().toString(36).substr(2, 9)}`;
@@ -28525,7 +29604,7 @@ async function saveAgent(location, agentType, description3, tools, systemPrompt,
28525
29604
  );
28526
29605
  try {
28527
29606
  writeFileSync6(tempFile, content, { encoding: "utf-8", flag: "wx" });
28528
- if (throwIfExists && (existsSync15(filePath) || existsSync15(legacyPath))) {
29607
+ if (throwIfExists && (existsSync18(filePath) || existsSync18(legacyPath))) {
28529
29608
  try {
28530
29609
  unlinkSync2(tempFile);
28531
29610
  } catch {
@@ -28535,7 +29614,7 @@ async function saveAgent(location, agentType, description3, tools, systemPrompt,
28535
29614
  renameSync3(tempFile, filePath);
28536
29615
  } catch (error) {
28537
29616
  try {
28538
- if (existsSync15(tempFile)) {
29617
+ if (existsSync18(tempFile)) {
28539
29618
  unlinkSync2(tempFile);
28540
29619
  }
28541
29620
  } catch (cleanupError) {
@@ -28563,7 +29642,7 @@ async function updateAgent(agent, description3, tools, systemPrompt, color, mode
28563
29642
  const location = agent.location;
28564
29643
  const primaryPath = getPrimaryAgentFilePath(location, agent.agentType);
28565
29644
  const legacyPath = getLegacyAgentFilePath(location, agent.agentType);
28566
- const filePath = existsSync15(primaryPath) ? primaryPath : existsSync15(legacyPath) ? legacyPath : primaryPath;
29645
+ const filePath = existsSync18(primaryPath) ? primaryPath : existsSync18(legacyPath) ? legacyPath : primaryPath;
28567
29646
  ensureDirectoryExists(location);
28568
29647
  writeFileSync6(filePath, content, { encoding: "utf-8", flag: "w" });
28569
29648
  }
@@ -28574,10 +29653,10 @@ async function deleteAgent(agent) {
28574
29653
  const location = agent.location;
28575
29654
  const primaryPath = getPrimaryAgentFilePath(location, agent.agentType);
28576
29655
  const legacyPath = getLegacyAgentFilePath(location, agent.agentType);
28577
- if (existsSync15(primaryPath)) {
29656
+ if (existsSync18(primaryPath)) {
28578
29657
  unlinkSync2(primaryPath);
28579
29658
  }
28580
- if (existsSync15(legacyPath)) {
29659
+ if (existsSync18(legacyPath)) {
28581
29660
  unlinkSync2(legacyPath);
28582
29661
  }
28583
29662
  }
@@ -28596,7 +29675,7 @@ var COLOR_OPTIONS = [
28596
29675
  "cyan"
28597
29676
  ];
28598
29677
  function openInEditor(filePath) {
28599
- return new Promise((resolve11, reject) => {
29678
+ return new Promise((resolve12, reject) => {
28600
29679
  const platform = process.platform;
28601
29680
  let command4;
28602
29681
  let args;
@@ -28619,7 +29698,7 @@ function openInEditor(filePath) {
28619
29698
  child.on("error", (err) => reject(err));
28620
29699
  child.on(
28621
29700
  "exit",
28622
- (code) => code === 0 ? resolve11() : reject(new Error(`Editor exited with ${code}`))
29701
+ (code) => code === 0 ? resolve12() : reject(new Error(`Editor exited with ${code}`))
28623
29702
  );
28624
29703
  });
28625
29704
  }
@@ -29595,8 +30674,8 @@ function ViewAgent(props) {
29595
30674
  if (props.agent.source === "plugin") return `Plugin: ${props.agent.baseDir ?? "Unknown"}`;
29596
30675
  const baseDir = props.agent.baseDir;
29597
30676
  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);
30677
+ if (props.agent.source === "projectSettings") return join14(".claude", "agents", file);
30678
+ if (baseDir) return join14(baseDir, file);
29600
30679
  return props.agent.source;
29601
30680
  })();
29602
30681
  const toolsSummary = () => {
@@ -29981,8 +31060,8 @@ function getCommand(commandName, commands) {
29981
31060
  var TOOL_NAME_FOR_PROMPT7 = "SlashCommand";
29982
31061
 
29983
31062
  // src/tools/interaction/SlashCommandTool/SlashCommandTool.tsx
29984
- var inputSchema12 = z11.strictObject({
29985
- command: z11.string().describe(
31063
+ var inputSchema12 = z13.strictObject({
31064
+ command: z13.string().describe(
29986
31065
  'The slash command to execute with its arguments, e.g., "/review-pr 123"'
29987
31066
  )
29988
31067
  });
@@ -30228,7 +31307,7 @@ function parseMcpToolName2(name3) {
30228
31307
  // src/tools/system/KillShellTool/KillShellTool.tsx
30229
31308
  import { Box as Box75, Text as Text79 } from "ink";
30230
31309
  import React104 from "react";
30231
- import { z as z12 } from "zod";
31310
+ import { z as z14 } from "zod";
30232
31311
 
30233
31312
  // src/tools/system/KillShellTool/prompt.ts
30234
31313
  var TOOL_NAME_FOR_PROMPT8 = "KillShell";
@@ -30242,8 +31321,8 @@ var PROMPT7 = `
30242
31321
  `;
30243
31322
 
30244
31323
  // 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")
31324
+ var inputSchema13 = z14.strictObject({
31325
+ shell_id: z14.string().describe("The ID of the background shell to kill")
30247
31326
  });
30248
31327
  var KillShellTool = {
30249
31328
  name: TOOL_NAME_FOR_PROMPT8,
@@ -31112,7 +32191,7 @@ var BashParser = class {
31112
32191
  };
31113
32192
 
31114
32193
  // src/utils/bash-parser/validator.ts
31115
- import { resolve as resolve9 } from "path";
32194
+ import { resolve as resolve10 } from "path";
31116
32195
  async function validateSafety(script, cwd = process.cwd()) {
31117
32196
  const tree = await BashParser.parse(script);
31118
32197
  const root = tree.rootNode;
@@ -31163,7 +32242,7 @@ function checkCommand(node, script, cwd) {
31163
32242
  const targetsCritical = args.some((arg) => {
31164
32243
  if (arg.startsWith("-") || arg.startsWith("$")) return false;
31165
32244
  try {
31166
- const absPath = resolve9(cwd, arg).replace(/\\/g, "/");
32245
+ const absPath = resolve10(cwd, arg).replace(/\\/g, "/");
31167
32246
  return criticalPaths.some((critical) => {
31168
32247
  const normalizedCritical = critical.endsWith("/") ? critical : critical + "/";
31169
32248
  if (absPath === critical || absPath === critical.replace(/\/$/, "")) return true;
@@ -31181,7 +32260,7 @@ function checkCommand(node, script, cwd) {
31181
32260
  const targetsRoot = args.some((arg) => {
31182
32261
  if (arg.startsWith("-") || arg.startsWith("$")) return false;
31183
32262
  try {
31184
- const absPath = resolve9(cwd, arg).replace(/\\/g, "/");
32263
+ const absPath = resolve10(cwd, arg).replace(/\\/g, "/");
31185
32264
  return absPath === "/" || /^[a-z]:\/?$/i.test(absPath);
31186
32265
  } catch {
31187
32266
  return arg === "/" || /^[a-z]:\/?$/i.test(arg);
@@ -31225,13 +32304,13 @@ function countNewlines(text) {
31225
32304
  }
31226
32305
  return count;
31227
32306
  }
31228
- var inputSchema11 = z13.strictObject({
31229
- command: z13.string().describe("The command to execute"),
31230
- cwd: z13.string().optional().describe(
32307
+ var inputSchema11 = z15.strictObject({
32308
+ command: z15.string().describe("The command to execute"),
32309
+ cwd: z15.string().optional().describe(
31231
32310
  "The directory to execute the command in. Use absolute path or path relative to the project root."
31232
32311
  ),
31233
- timeout: z13.number().optional().describe("Optional timeout in milliseconds (max 600000)"),
31234
- description: z13.string().optional().describe(
32312
+ timeout: z15.number().optional().describe("Optional timeout in milliseconds (max 600000)"),
32313
+ description: z15.string().optional().describe(
31235
32314
  `Clear, concise description of what this command does in 5-10 words, in active voice. Examples:
31236
32315
  Input: ls
31237
32316
  Output: List files in current directory
@@ -31245,10 +32324,10 @@ Output: Install package dependencies
31245
32324
  Input: mkdir foo
31246
32325
  Output: Create directory 'foo'`
31247
32326
  ),
31248
- run_in_background: z13.boolean().optional().describe(
32327
+ run_in_background: z15.boolean().optional().describe(
31249
32328
  "Set to true to run this command in the background. Use TaskOutput to read the output later."
31250
32329
  ),
31251
- dangerouslyDisableSandbox: z13.boolean().optional().describe(
32330
+ dangerouslyDisableSandbox: z15.boolean().optional().describe(
31252
32331
  "Set this to true to dangerously override sandbox mode and run commands without sandboxing."
31253
32332
  )
31254
32333
  });
@@ -31289,7 +32368,7 @@ var BashTool = {
31289
32368
  async validateInput({ command: command4, timeout, dangerouslyDisableSandbox, cwd }, context) {
31290
32369
  const trimmed = command4.trim();
31291
32370
  try {
31292
- await validateSafety(trimmed, cwd ? resolve10(getCwd(), cwd) : getCwd());
32371
+ await validateSafety(trimmed, cwd ? resolve11(getCwd(), cwd) : getCwd());
31293
32372
  } catch (e) {
31294
32373
  return {
31295
32374
  result: false,
@@ -31329,7 +32408,7 @@ var BashTool = {
31329
32408
  };
31330
32409
  }
31331
32410
  if (cwd) {
31332
- const fullTargetDir = isAbsolute8(cwd) ? cwd : resolve10(getCwd(), cwd);
32411
+ const fullTargetDir = isAbsolute8(cwd) ? cwd : resolve11(getCwd(), cwd);
31333
32412
  if (!isInDirectory(
31334
32413
  relative12(getOriginalCwd(), fullTargetDir),
31335
32414
  relative12(getCwd(), getOriginalCwd())
@@ -31349,7 +32428,7 @@ var BashTool = {
31349
32428
  continue;
31350
32429
  }
31351
32430
  const targetDir = parts[1].replace(/^['"]|['"]$/g, "");
31352
- const fullTargetDir = isAbsolute8(targetDir) ? targetDir : resolve10(getCwd(), targetDir);
32431
+ const fullTargetDir = isAbsolute8(targetDir) ? targetDir : resolve11(getCwd(), targetDir);
31353
32432
  if (!isInDirectory(
31354
32433
  relative12(getOriginalCwd(), fullTargetDir),
31355
32434
  relative12(getCwd(), getOriginalCwd())
@@ -31460,7 +32539,7 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31460
32539
  const safeMode = Boolean(context?.safeMode ?? context?.options?.safeMode);
31461
32540
  const userPrompt = typeof context?.options?.lastUserPrompt === "string" ? context.options.lastUserPrompt.trim() : "";
31462
32541
  const commandDescription = typeof description3 === "string" ? description3.trim() : "";
31463
- const effectiveCwd = cwd ? isAbsolute8(cwd) ? cwd : resolve10(getCwd(), cwd) : getCwd();
32542
+ const effectiveCwd = cwd ? isAbsolute8(cwd) ? cwd : resolve11(getCwd(), cwd) : getCwd();
31464
32543
  try {
31465
32544
  await validateSafety(command4, effectiveCwd);
31466
32545
  } catch (error) {
@@ -31610,7 +32689,7 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31610
32689
  if (abortController.signal.aborted) return false;
31611
32690
  const hostForUrl = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
31612
32691
  const url2 = `http://${hostForUrl}:${port}/`;
31613
- return await new Promise((resolve11) => {
32692
+ return await new Promise((resolve12) => {
31614
32693
  const assistantMessage = createAssistantMessage("");
31615
32694
  if (context.messageId) {
31616
32695
  ;
@@ -31626,13 +32705,13 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31626
32705
  suggestions: void 0,
31627
32706
  riskScore: null,
31628
32707
  onAbort() {
31629
- resolve11(false);
32708
+ resolve12(false);
31630
32709
  },
31631
32710
  onAllow() {
31632
- resolve11(true);
32711
+ resolve12(true);
31633
32712
  },
31634
32713
  onReject() {
31635
- resolve11(false);
32714
+ resolve12(false);
31636
32715
  }
31637
32716
  };
31638
32717
  setToolJSX({
@@ -31726,8 +32805,8 @@ Did you mean "git ${cmdParts.slice(1).join(" ")}"?`;
31726
32805
  );
31727
32806
  let backgroundRequested = false;
31728
32807
  let resolveBackground = null;
31729
- const backgroundPromise = new Promise((resolve11) => {
31730
- resolveBackground = resolve11;
32808
+ const backgroundPromise = new Promise((resolve12) => {
32809
+ resolveBackground = resolve12;
31731
32810
  });
31732
32811
  const requestBackground = () => {
31733
32812
  if (backgroundRequested) return;
@@ -31770,7 +32849,7 @@ ${footerParts.join(" ")}`;
31770
32849
  bashId
31771
32850
  })),
31772
32851
  new Promise(
31773
- (resolve11) => setTimeout(() => resolve11({ kind: "tick" }), waitMs)
32852
+ (resolve12) => setTimeout(() => resolve12({ kind: "tick" }), waitMs)
31774
32853
  )
31775
32854
  ]);
31776
32855
  if (race.kind === "background") {
@@ -31804,7 +32883,7 @@ ${footerParts.join(" ")}`;
31804
32883
  if (process.env.NODE_ENV !== "test") {
31805
32884
  getCommandFilePaths(command4, stdout).then((filePaths) => {
31806
32885
  for (const filePath of filePaths) {
31807
- const fullFilePath = isAbsolute8(filePath) ? filePath : resolve10(getCwd(), filePath);
32886
+ const fullFilePath = isAbsolute8(filePath) ? filePath : resolve11(getCwd(), filePath);
31808
32887
  try {
31809
32888
  readFileTimestamps[fullFilePath] = statSync13(fullFilePath).mtimeMs;
31810
32889
  } catch (e) {
@@ -32118,6 +33197,7 @@ export {
32118
33197
  KillShellTool,
32119
33198
  hasPermissionsToUseTool,
32120
33199
  BashTool,
33200
+ getModelCapabilities,
32121
33201
  getCLISyspromptPrefix,
32122
33202
  getSystemPrompt,
32123
33203
  getEnvInfo,
@@ -32126,6 +33206,8 @@ export {
32126
33206
  getReasoningEffort,
32127
33207
  generatePybContext,
32128
33208
  refreshPybContext,
33209
+ emitTelemetryEvent,
33210
+ resolveModelResponsePolicy,
32129
33211
  formatSystemPromptWithContext,
32130
33212
  useExitOnCtrlCD,
32131
33213
  clearTerminal,