@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
- import {
2
- __esm,
3
- __export,
4
- init_esm_shims
5
- } from "./chunk-MD32R22I.js";
6
-
7
- // src/context/token-counter.ts
8
- function estimateStringTokens(text) {
9
- if (!text) return 0;
10
- const cjkChars = (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 = __esm({
52
- "src/context/token-counter.ts"() {
53
- "use strict";
54
- init_esm_shims();
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
- __export(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 = options.keepRecentN ?? 5;
195
- const compactable = 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(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
- options.onClear?.({
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 = 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 = __esm({
405
- "src/context/compaction.ts"() {
406
- init_esm_shims();
407
- init_token_counter();
408
- 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
- export {
423
- estimateTokens,
424
- adjustIndexToPreserveAPIInvariants,
425
- snipCompact,
426
- windowCompact,
427
- COMPACTABLE_TOOL_NAMES,
428
- microcompact,
429
- applyToolResultBudget,
430
- truncateToolResult,
431
- buildSummarizationPrompt,
432
- applySummaryCompaction,
433
- groupMessagesByApiRound,
434
- dropOldestRounds,
435
- extractReferencedFilePaths,
436
- compaction_exports,
437
- init_compaction
438
- };
@@ -1,107 +0,0 @@
1
- import {
2
- CompositeEvaluator,
3
- FileRunStore,
4
- NoopEvaluator,
5
- RunManager,
6
- registerPreset
7
- } from "./chunk-PKGRTCCY.js";
8
- import {
9
- init_esm_shims
10
- } from "./chunk-MD32R22I.js";
11
-
12
- // src/product/index.ts
13
- init_esm_shims();
14
-
15
- // src/product/define.ts
16
- init_esm_shims();
17
- import { join } from "path";
18
- import { homedir } from "os";
19
- function defineProduct(definition, runtime) {
20
- const { preset: presetDef, adapter, contract } = definition;
21
- const presetName = presetDef.name;
22
- const baseTools = [
23
- "Read",
24
- "Write",
25
- "Edit",
26
- "Glob",
27
- "Grep",
28
- "Bash",
29
- "AskUserQuestion",
30
- "Agent",
31
- "ToolSearch",
32
- "TaskCreate",
33
- "TaskList",
34
- "TaskUpdate",
35
- "TaskGet"
36
- ];
37
- const enabledSet = /* @__PURE__ */ new Set([...baseTools, ...adapter?.enableTools ?? []]);
38
- for (const t of adapter?.disableTools ?? []) {
39
- enabledSet.delete(t);
40
- }
41
- const permissionRules = [
42
- // Default safe rules
43
- { tool: "Read", decision: "allow" },
44
- { tool: "Glob", decision: "allow" },
45
- { tool: "Grep", decision: "allow" },
46
- { tool: "AskUserQuestion", decision: "allow" },
47
- { tool: "ToolSearch", decision: "allow" },
48
- { tool: "TaskCreate", decision: "allow" },
49
- { tool: "TaskList", decision: "allow" },
50
- { tool: "TaskUpdate", decision: "allow" },
51
- { tool: "TaskGet", decision: "allow" },
52
- // Product-specific rules (higher priority)
53
- ...adapter?.permissionRules ?? []
54
- ];
55
- const agentPreset = {
56
- name: presetName,
57
- label: presetDef.label,
58
- description: presetDef.description,
59
- promptSections: presetDef.sections ?? ["base", "orchestration"],
60
- injectGitStatus: presetDef.injectGitStatus ?? false,
61
- builtinTools: [...enabledSet],
62
- defaultPermissionRules: permissionRules
63
- };
64
- registerPreset(agentPreset);
65
- let evaluator;
66
- if (!contract?.evaluator) {
67
- evaluator = new NoopEvaluator();
68
- } else if (Array.isArray(contract.evaluator)) {
69
- evaluator = new CompositeEvaluator(contract.evaluator);
70
- } else {
71
- evaluator = contract.evaluator;
72
- }
73
- const customTools = adapter?.tools ?? [];
74
- const customToolEntries = customTools.map((ct) => ({
75
- definition: ct.definition,
76
- execute: ct.execute
77
- }));
78
- const runsDir = runtime.runsDir ?? join(homedir(), ".code-shell", "runs");
79
- const store = new FileRunStore(runsDir);
80
- const manager = new RunManager({
81
- store,
82
- executor: {
83
- llm: runtime.llm,
84
- maxTurns: contract?.maxTurns ?? 30,
85
- maxContextTokens: contract?.maxContextTokens ?? 2e5,
86
- permissionMode: runtime.permissionMode ?? "acceptEdits",
87
- sessionStorageDir: runtime.sessionStorageDir,
88
- mcpServers: adapter?.mcpServers,
89
- enabledBuiltinTools: [...enabledSet],
90
- disabledBuiltinTools: adapter?.disableTools,
91
- customSystemPrompt: presetDef.customPrompt,
92
- appendSystemPrompt: presetDef.appendPrompt,
93
- hooks: adapter?.hooks,
94
- customTools: customToolEntries.length > 0 ? customToolEntries : void 0
95
- },
96
- concurrency: contract?.concurrency ?? 1,
97
- runsDir,
98
- evaluator,
99
- defaultTags: contract?.defaultTags,
100
- defaultMetadata: contract?.defaultMetadata
101
- });
102
- return { manager, preset: agentPreset, customTools };
103
- }
104
-
105
- export {
106
- defineProduct
107
- };
@@ -1,146 +0,0 @@
1
- import {
2
- readCache
3
- } from "./chunk-3OA5G4TM.js";
4
- import {
5
- init_esm_shims
6
- } from "./chunk-MD32R22I.js";
7
-
8
- // src/llm/model-pool.ts
9
- init_esm_shims();
10
- var BUILTIN_CONTEXT_WINDOWS = [
11
- // DeepSeek V4 family — 1M context (api-docs.deepseek.com)
12
- [/^deepseek-v4(?:-|$)/i, 1e6],
13
- [/(?:^|\/)deepseek-v4(?:-|$)/i, 1e6]
14
- ];
15
- function lookupBuiltinContextWindow(model) {
16
- for (const [re, tokens] of BUILTIN_CONTEXT_WINDOWS) {
17
- if (re.test(model)) return tokens;
18
- }
19
- return void 0;
20
- }
21
- var ModelPool = class {
22
- models = /* @__PURE__ */ new Map();
23
- activeKey;
24
- providerCatalog;
25
- cacheDir;
26
- setProviderCatalog(cat) {
27
- this.providerCatalog = cat;
28
- }
29
- setCacheDir(dir) {
30
- this.cacheDir = dir;
31
- }
32
- /**
33
- * For each entry in the pool that lacks an explicit maxContextTokens
34
- * but has a providerKey, look up the contextLength from the cached
35
- * model list and patch it in.
36
- */
37
- reloadCachedContextWindows() {
38
- if (!this.cacheDir) return;
39
- for (const [key, entry] of this.models) {
40
- if (entry.maxContextTokens != null) continue;
41
- if (!entry.providerKey) continue;
42
- const file = readCache(this.cacheDir, entry.providerKey);
43
- if (!file) continue;
44
- const match = file.models.find((m) => m.id === entry.model);
45
- if (match?.contextLength) {
46
- this.models.set(key, { ...entry, maxContextTokens: match.contextLength });
47
- }
48
- }
49
- }
50
- /**
51
- * Build a pool from an array of model entries.
52
- * The first entry (or the one matching `defaultKey`) becomes active.
53
- */
54
- constructor(entries, defaultKey) {
55
- if (entries) {
56
- for (const e of entries) {
57
- this.models.set(e.key, this.withBuiltinDefaults(e));
58
- }
59
- }
60
- if (defaultKey && this.models.has(defaultKey)) {
61
- this.activeKey = defaultKey;
62
- } else if (entries?.length) {
63
- this.activeKey = entries[0].key;
64
- }
65
- }
66
- /** Register a model at runtime. */
67
- register(entry) {
68
- this.models.set(entry.key, this.withBuiltinDefaults(entry));
69
- if (!this.activeKey) {
70
- this.activeKey = entry.key;
71
- }
72
- }
73
- /** Fill in known defaults (e.g. context window for DeepSeek V4) when the entry doesn't specify them. */
74
- withBuiltinDefaults(entry) {
75
- if (entry.maxContextTokens != null) return entry;
76
- const builtin = lookupBuiltinContextWindow(entry.model);
77
- if (builtin == null) return entry;
78
- return { ...entry, maxContextTokens: builtin };
79
- }
80
- /** Switch the active model. Throws if key not found. */
81
- switch(key) {
82
- const entry = this.models.get(key);
83
- if (!entry) {
84
- const available = [...this.models.keys()].join(", ");
85
- throw new Error(`Model "${key}" not found. Available: ${available}`);
86
- }
87
- this.activeKey = key;
88
- return entry;
89
- }
90
- /** Get a model by key. No key = active model. Returns undefined if not found. */
91
- get(key) {
92
- if (key) return this.models.get(key);
93
- if (this.activeKey) return this.models.get(this.activeKey);
94
- return void 0;
95
- }
96
- /** Get the active model key. */
97
- getActiveKey() {
98
- return this.activeKey;
99
- }
100
- /** List all registered models. */
101
- list() {
102
- return [...this.models.values()];
103
- }
104
- /** Number of registered models. */
105
- get size() {
106
- return this.models.size;
107
- }
108
- /** Check if a key exists. */
109
- has(key) {
110
- return this.models.has(key);
111
- }
112
- /**
113
- * Build an LLMConfig for a given model entry, merging with a base config
114
- * (inherits apiKey, baseUrl, etc. from the base if not set on the entry).
115
- */
116
- toLLMConfig(entry, base) {
117
- const fromCat = entry.providerKey && this.providerCatalog ? this.providerCatalog.get(entry.providerKey) : void 0;
118
- const kindToClientProvider = (kind) => {
119
- if (!kind) return "openai";
120
- if (kind === "anthropic") return "anthropic";
121
- return "openai";
122
- };
123
- return {
124
- provider: entry.provider || kindToClientProvider(fromCat?.kind) || "openai",
125
- model: entry.model,
126
- apiKey: entry.apiKey ?? fromCat?.apiKey ?? base?.apiKey,
127
- baseUrl: entry.baseUrl ?? fromCat?.baseUrl ?? base?.baseUrl,
128
- temperature: base?.temperature ?? 0.3,
129
- maxTokens: entry.maxOutputTokens ?? base?.maxTokens ?? 8192,
130
- enableStreaming: base?.enableStreaming ?? true
131
- };
132
- }
133
- /**
134
- * Build an LLMConfig for the active model (or a specific key),
135
- * merging with a base config.
136
- */
137
- resolveLLMConfig(key, base) {
138
- const entry = this.get(key);
139
- if (!entry) return void 0;
140
- return this.toLLMConfig(entry, base);
141
- }
142
- };
143
-
144
- export {
145
- ModelPool
146
- };