@cjhyy/code-shell 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/anthropic-OVRWAZRD.js +1 -0
  2. package/dist/arena/index.js +1 -104
  3. package/dist/arena-64T2EQD4.js +3 -0
  4. package/dist/bwrap-PVZMLHZR.js +2 -0
  5. package/dist/chunk-2EUIMKJA.js +1 -0
  6. package/dist/chunk-2GJ7H5NC.js +641 -0
  7. package/dist/chunk-2OD6VR4N.js +2 -0
  8. package/dist/chunk-3QP5BQ3L.js +1 -0
  9. package/dist/chunk-A4M2Y42L.js +2 -0
  10. package/dist/chunk-DEYFK6FP.js +1 -0
  11. package/dist/chunk-DTPABBSV.js +2 -0
  12. package/dist/chunk-EU3J7TBP.js +1 -0
  13. package/dist/chunk-FU7AHZNN.js +1 -0
  14. package/dist/chunk-L7B2ORID.js +4 -0
  15. package/dist/chunk-M7VU4YVY.js +49 -0
  16. package/dist/chunk-MGP35GKD.js +254 -0
  17. package/dist/chunk-MLCTC53I.js +1 -0
  18. package/dist/chunk-O5HFCH2U.js +1 -0
  19. package/dist/chunk-P6JSTIFM.js +1 -0
  20. package/dist/chunk-Q3RSX66I.js +1 -0
  21. package/dist/chunk-QTWU7UNA.js +5 -0
  22. package/dist/chunk-RERBX75D.js +251 -0
  23. package/dist/chunk-SNFAPSLA.js +1 -0
  24. package/dist/chunk-T222K6IV.js +18 -0
  25. package/dist/chunk-TKJA6W36.js +3 -0
  26. package/dist/chunk-VKKU4LOM.js +3 -0
  27. package/dist/chunk-WI6FSWGU.js +1 -0
  28. package/dist/chunk-XXCZE2U2.js +2 -0
  29. package/dist/chunk-ZSAONDT6.js +2 -0
  30. package/dist/cli/main.js +303 -22060
  31. package/dist/cli/onboarding.d.ts +7 -2
  32. package/dist/client-base-F5FCRSB3.js +1 -0
  33. package/dist/compaction-L3Y6NG4N.js +1 -0
  34. package/dist/context/compaction.d.ts +2 -1
  35. package/dist/data/static-catalogs.d.ts +25 -0
  36. package/dist/devtools-SGDUOOM4.js +1 -0
  37. package/dist/engine/engine.d.ts +24 -0
  38. package/dist/engine/turn-loop.d.ts +20 -0
  39. package/dist/export-md-U72T7NW7.js +22 -0
  40. package/dist/file-history-7FQFEQOL.js +1 -0
  41. package/dist/index.d.ts +1 -1
  42. package/dist/index.js +1 -347
  43. package/dist/llm/capabilities/index.d.ts +20 -0
  44. package/dist/llm/capabilities/rules.d.ts +26 -0
  45. package/dist/llm/capabilities/types.d.ts +108 -0
  46. package/dist/llm/model-pool.d.ts +7 -0
  47. package/dist/llm/provider-catalog.d.ts +2 -0
  48. package/dist/llm/provider-kinds.d.ts +1 -1
  49. package/dist/llm/providers/openai.d.ts +22 -0
  50. package/dist/llm/token-counter.d.ts +17 -0
  51. package/dist/llm/types.d.ts +8 -0
  52. package/dist/logging/logger.d.ts +10 -2
  53. package/dist/logging/session-recorder.d.ts +16 -3
  54. package/dist/manager-J6FXEUEK.js +1 -0
  55. package/dist/mcp-manager-27EVBKRT.js +1 -0
  56. package/dist/memory-BNI4WEWL.js +1 -0
  57. package/dist/model-cache-HEDXI7UJ.js +1 -0
  58. package/dist/model-fetcher-X5W5EASG.js +1 -0
  59. package/dist/off-7SDVMMXW.js +1 -0
  60. package/dist/openai-3QEADSYL.js +1 -0
  61. package/dist/openrouter-models-GZVCRWD2.js +1 -0
  62. package/dist/openrouter-sync-WG4AG5NC.js +1 -0
  63. package/dist/product/index.js +1 -21
  64. package/dist/protocol/client.d.ts +1 -1
  65. package/dist/run/index.js +1 -48
  66. package/dist/seatbelt-L54CNI2Y.js +37 -0
  67. package/dist/session/session-manager.d.ts +2 -0
  68. package/dist/session-manager-AGWS5SMJ.js +1 -0
  69. package/dist/settings/schema.d.ts +147 -21
  70. package/dist/tool-summary-V2B3MD5N.js +2 -0
  71. package/dist/tool-system/builtin/bash.d.ts +7 -1
  72. package/dist/tool-system/context.d.ts +7 -0
  73. package/dist/tool-system/executor.d.ts +4 -0
  74. package/dist/tool-system/sandbox/bwrap.d.ts +13 -0
  75. package/dist/tool-system/sandbox/index.d.ts +78 -0
  76. package/dist/tool-system/sandbox/off.d.ts +2 -0
  77. package/dist/tool-system/sandbox/seatbelt.d.ts +18 -0
  78. package/dist/tool-system/task-guard.d.ts +30 -0
  79. package/dist/types.d.ts +17 -0
  80. package/dist/ui/components/SessionPicker.d.ts +2 -0
  81. package/dist/ui/components/SpinnerWithVerb.d.ts +7 -2
  82. package/dist/ui/components/StatusLine.d.ts +7 -3
  83. package/dist/updater-OCNU2K2Z.js +1 -0
  84. package/package.json +7 -10
  85. package/dist/anthropic-IBTI4WL2.cjs +0 -10
  86. package/dist/anthropic-PRZZKHEZ.js +0 -10
  87. package/dist/arena/index.cjs +0 -104
  88. package/dist/arena-2LTLIXOL.js +0 -261
  89. package/dist/arena-ADB7DRFI.cjs +0 -261
  90. package/dist/chunk-2YW4FPFG.cjs +0 -101
  91. package/dist/chunk-3OA5G4TM.js +0 -47
  92. package/dist/chunk-3QO25N6E.js +0 -4711
  93. package/dist/chunk-3SBSUOWZ.js +0 -447
  94. package/dist/chunk-52LGZKT3.cjs +0 -47
  95. package/dist/chunk-55XGPMAP.cjs +0 -146
  96. package/dist/chunk-6QVAYW7C.cjs +0 -438
  97. package/dist/chunk-6S4BJ65N.js +0 -113
  98. package/dist/chunk-76HYEPDM.js +0 -307
  99. package/dist/chunk-7BI3V74Y.cjs +0 -447
  100. package/dist/chunk-7EG3V4JY.cjs +0 -113
  101. package/dist/chunk-7JVTYEEC.js +0 -340
  102. package/dist/chunk-7QIM3BKD.js +0 -44
  103. package/dist/chunk-7Y6S3OCX.js +0 -438
  104. package/dist/chunk-ABRRONJ7.js +0 -107
  105. package/dist/chunk-BSW22MPA.js +0 -146
  106. package/dist/chunk-BXCY2FSE.js +0 -203
  107. package/dist/chunk-BZ5TNE7L.js +0 -5128
  108. package/dist/chunk-DDB6QOKJ.cjs +0 -1252
  109. package/dist/chunk-HEKQCI7B.cjs +0 -224
  110. package/dist/chunk-IK4EWJBP.cjs +0 -203
  111. package/dist/chunk-ILHE7XLT.cjs +0 -107
  112. package/dist/chunk-JMR33QVF.cjs +0 -169
  113. package/dist/chunk-KAQHULYN.js +0 -54
  114. package/dist/chunk-KE4EQOWA.js +0 -294
  115. package/dist/chunk-KOVYSDHZ.cjs +0 -340
  116. package/dist/chunk-KS3RYAYL.cjs +0 -45
  117. package/dist/chunk-MD32R22I.js +0 -50
  118. package/dist/chunk-MV7YI4WO.cjs +0 -293
  119. package/dist/chunk-MY5XHADU.cjs +0 -216
  120. package/dist/chunk-NUNC3VFB.cjs +0 -307
  121. package/dist/chunk-PKGRTCCY.js +0 -9092
  122. package/dist/chunk-QARL3IDQ.js +0 -1252
  123. package/dist/chunk-S754JHLR.cjs +0 -54
  124. package/dist/chunk-SFXHZSRF.js +0 -101
  125. package/dist/chunk-SIHHIQLO.js +0 -224
  126. package/dist/chunk-T6VYG46N.js +0 -105
  127. package/dist/chunk-TNLGBJYS.cjs +0 -44
  128. package/dist/chunk-TUY2T5KP.cjs +0 -105
  129. package/dist/chunk-UXOCVJJ6.cjs +0 -9092
  130. package/dist/chunk-VIAGTYYW.js +0 -169
  131. package/dist/chunk-WASS5YWB.js +0 -215
  132. package/dist/chunk-WZJV6DJC.cjs +0 -5128
  133. package/dist/chunk-YIQBXAYU.cjs +0 -264
  134. package/dist/chunk-YKIAELDZ.cjs +0 -4711
  135. package/dist/chunk-ZBPSQCPU.js +0 -264
  136. package/dist/cli/main.cjs +0 -22156
  137. package/dist/client-base-HTF236ZD.cjs +0 -9
  138. package/dist/client-base-QKRKCOWB.js +0 -9
  139. package/dist/compaction-6VU2T643.js +0 -33
  140. package/dist/compaction-OKUNTCA7.cjs +0 -33
  141. package/dist/devtools-T2NIZBJK.cjs +0 -6
  142. package/dist/devtools-YXWHOVKR.js +0 -6
  143. package/dist/export-md-RXDW6F5W.cjs +0 -135
  144. package/dist/export-md-XXKZANW5.js +0 -135
  145. package/dist/file-history-KYPE3ECT.cjs +0 -7
  146. package/dist/file-history-LF4F7X26.js +0 -7
  147. package/dist/index.cjs +0 -347
  148. package/dist/manager-D65VFAPX.js +0 -7
  149. package/dist/manager-TTF5VHJC.cjs +0 -7
  150. package/dist/mcp-manager-QMKWPBZ4.js +0 -8
  151. package/dist/mcp-manager-Z3OKI74O.cjs +0 -8
  152. package/dist/memory-5LWZ6FI2.cjs +0 -9
  153. package/dist/memory-VIJLBAMQ.js +0 -9
  154. package/dist/model-cache-5KIYL5SL.js +0 -13
  155. package/dist/model-cache-OED3IM4R.cjs +0 -13
  156. package/dist/model-fetcher-HKGICACL.js +0 -8
  157. package/dist/model-fetcher-UR6WJOQP.cjs +0 -8
  158. package/dist/openai-JR2WEKOF.js +0 -10
  159. package/dist/openai-YBTOET4O.cjs +0 -10
  160. package/dist/openrouter-models-H56GHBHN.js +0 -15
  161. package/dist/openrouter-models-TWUFWZ5T.cjs +0 -15
  162. package/dist/openrouter-sync-5VMGN6C2.cjs +0 -11
  163. package/dist/openrouter-sync-ALEMF5IU.js +0 -11
  164. package/dist/product/index.cjs +0 -21
  165. package/dist/run/index.cjs +0 -48
  166. package/dist/session-manager-Q22BBMD3.js +0 -8
  167. package/dist/session-manager-XODQVL3C.cjs +0 -8
  168. package/dist/tool-summary-63DPIS7G.cjs +0 -31
  169. package/dist/tool-summary-NP5CDBKG.js +0 -31
  170. package/dist/updater-I7QBW4DP.cjs +0 -17
  171. package/dist/updater-NVME5S3Z.js +0 -17
@@ -1,438 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
-
5
- var _chunkKS3RYAYLcjs = require('./chunk-KS3RYAYL.cjs');
6
-
7
- // src/context/token-counter.ts
8
- function estimateStringTokens(text) {
9
- if (!text) return 0;
10
- const cjkChars = (_nullishCoalesce(text.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g), () => ( []))).length;
11
- const cjkRatio = cjkChars / text.length;
12
- if (cjkRatio > 0.3) {
13
- const cjkTokens = cjkChars / RATIOS.cjk;
14
- const otherChars = text.length - cjkChars;
15
- const otherTokens = otherChars / RATIOS.english;
16
- return Math.ceil(cjkTokens + otherTokens);
17
- }
18
- const codeIndicators = ["{", "}", "(", ")", ";", "=>", "import ", "function ", "class ", "const "];
19
- const codeScore = codeIndicators.reduce((s, ind) => s + (text.includes(ind) ? 1 : 0), 0);
20
- if (codeScore >= 3) return Math.ceil(text.length / RATIOS.code);
21
- if (text.startsWith("{") || text.startsWith("[")) return Math.ceil(text.length / RATIOS.json);
22
- return Math.ceil(text.length / RATIOS.english);
23
- }
24
- function estimateMessagesTokens(messages) {
25
- let total = 0;
26
- for (const msg of messages) {
27
- total += 4;
28
- if (typeof msg.content === "string") {
29
- total += estimateStringTokens(msg.content);
30
- } else if (Array.isArray(msg.content)) {
31
- for (const block of msg.content) {
32
- total += estimateBlockTokens(block);
33
- }
34
- }
35
- }
36
- return total;
37
- }
38
- function estimateBlockTokens(block) {
39
- let tokens = 2;
40
- if (block.text) tokens += estimateStringTokens(block.text);
41
- if (block.content && typeof block.content === "string") {
42
- tokens += estimateStringTokens(block.content);
43
- }
44
- if (block.input) {
45
- tokens += estimateStringTokens(JSON.stringify(block.input));
46
- }
47
- if (block.name) tokens += estimateStringTokens(block.name);
48
- return tokens;
49
- }
50
- var RATIOS;
51
- var init_token_counter = _chunkKS3RYAYLcjs.__esm.call(void 0, {
52
- "src/context/token-counter.ts"() {
53
- "use strict";
54
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
55
- RATIOS = {
56
- english: 4,
57
- // ~4 chars per token for English prose
58
- code: 3.2,
59
- // ~3.2 chars per token for code (more tokens per char)
60
- json: 3.5,
61
- // JSON structures
62
- mixed: 3.6,
63
- // Mixed content (typical for tool results)
64
- cjk: 1.5
65
- // CJK characters: ~1.5 chars per token
66
- };
67
- }
68
- });
69
-
70
- // src/context/compaction.ts
71
- var compaction_exports = {};
72
- _chunkKS3RYAYLcjs.__export.call(void 0, compaction_exports, {
73
- COMPACTABLE_TOOL_NAMES: () => COMPACTABLE_TOOL_NAMES,
74
- adjustIndexToPreserveAPIInvariants: () => adjustIndexToPreserveAPIInvariants,
75
- applySummaryCompaction: () => applySummaryCompaction,
76
- applyToolResultBudget: () => applyToolResultBudget,
77
- buildSummarizationPrompt: () => buildSummarizationPrompt,
78
- dropOldestRounds: () => dropOldestRounds,
79
- estimateTokens: () => estimateTokens,
80
- extractReferencedFilePaths: () => extractReferencedFilePaths,
81
- groupMessagesByApiRound: () => groupMessagesByApiRound,
82
- microcompact: () => microcompact,
83
- snipCompact: () => snipCompact,
84
- truncateToolResult: () => truncateToolResult,
85
- windowCompact: () => windowCompact
86
- });
87
- function estimateTokens(messages) {
88
- return Math.ceil(estimateMessagesTokens(messages) * (4 / 3));
89
- }
90
- function adjustIndexToPreserveAPIInvariants(messages, startIndex) {
91
- let adjusted = startIndex;
92
- const neededToolUseIds = /* @__PURE__ */ new Set();
93
- for (let i = adjusted; i < messages.length; i++) {
94
- const msg = messages[i];
95
- if (!Array.isArray(msg.content)) continue;
96
- for (const block of msg.content) {
97
- if (block.type === "tool_result" && block.tool_use_id) {
98
- neededToolUseIds.add(block.tool_use_id);
99
- }
100
- }
101
- }
102
- for (let i = adjusted; i < messages.length; i++) {
103
- const msg = messages[i];
104
- if (!Array.isArray(msg.content)) continue;
105
- for (const block of msg.content) {
106
- if (block.type === "tool_use" && block.id) {
107
- neededToolUseIds.delete(block.id);
108
- }
109
- }
110
- }
111
- if (neededToolUseIds.size === 0) return adjusted;
112
- for (let i = adjusted - 1; i >= 0 && neededToolUseIds.size > 0; i--) {
113
- const msg = messages[i];
114
- if (msg.role !== "assistant" || !Array.isArray(msg.content)) continue;
115
- for (const block of msg.content) {
116
- if (block.type === "tool_use" && block.id && neededToolUseIds.has(block.id)) {
117
- neededToolUseIds.delete(block.id);
118
- if (i < adjusted) adjusted = i;
119
- }
120
- }
121
- }
122
- return adjusted;
123
- }
124
- function snipCompact(messages, keepFirstN = 3, keepLastM = 8) {
125
- if (messages.length <= keepFirstN + keepLastM + 1) return messages;
126
- let lastStart = messages.length - keepLastM;
127
- lastStart = adjustIndexToPreserveAPIInvariants(messages, lastStart);
128
- if (lastStart <= keepFirstN) return messages;
129
- const snippedCount = lastStart - keepFirstN;
130
- const snipMarker = {
131
- role: "user",
132
- content: `<system-reminder>[${snippedCount} messages snipped to save context. Use the transcript file to review details if needed.]</system-reminder>`
133
- };
134
- return [
135
- ...messages.slice(0, keepFirstN),
136
- snipMarker,
137
- ...messages.slice(lastStart)
138
- ];
139
- }
140
- function windowCompact(messages, keepLastN) {
141
- if (messages.length <= keepLastN + 1) return messages;
142
- let startIndex = messages.length - keepLastN;
143
- startIndex = adjustIndexToPreserveAPIInvariants(messages, startIndex);
144
- if (startIndex <= 1) return messages;
145
- return [messages[0], ...messages.slice(startIndex)];
146
- }
147
- function buildToolUseIdToNameMap(messages) {
148
- const map = /* @__PURE__ */ new Map();
149
- for (const msg of messages) {
150
- if (!Array.isArray(msg.content)) continue;
151
- for (const block of msg.content) {
152
- if (block.type === "tool_use" && block.id && block.name) {
153
- map.set(block.id, block.name);
154
- }
155
- }
156
- }
157
- return map;
158
- }
159
- function summarizeToolCallArgs(toolName, input) {
160
- if (!input || typeof input !== "object") return "";
161
- const pick = (keys) => {
162
- const parts = [];
163
- for (const key of keys) {
164
- const v = input[key];
165
- if (typeof v === "string" && v.length > 0) {
166
- parts.push(`${key}=${v.length > 80 ? v.slice(0, 77) + "..." : v}`);
167
- }
168
- }
169
- return parts.join(" ");
170
- };
171
- switch (toolName) {
172
- case "Read":
173
- case "Write":
174
- case "Edit":
175
- case "NotebookEdit":
176
- return pick(["file_path", "path", "notebook_path"]);
177
- case "Glob":
178
- case "Grep":
179
- return pick(["pattern", "path", "glob"]);
180
- case "Bash":
181
- case "PowerShell":
182
- case "REPL":
183
- return pick(["command"]);
184
- case "WebFetch":
185
- case "WebSearch":
186
- return pick(["url", "query"]);
187
- default: {
188
- const json = JSON.stringify(input);
189
- return json.length > 100 ? json.slice(0, 97) + "..." : json;
190
- }
191
- }
192
- }
193
- function microcompact(messages, options = {}) {
194
- const keepRecentN = _nullishCoalesce(options.keepRecentN, () => ( 5));
195
- const compactable = _nullishCoalesce(options.compactableTools, () => ( COMPACTABLE_TOOL_NAMES));
196
- const idToName = buildToolUseIdToNameMap(messages);
197
- const idToInput = /* @__PURE__ */ new Map();
198
- for (const msg of messages) {
199
- if (!Array.isArray(msg.content)) continue;
200
- for (const block of msg.content) {
201
- if (block.type === "tool_use" && block.id) {
202
- idToInput.set(block.id, block.input);
203
- }
204
- }
205
- }
206
- let compactableRoundCount = 0;
207
- const indicesToTouch = [];
208
- for (let i = messages.length - 1; i >= 0; i--) {
209
- const msg = messages[i];
210
- if (!Array.isArray(msg.content)) continue;
211
- const hasEligible = msg.content.some(
212
- (b) => b.type === "tool_result" && b.tool_use_id != null && compactable.has(_nullishCoalesce(idToName.get(b.tool_use_id), () => ( ""))) && typeof b.content === "string" && !b.content.startsWith("[Old tool result cleared")
213
- );
214
- if (!hasEligible) continue;
215
- compactableRoundCount++;
216
- if (compactableRoundCount > keepRecentN) {
217
- indicesToTouch.push(i);
218
- }
219
- }
220
- if (indicesToTouch.length === 0) return messages;
221
- const touchSet = new Set(indicesToTouch);
222
- const clearedToolNames = /* @__PURE__ */ new Set();
223
- let clearedBlocks = 0;
224
- const result = messages.map((msg, i) => {
225
- if (!touchSet.has(i) || !Array.isArray(msg.content)) return msg;
226
- return {
227
- ...msg,
228
- content: msg.content.map((block) => {
229
- if (block.type !== "tool_result" || !block.tool_use_id) return block;
230
- const toolName = idToName.get(block.tool_use_id);
231
- if (!toolName || !compactable.has(toolName)) return block;
232
- if (typeof block.content !== "string") return block;
233
- if (block.content.startsWith("[Old tool result cleared")) return block;
234
- const argsSummary = summarizeToolCallArgs(toolName, idToInput.get(block.tool_use_id));
235
- const fingerprint = argsSummary ? `[Old tool result cleared \u2014 ${toolName} ${argsSummary}]` : `[Old tool result cleared \u2014 ${toolName}]`;
236
- clearedToolNames.add(toolName);
237
- clearedBlocks++;
238
- return { ...block, content: fingerprint };
239
- })
240
- };
241
- });
242
- if (clearedBlocks > 0) {
243
- _optionalChain([options, 'access', _ => _.onClear, 'optionalCall', _2 => _2({
244
- clearedRounds: indicesToTouch.length,
245
- toolNames: [...clearedToolNames].sort()
246
- })]);
247
- }
248
- return result;
249
- }
250
- function applyToolResultBudget(messages, maxTotalChars = 1e5) {
251
- return messages.map((msg) => {
252
- if (!Array.isArray(msg.content)) return msg;
253
- const resultBlocks = [];
254
- let totalSize = 0;
255
- for (let i = 0; i < msg.content.length; i++) {
256
- const block = msg.content[i];
257
- if (block.type === "tool_result" && typeof block.content === "string") {
258
- const size = block.content.length;
259
- resultBlocks.push({ index: i, size });
260
- totalSize += size;
261
- }
262
- }
263
- if (totalSize <= maxTotalChars || resultBlocks.length === 0) return msg;
264
- resultBlocks.sort((a, b) => b.size - a.size);
265
- let remaining = totalSize;
266
- const toTruncate = /* @__PURE__ */ new Set();
267
- for (const rb of resultBlocks) {
268
- if (remaining <= maxTotalChars) break;
269
- toTruncate.add(rb.index);
270
- remaining -= rb.size;
271
- remaining += 200;
272
- }
273
- if (toTruncate.size === 0) return msg;
274
- const newContent = msg.content.map((block, i) => {
275
- if (!toTruncate.has(i)) return block;
276
- const preview = typeof block.content === "string" ? block.content.slice(0, 500) : "";
277
- const sizeKb = (block.content.length / 1e3).toFixed(0);
278
- return {
279
- ...block,
280
- content: `Output too large (${sizeKb}KB) \u2014 truncated to fit the per-message budget. Re-run the originating tool if you need the full output.
281
-
282
- Preview (first 500 chars):
283
- ${preview}`
284
- };
285
- });
286
- return { ...msg, content: newContent };
287
- });
288
- }
289
- function truncateToolResult(result, maxChars = 3e4) {
290
- if (result.length <= maxChars) return result;
291
- const headSize = Math.floor(maxChars * 0.7);
292
- const tailSize = Math.floor(maxChars * 0.2);
293
- const head = result.slice(0, headSize);
294
- const tail = result.slice(-tailSize);
295
- return head + `
296
-
297
- ... [${result.length - headSize - tailSize} characters truncated] ...
298
-
299
- ` + tail;
300
- }
301
- function buildSummarizationPrompt(messagesToSummarize) {
302
- const parts = [];
303
- for (const msg of messagesToSummarize) {
304
- if (typeof msg.content === "string") {
305
- parts.push(`[${msg.role}]: ${msg.content.slice(0, 3e3)}`);
306
- } else {
307
- for (const block of msg.content) {
308
- if (block.type === "text" && block.text) {
309
- parts.push(`[${msg.role}]: ${block.text.slice(0, 3e3)}`);
310
- } else if (block.type === "tool_use") {
311
- const args = JSON.stringify(block.input).slice(0, 500);
312
- parts.push(`[tool_use]: ${block.name}(${args})`);
313
- } else if (block.type === "tool_result") {
314
- const content = typeof block.content === "string" ? block.content : "";
315
- parts.push(`[tool_result]: ${content.slice(0, 1500)}`);
316
- }
317
- }
318
- }
319
- }
320
- return "Summarize the following conversation into these sections. Be factual. Preserve file paths, function names, and error messages exactly.\n\n1. **Primary Request**: What the user originally asked for\n2. **Key Concepts**: Important technical terms, patterns, file paths\n3. **Files Referenced**: List of files read/edited with key content\n4. **Errors & Fixes**: Any errors encountered and how they were resolved\n5. **Actions Taken**: Tools used and their outcomes\n6. **User Messages**: All distinct user requests (verbatim if short)\n7. **Pending Tasks**: Anything started but not finished\n8. **Current State**: Where things stand right now\n9. **Next Steps**: What should happen next\n\nConversation:\n\n" + parts.join("\n");
321
- }
322
- function applySummaryCompaction(messages, summary, keepRecentN, transcriptPath) {
323
- if (messages.length <= keepRecentN + 2) return messages;
324
- let startIndex = messages.length - keepRecentN;
325
- startIndex = adjustIndexToPreserveAPIInvariants(messages, startIndex);
326
- if (startIndex <= 1) return messages;
327
- const first = messages[0];
328
- const compactedMessages = messages.slice(1, startIndex);
329
- const recent = messages.slice(startIndex);
330
- const referencedFiles = extractReferencedFilePaths(compactedMessages);
331
- let body = `This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.
332
-
333
- ${summary}`;
334
- if (transcriptPath) {
335
- body += `
336
-
337
- If you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: ${transcriptPath}`;
338
- }
339
- if (referencedFiles.length > 0) {
340
- body += `
341
-
342
- Files referenced before compaction (use Read tool if you need their current content):
343
- ` + referencedFiles.map((f) => `- ${f}`).join("\n");
344
- }
345
- body += `
346
-
347
- Recent messages are preserved verbatim below. Continue from where you left off.`;
348
- const summaryMsg = {
349
- role: "user",
350
- content: `<system-reminder>${body}</system-reminder>`
351
- };
352
- return [first, summaryMsg, ...recent];
353
- }
354
- function groupMessagesByApiRound(messages) {
355
- const groups = [];
356
- let current = [];
357
- for (const msg of messages) {
358
- if (msg.role === "assistant" && current.length > 0) {
359
- groups.push(current);
360
- current = [msg];
361
- } else {
362
- current.push(msg);
363
- }
364
- }
365
- if (current.length > 0) groups.push(current);
366
- return groups;
367
- }
368
- function dropOldestRounds(messages, roundsToDrop) {
369
- const groups = groupMessagesByApiRound(messages);
370
- if (groups.length <= roundsToDrop + 1) {
371
- return groups[groups.length - 1];
372
- }
373
- const kept = groups.slice(roundsToDrop).flat();
374
- const safeStart = adjustIndexToPreserveAPIInvariants(
375
- kept,
376
- 0
377
- // already sliced, just validate from start
378
- );
379
- const result = kept.slice(safeStart);
380
- if (result.length > 0 && result[0].role === "assistant") {
381
- result.unshift({
382
- role: "user",
383
- content: "<system-reminder>Earlier conversation context was removed to fit within the context window. Continue from the assistant's response below.</system-reminder>"
384
- });
385
- }
386
- return result;
387
- }
388
- function extractReferencedFilePaths(messages) {
389
- const paths = /* @__PURE__ */ new Set();
390
- const FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write", "Glob", "Grep"]);
391
- for (const msg of messages) {
392
- if (!Array.isArray(msg.content)) continue;
393
- for (const block of msg.content) {
394
- if (block.type === "tool_use" && block.name && FILE_TOOLS.has(block.name) && block.input) {
395
- const input = block.input;
396
- const fp = _nullishCoalesce(input.file_path, () => ( input.path));
397
- if (fp) paths.add(fp);
398
- }
399
- }
400
- }
401
- return [...paths];
402
- }
403
- var COMPACTABLE_TOOL_NAMES;
404
- var init_compaction = _chunkKS3RYAYLcjs.__esm.call(void 0, {
405
- "src/context/compaction.ts"() {
406
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
407
- init_token_counter();
408
- COMPACTABLE_TOOL_NAMES = exports.COMPACTABLE_TOOL_NAMES = /* @__PURE__ */ new Set([
409
- "Read",
410
- "Glob",
411
- "Grep",
412
- "Bash",
413
- "PowerShell",
414
- "NotebookEdit",
415
- "WebFetch",
416
- "WebSearch",
417
- "REPL"
418
- ]);
419
- }
420
- });
421
-
422
-
423
-
424
-
425
-
426
-
427
-
428
-
429
-
430
-
431
-
432
-
433
-
434
-
435
-
436
-
437
-
438
- exports.estimateTokens = estimateTokens; exports.adjustIndexToPreserveAPIInvariants = adjustIndexToPreserveAPIInvariants; exports.snipCompact = snipCompact; exports.windowCompact = windowCompact; exports.COMPACTABLE_TOOL_NAMES = COMPACTABLE_TOOL_NAMES; exports.microcompact = microcompact; exports.applyToolResultBudget = applyToolResultBudget; exports.truncateToolResult = truncateToolResult; exports.buildSummarizationPrompt = buildSummarizationPrompt; exports.applySummaryCompaction = applySummaryCompaction; exports.groupMessagesByApiRound = groupMessagesByApiRound; exports.dropOldestRounds = dropOldestRounds; exports.extractReferencedFilePaths = extractReferencedFilePaths; exports.compaction_exports = compaction_exports; exports.init_compaction = init_compaction;
@@ -1,113 +0,0 @@
1
- import {
2
- ContextLimitError,
3
- LLMError,
4
- LLMRateLimitError
5
- } from "./chunk-SFXHZSRF.js";
6
- import {
7
- logger
8
- } from "./chunk-BXCY2FSE.js";
9
- import {
10
- init_esm_shims
11
- } from "./chunk-MD32R22I.js";
12
-
13
- // src/llm/client-base.ts
14
- init_esm_shims();
15
- var LLMClientBase = class _LLMClientBase {
16
- constructor(config) {
17
- this.config = config;
18
- this.provider = config.provider;
19
- this.model = config.model;
20
- this.temperature = config.temperature ?? 0.3;
21
- this.maxTokens = config.maxTokens ?? 8192;
22
- this.timeout = config.timeout ?? 12e4;
23
- this.retryMaxAttempts = config.retryMaxAttempts ?? 3;
24
- this.enableStreaming = config.enableStreaming ?? true;
25
- this.initClient();
26
- }
27
- provider;
28
- model;
29
- temperature;
30
- maxTokens;
31
- timeout;
32
- retryMaxAttempts;
33
- enableStreaming;
34
- /**
35
- * Process-wide hook fired on every LLM response. The CLI installs this in
36
- * main.ts to feed the cost tracker; lives on the base class so every code
37
- * path (REPL, run, arena, sub-agents) reports through one funnel without
38
- * each call site needing to remember.
39
- */
40
- static onUsage;
41
- usage = {
42
- records: [],
43
- totalPromptTokens: 0,
44
- totalCompletionTokens: 0,
45
- totalTokens: 0,
46
- requestCount: 0
47
- };
48
- recordUsage(usage, options) {
49
- if (options?.recordUsage === false) return;
50
- this.usage.records.push(usage);
51
- this.usage.totalPromptTokens += usage.promptTokens;
52
- this.usage.totalCompletionTokens += usage.completionTokens;
53
- this.usage.totalTokens += usage.totalTokens;
54
- this.usage.requestCount++;
55
- _LLMClientBase.onUsage?.(this.model, usage);
56
- }
57
- getUsage() {
58
- return { ...this.usage };
59
- }
60
- async withRetry(fn, maxAttempts) {
61
- const attempts = maxAttempts ?? this.retryMaxAttempts;
62
- let lastError;
63
- for (let attempt = 1; attempt <= attempts; attempt++) {
64
- try {
65
- return await fn();
66
- } catch (err) {
67
- lastError = err;
68
- if (err instanceof ContextLimitError) throw err;
69
- if (err instanceof LLMRateLimitError) {
70
- const waitMs = (err.retryAfter ?? attempt * 2) * 1e3;
71
- logger.warn("llm.retry", {
72
- cat: "llm",
73
- provider: this.provider,
74
- model: this.model,
75
- attempt,
76
- of: attempts,
77
- reason: "rate_limit",
78
- waitMs
79
- });
80
- await new Promise((r) => setTimeout(r, waitMs));
81
- continue;
82
- }
83
- if (attempt === attempts) {
84
- logger.error("llm.exhausted", {
85
- cat: "llm",
86
- provider: this.provider,
87
- model: this.model,
88
- attempts,
89
- error: err.message
90
- });
91
- break;
92
- }
93
- const backoff = Math.min(1e3 * Math.pow(2, attempt - 1), 3e4);
94
- logger.warn("llm.retry", {
95
- cat: "llm",
96
- provider: this.provider,
97
- model: this.model,
98
- attempt,
99
- of: attempts,
100
- reason: "error",
101
- error: err.message,
102
- backoffMs: backoff
103
- });
104
- await new Promise((r) => setTimeout(r, backoff));
105
- }
106
- }
107
- throw lastError ?? new LLMError("Unknown LLM error");
108
- }
109
- };
110
-
111
- export {
112
- LLMClientBase
113
- };