@cjhyy/code-shell 0.1.6 → 0.1.7

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 (154) hide show
  1. package/dist/anthropic-UBSB5AQH.js +1 -0
  2. package/dist/arena/index.js +1 -104
  3. package/dist/arena-OW55ZCHT.js +3 -0
  4. package/dist/bwrap-PVZMLHZR.js +2 -0
  5. package/dist/chunk-2NS3JMNK.js +1 -0
  6. package/dist/chunk-3QP5BQ3L.js +1 -0
  7. package/dist/chunk-B7K2OWKC.js +2 -0
  8. package/dist/chunk-EWWK56K6.js +2 -0
  9. package/dist/chunk-FU7AHZNN.js +1 -0
  10. package/dist/chunk-HIJ2XXGX.js +1 -0
  11. package/dist/chunk-KCXSARAA.js +1 -0
  12. package/dist/chunk-NFH3UQ3E.js +2 -0
  13. package/dist/chunk-NMBYBGC7.js +250 -0
  14. package/dist/chunk-NVAZJ5XS.js +2 -0
  15. package/dist/chunk-O5HFCH2U.js +1 -0
  16. package/dist/chunk-P6JSTIFM.js +1 -0
  17. package/dist/chunk-PGANL6F2.js +3 -0
  18. package/dist/chunk-Q4O2HGWS.js +251 -0
  19. package/dist/chunk-QTWU7UNA.js +5 -0
  20. package/dist/chunk-RP26WO4R.js +1 -0
  21. package/dist/chunk-SNFAPSLA.js +1 -0
  22. package/dist/chunk-T222K6IV.js +18 -0
  23. package/dist/chunk-TKJA6W36.js +3 -0
  24. package/dist/chunk-UDPUTFQT.js +2 -0
  25. package/dist/chunk-W47Z7MGS.js +33 -0
  26. package/dist/chunk-WI6FSWGU.js +1 -0
  27. package/dist/chunk-WOP6MJKW.js +1 -0
  28. package/dist/chunk-XDOWC7EG.js +4 -0
  29. package/dist/chunk-Y2NS6HPO.js +641 -0
  30. package/dist/cli/main.js +303 -22060
  31. package/dist/client-base-6ZZJJYDY.js +1 -0
  32. package/dist/compaction-ECVQVOCT.js +1 -0
  33. package/dist/devtools-SGDUOOM4.js +1 -0
  34. package/dist/engine/engine.d.ts +8 -0
  35. package/dist/export-md-U72T7NW7.js +22 -0
  36. package/dist/file-history-7FQFEQOL.js +1 -0
  37. package/dist/index.d.ts +1 -1
  38. package/dist/index.js +1 -347
  39. package/dist/llm/token-counter.d.ts +17 -0
  40. package/dist/manager-C3TDN6MS.js +1 -0
  41. package/dist/mcp-manager-OP4XYV53.js +1 -0
  42. package/dist/memory-BNI4WEWL.js +1 -0
  43. package/dist/model-cache-HEDXI7UJ.js +1 -0
  44. package/dist/model-fetcher-BJ64META.js +1 -0
  45. package/dist/off-7SDVMMXW.js +1 -0
  46. package/dist/openai-KEWQ54TM.js +1 -0
  47. package/dist/openrouter-models-AM6M52D6.js +1 -0
  48. package/dist/openrouter-sync-5JNBL3Z6.js +1 -0
  49. package/dist/product/index.js +1 -21
  50. package/dist/run/index.js +1 -48
  51. package/dist/seatbelt-WBYROQT6.js +37 -0
  52. package/dist/session/session-manager.d.ts +2 -0
  53. package/dist/session-manager-AGWS5SMJ.js +1 -0
  54. package/dist/settings/schema.d.ts +72 -6
  55. package/dist/tool-summary-5UE62VU4.js +2 -0
  56. package/dist/tool-system/builtin/bash.d.ts +7 -1
  57. package/dist/tool-system/context.d.ts +7 -0
  58. package/dist/tool-system/sandbox/bwrap.d.ts +13 -0
  59. package/dist/tool-system/sandbox/index.d.ts +71 -0
  60. package/dist/tool-system/sandbox/off.d.ts +2 -0
  61. package/dist/tool-system/sandbox/seatbelt.d.ts +18 -0
  62. package/dist/types.d.ts +4 -0
  63. package/dist/ui/components/SessionPicker.d.ts +2 -0
  64. package/dist/ui/components/SpinnerWithVerb.d.ts +2 -2
  65. package/dist/ui/components/StatusLine.d.ts +2 -2
  66. package/dist/updater-OCNU2K2Z.js +1 -0
  67. package/package.json +7 -10
  68. package/dist/anthropic-IBTI4WL2.cjs +0 -10
  69. package/dist/anthropic-PRZZKHEZ.js +0 -10
  70. package/dist/arena/index.cjs +0 -104
  71. package/dist/arena-2LTLIXOL.js +0 -261
  72. package/dist/arena-ADB7DRFI.cjs +0 -261
  73. package/dist/chunk-2YW4FPFG.cjs +0 -101
  74. package/dist/chunk-3OA5G4TM.js +0 -47
  75. package/dist/chunk-3QO25N6E.js +0 -4711
  76. package/dist/chunk-3SBSUOWZ.js +0 -447
  77. package/dist/chunk-52LGZKT3.cjs +0 -47
  78. package/dist/chunk-55XGPMAP.cjs +0 -146
  79. package/dist/chunk-6QVAYW7C.cjs +0 -438
  80. package/dist/chunk-6S4BJ65N.js +0 -113
  81. package/dist/chunk-76HYEPDM.js +0 -307
  82. package/dist/chunk-7BI3V74Y.cjs +0 -447
  83. package/dist/chunk-7EG3V4JY.cjs +0 -113
  84. package/dist/chunk-7JVTYEEC.js +0 -340
  85. package/dist/chunk-7QIM3BKD.js +0 -44
  86. package/dist/chunk-7Y6S3OCX.js +0 -438
  87. package/dist/chunk-ABRRONJ7.js +0 -107
  88. package/dist/chunk-BSW22MPA.js +0 -146
  89. package/dist/chunk-BXCY2FSE.js +0 -203
  90. package/dist/chunk-BZ5TNE7L.js +0 -5128
  91. package/dist/chunk-DDB6QOKJ.cjs +0 -1252
  92. package/dist/chunk-HEKQCI7B.cjs +0 -224
  93. package/dist/chunk-IK4EWJBP.cjs +0 -203
  94. package/dist/chunk-ILHE7XLT.cjs +0 -107
  95. package/dist/chunk-JMR33QVF.cjs +0 -169
  96. package/dist/chunk-KAQHULYN.js +0 -54
  97. package/dist/chunk-KE4EQOWA.js +0 -294
  98. package/dist/chunk-KOVYSDHZ.cjs +0 -340
  99. package/dist/chunk-KS3RYAYL.cjs +0 -45
  100. package/dist/chunk-MD32R22I.js +0 -50
  101. package/dist/chunk-MV7YI4WO.cjs +0 -293
  102. package/dist/chunk-MY5XHADU.cjs +0 -216
  103. package/dist/chunk-NUNC3VFB.cjs +0 -307
  104. package/dist/chunk-PKGRTCCY.js +0 -9092
  105. package/dist/chunk-QARL3IDQ.js +0 -1252
  106. package/dist/chunk-S754JHLR.cjs +0 -54
  107. package/dist/chunk-SFXHZSRF.js +0 -101
  108. package/dist/chunk-SIHHIQLO.js +0 -224
  109. package/dist/chunk-T6VYG46N.js +0 -105
  110. package/dist/chunk-TNLGBJYS.cjs +0 -44
  111. package/dist/chunk-TUY2T5KP.cjs +0 -105
  112. package/dist/chunk-UXOCVJJ6.cjs +0 -9092
  113. package/dist/chunk-VIAGTYYW.js +0 -169
  114. package/dist/chunk-WASS5YWB.js +0 -215
  115. package/dist/chunk-WZJV6DJC.cjs +0 -5128
  116. package/dist/chunk-YIQBXAYU.cjs +0 -264
  117. package/dist/chunk-YKIAELDZ.cjs +0 -4711
  118. package/dist/chunk-ZBPSQCPU.js +0 -264
  119. package/dist/cli/main.cjs +0 -22156
  120. package/dist/client-base-HTF236ZD.cjs +0 -9
  121. package/dist/client-base-QKRKCOWB.js +0 -9
  122. package/dist/compaction-6VU2T643.js +0 -33
  123. package/dist/compaction-OKUNTCA7.cjs +0 -33
  124. package/dist/devtools-T2NIZBJK.cjs +0 -6
  125. package/dist/devtools-YXWHOVKR.js +0 -6
  126. package/dist/export-md-RXDW6F5W.cjs +0 -135
  127. package/dist/export-md-XXKZANW5.js +0 -135
  128. package/dist/file-history-KYPE3ECT.cjs +0 -7
  129. package/dist/file-history-LF4F7X26.js +0 -7
  130. package/dist/index.cjs +0 -347
  131. package/dist/manager-D65VFAPX.js +0 -7
  132. package/dist/manager-TTF5VHJC.cjs +0 -7
  133. package/dist/mcp-manager-QMKWPBZ4.js +0 -8
  134. package/dist/mcp-manager-Z3OKI74O.cjs +0 -8
  135. package/dist/memory-5LWZ6FI2.cjs +0 -9
  136. package/dist/memory-VIJLBAMQ.js +0 -9
  137. package/dist/model-cache-5KIYL5SL.js +0 -13
  138. package/dist/model-cache-OED3IM4R.cjs +0 -13
  139. package/dist/model-fetcher-HKGICACL.js +0 -8
  140. package/dist/model-fetcher-UR6WJOQP.cjs +0 -8
  141. package/dist/openai-JR2WEKOF.js +0 -10
  142. package/dist/openai-YBTOET4O.cjs +0 -10
  143. package/dist/openrouter-models-H56GHBHN.js +0 -15
  144. package/dist/openrouter-models-TWUFWZ5T.cjs +0 -15
  145. package/dist/openrouter-sync-5VMGN6C2.cjs +0 -11
  146. package/dist/openrouter-sync-ALEMF5IU.js +0 -11
  147. package/dist/product/index.cjs +0 -21
  148. package/dist/run/index.cjs +0 -48
  149. package/dist/session-manager-Q22BBMD3.js +0 -8
  150. package/dist/session-manager-XODQVL3C.cjs +0 -8
  151. package/dist/tool-summary-63DPIS7G.cjs +0 -31
  152. package/dist/tool-summary-NP5CDBKG.js +0 -31
  153. package/dist/updater-I7QBW4DP.cjs +0 -17
  154. package/dist/updater-NVME5S3Z.js +0 -17
@@ -0,0 +1,2 @@
1
+ import {h,a}from'./chunk-3QP5BQ3L.js';import {existsSync,readFileSync,copyFileSync,writeFileSync,mkdirSync,renameSync}from'fs';import {join,dirname}from'path';import {homedir}from'os';import {z}from'zod';h();h();var C=z.object({agent:z.object({preset:z.string().default("terminal-coding"),enabledBuiltinTools:z.array(z.string()).default([]),disabledBuiltinTools:z.array(z.string()).default([]),customSystemPrompt:z.string().optional(),appendSystemPrompt:z.string().optional()}).default({}),activeKey:z.string().optional(),autoUpdates:z.boolean().default(true),model:z.object({provider:z.string().default("openai"),name:z.string().default("anthropic/claude-opus-4-6"),apiKey:z.string().optional(),baseUrl:z.string().default("https://openrouter.ai/api/v1"),temperature:z.number().min(0).max(2).default(.3),maxTokens:z.number().default(8192)}).default({}),providers:z.array(z.object({key:z.string(),label:z.string().optional(),kind:z.enum(["openai","anthropic","deepseek","xai","mistral","groq","google","openrouter","ollama","custom"]),baseUrl:z.string(),apiKey:z.string().optional(),protocol:z.enum(["openai-compat","anthropic-style"]).optional(),modelsPath:z.string().optional()})).default([]),models:z.array(z.object({key:z.string(),label:z.string().optional(),providerKey:z.string().optional(),model:z.string(),maxOutputTokens:z.number().optional(),maxContextTokens:z.number().optional(),protocol:z.string().optional(),provider:z.string().optional(),baseUrl:z.string().optional(),apiKey:z.string().optional()}).transform(r=>{let o=r.protocol??r.provider;return {...r,protocol:o,provider:o}})).default([]),permissions:z.object({defaultMode:z.enum(["default","acceptEdits","dontAsk","bypassPermissions","auto","plan"]).default("default"),rules:z.array(z.object({tool:z.string(),argsPattern:z.record(z.string()).optional(),decision:z.enum(["allow","deny","ask"]),reason:z.string().optional()})).default([])}).default({}),context:z.object({maxTokens:z.number().default(2e5),compactAtRatio:z.number().default(.6),summarizeAtRatio:z.number().default(.8)}).default({}),session:z.object({storageDir:z.string().optional(),maxHistory:z.number().default(100)}).default({}),mcpServers:z.record(z.object({name:z.string(),command:z.string().optional(),args:z.array(z.string()).optional(),env:z.record(z.string()).optional(),url:z.string().optional(),transport:z.enum(["stdio","sse","streamable-http","inprocess"]).optional(),headers:z.record(z.string()).optional()})).default({}),instructions:z.object({fileName:z.string().default("CODESHELL.md"),scanDirs:z.array(z.string()).default([]),compatFileNames:z.array(z.string()).default(["CLAUDE.md","AGENTS.md"]),ignoreGitBoundary:z.boolean().default(false)}).default({}),arena:z.object({participants:z.array(z.union([z.string(),z.object({name:z.string(),model:z.string(),provider:z.string().optional(),apiKey:z.string().optional(),baseUrl:z.string().optional()})])).default([])}).default({}),search:z.object({provider:z.enum(["serper","tavily","searxng"]).default("serper"),apiKey:z.string().optional(),baseUrl:z.string().optional()}).default({}),output:z.object({format:z.enum(["text","json","jsonl","stream-json"]).default("text")}).default({}),sandbox:z.object({mode:z.enum(["off","auto","seatbelt","bwrap"]).optional(),writableRoots:z.array(z.string()).optional(),deniedReads:z.array(z.string()).optional(),network:z.enum(["allow","deny"]).optional()}).optional()}).passthrough();function x(r){return C.parse(r)}a(x,"validateSettings");h();var N=[[/deepseek\.com/i,"deepseek"],[/anthropic\.com/i,"anthropic"],[/openai\.com/i,"openai"],[/x\.ai/i,"xai"],[/mistral\.ai/i,"mistral"],[/groq\.com/i,"groq"],[/generativelanguage\.googleapis/i,"google"],[/openrouter\.ai/i,"openrouter"],[/localhost:11434|127\.0\.0\.1:11434/i,"ollama"]];function S(r){if(!r)return "custom";for(let[o,n]of N)if(o.test(r))return n;return "custom"}a(S,"inferKind");function M(r){return `${r.provider??""}|${r.baseUrl??""}|${r.apiKey??""}`}a(M,"makeFingerprint");function L(r,o){if(!o.has(r))return r;for(let n=2;;n++){let s=`${r}-${n}`;if(!o.has(s))return s}}a(L,"deriveKey");function T(r,o,n){let s=o.lastIndexOf("/"),i=s>=0?o.slice(s+1):o,a=r.toLowerCase(),l=i.toLowerCase().startsWith(`${a}-`)?i:`${a}-${i}`;if(!n.has(l))return l;for(let d=2;;d++){let p=`${l}-${d}`;if(!n.has(p))return p}}a(T,"deriveProviderModelKey");function R(r){if(r.models.length===0)return {providers:r.providers,models:[],changed:false};let o=r.providers.length>0,n=new Map;for(let t of r.models)n.set(t.key,(n.get(t.key)??0)+1);if(!r.models.some(t=>!t.providerKey||(n.get(t.key)??0)>1))return {providers:r.providers,models:r.models.map(t=>({key:t.key,label:t.label,providerKey:t.providerKey??"",model:t.model,maxOutputTokens:t.maxOutputTokens,maxContextTokens:t.maxContextTokens,provider:t.provider,baseUrl:t.baseUrl,apiKey:t.apiKey})),changed:false};let i=new Map,a=[],l=new Set(r.providers.map(t=>t.key));for(let t of r.providers){let g=`|${t.baseUrl}|${t.apiKey??""}`;i.set(g,t.key);}for(let t of r.models){let g=M(t),h=r.providers.find(O=>O.baseUrl===(t.baseUrl??""));if(h){i.set(g,h.key);continue}if(i.has(g))continue;let m=S(t.baseUrl),f=L(m,l);l.add(f),i.set(g,f),a.push({key:f,kind:m,baseUrl:t.baseUrl??"",apiKey:t.apiKey});}let d=new Set,p=r.models.map(t=>{let g=i.get(M(t)),h=(n.get(t.key)??0)>1,m=t.key;if(h){let f=S(t.baseUrl);m=T(f,t.model,d);}if(d.has(m)){let f=S(t.baseUrl);m=T(f,t.model,d);}return d.add(m),{key:m,label:t.label,providerKey:g,provider:t.provider,model:t.model,baseUrl:t.baseUrl,apiKey:t.apiKey,maxOutputTokens:t.maxOutputTokens,maxContextTokens:t.maxContextTokens}}),c=new Set,b=p.filter(t=>{let g=`${t.key}|${t.model}`;return c.has(g)?false:(c.add(g),true)});return {providers:o?[...r.providers,...a]:a,models:b,changed:true}}a(R,"migrateModels");function k(){return process.env.HOME??homedir()}a(k,"userHome");var P=class{constructor(o=process.cwd()){this.cwd=o;}static{a(this,"SettingsManager");}sources=[];merged=null;load(o){this.sources=[],this.loadJsonFile(join(k(),".code-shell","settings.managed.json"),"managed",0),this.loadJsonFile(join(k(),".code-shell","settings.json"),"user",1),this.loadJsonFile(join(this.cwd,".code-shell","settings.json"),"project",2),this.loadJsonFile(join(this.cwd,".code-shell","settings.local.json"),"local",3),o&&Object.keys(o).length>0&&this.sources.push({name:"flag",priority:4,data:o}),this.sources.sort((i,a)=>i.priority-a.priority);let n=this.deepMerge(),s=join(k(),".code-shell","settings.json");if(existsSync(s))try{let i=JSON.parse(readFileSync(s,"utf-8")),a=R({providers:i.providers??[],models:i.models??[]});if(a.changed){copyFileSync(s,`${s}.bak`);let l={...i,providers:a.providers,models:a.models};writeFileSync(s,JSON.stringify(l,null,2),"utf-8");let d=this.sources.find(c=>c.name==="user");d&&(d.data=l);let p=this.deepMerge();return this.merged=x(p),this.merged}}catch{}return this.merged=x(n),this.merged}get(){return this.merged?this.merged:this.load()}invalidate(){this.merged=null;}saveUserSetting(o,n){let s=join(k(),".code-shell","settings.json"),i={};if(existsSync(s))try{let p=readFileSync(s,"utf-8"),c=JSON.parse(p);c&&typeof c=="object"&&!Array.isArray(c)&&(i=c);}catch{}let a=o.split("."),l=i;for(let p=0;p<a.length-1;p++){let c=a[p],b=l[c];(!b||typeof b!="object"||Array.isArray(b))&&(l[c]={}),l=l[c];}l[a[a.length-1]]=n,mkdirSync(dirname(s),{recursive:true});let d=`${s}.${process.pid}.${Date.now()}.tmp`;writeFileSync(d,JSON.stringify(i,null,2),"utf-8"),renameSync(d,s),this.invalidate();}loadJsonFile(o,n,s){if(existsSync(o))try{let i=readFileSync(o,"utf-8"),a=JSON.parse(i);typeof a=="object"&&a!==null&&this.sources.push({name:n,priority:s,data:a});}catch{}}deepMerge(){let o={};for(let n of this.sources)o=A(o,n.data);return o}};function A(r,o){let n={...r};for(let[s,i]of Object.entries(o))i===null?delete n[s]:typeof i=="object"&&!Array.isArray(i)&&typeof n[s]=="object"&&!Array.isArray(n[s])&&n[s]!==null?n[s]=A(n[s],i):n[s]=i;return n}a(A,"merge");
2
+ export{C as a,x as b,P as c};
@@ -0,0 +1,33 @@
1
+ import {c,h,a,d}from'./chunk-3QP5BQ3L.js';function M(e){if(!e)return 0;let n=(e.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g)??[]).length;if(n/e.length>.3){let s=n/y.cjk,p=(e.length-n)/y.english;return Math.ceil(s+p)}return ["{","}","(",")",";","=>","import ","function ","class ","const "].reduce((s,i)=>s+(e.includes(i)?1:0),0)>=3?Math.ceil(e.length/y.code):e.startsWith("{")||e.startsWith("[")?Math.ceil(e.length/y.json):Math.ceil(e.length/y.english)}function T(e){let n=0;for(let t of e)if(n+=4,typeof t.content=="string")n+=M(t.content);else if(Array.isArray(t.content))for(let o of t.content)n+=O(o);return n}function O(e){let n=2;return e.text&&(n+=M(e.text)),e.content&&typeof e.content=="string"&&(n+=M(e.content)),e.input&&(n+=M(JSON.stringify(e.input))),e.name&&(n+=M(e.name)),n}var y,A=c(()=>{h();y={english:4,code:3.2,json:3.5,mixed:3.6,cjk:1.5};a(M,"estimateStringTokens");a(T,"estimateMessagesTokens");a(O,"estimateBlockTokens");});var q={};d(q,{COMPACTABLE_TOOL_NAMES:()=>x,adjustIndexToPreserveAPIInvariants:()=>b,applySummaryCompaction:()=>G,applyToolResultBudget:()=>N,buildSummarizationPrompt:()=>F,dropOldestRounds:()=>L,estimateTokens:()=>P,extractReferencedFilePaths:()=>k,groupMessagesByApiRound:()=>R,microcompact:()=>B,snipCompact:()=>z,truncateToolResult:()=>U,windowCompact:()=>I});function P(e){return Math.ceil(T(e)*(4/3))}function b(e,n){let t=n,o=new Set;for(let r=t;r<e.length;r++){let s=e[r];if(Array.isArray(s.content))for(let i of s.content)i.type==="tool_result"&&i.tool_use_id&&o.add(i.tool_use_id);}for(let r=t;r<e.length;r++){let s=e[r];if(Array.isArray(s.content))for(let i of s.content)i.type==="tool_use"&&i.id&&o.delete(i.id);}if(o.size===0)return t;for(let r=t-1;r>=0&&o.size>0;r--){let s=e[r];if(!(s.role!=="assistant"||!Array.isArray(s.content)))for(let i of s.content)i.type==="tool_use"&&i.id&&o.has(i.id)&&(o.delete(i.id),r<t&&(t=r));}return t}function z(e,n=3,t=8){if(e.length<=n+t+1)return e;let o=e.length-t;if(o=b(e,o),o<=n)return e;let s={role:"user",content:`<system-reminder>[${o-n} messages snipped to save context. Use the transcript file to review details if needed.]</system-reminder>`};return [...e.slice(0,n),s,...e.slice(o)]}function I(e,n){if(e.length<=n+1)return e;let t=e.length-n;return t=b(e,t),t<=1?e:[e[0],...e.slice(t)]}function E(e){let n=new Map;for(let t of e)if(Array.isArray(t.content))for(let o of t.content)o.type==="tool_use"&&o.id&&o.name&&n.set(o.id,o.name);return n}function W(e,n){if(!n||typeof n!="object")return "";let t=a(o=>{let r=[];for(let s of o){let i=n[s];typeof i=="string"&&i.length>0&&r.push(`${s}=${i.length>80?i.slice(0,77)+"...":i}`);}return r.join(" ")},"pick");switch(e){case "Read":case "Write":case "Edit":case "NotebookEdit":return t(["file_path","path","notebook_path"]);case "Glob":case "Grep":return t(["pattern","path","glob"]);case "Bash":case "PowerShell":case "REPL":return t(["command"]);case "WebFetch":case "WebSearch":return t(["url","query"]);default:{let o=JSON.stringify(n);return o.length>100?o.slice(0,97)+"...":o}}}function B(e,n={}){let t=n.keepRecentN??5,o=n.compactableTools??x,r=E(e),s=new Map;for(let l of e)if(Array.isArray(l.content))for(let g of l.content)g.type==="tool_use"&&g.id&&s.set(g.id,g.input);let i=0,p=[];for(let l=e.length-1;l>=0;l--){let g=e[l];!Array.isArray(g.content)||!g.content.some(d=>d.type==="tool_result"&&d.tool_use_id!=null&&o.has(r.get(d.tool_use_id)??"")&&typeof d.content=="string"&&!d.content.startsWith("[Old tool result cleared"))||(i++,i>t&&p.push(l));}if(p.length===0)return e;let c=new Set(p),u=new Set,h=0,m=e.map((l,g)=>!c.has(g)||!Array.isArray(l.content)?l:{...l,content:l.content.map(f=>{if(f.type!=="tool_result"||!f.tool_use_id)return f;let d=r.get(f.tool_use_id);if(!d||!o.has(d)||typeof f.content!="string"||f.content.startsWith("[Old tool result cleared"))return f;let _=W(d,s.get(f.tool_use_id)),C=_?`[Old tool result cleared \u2014 ${d} ${_}]`:`[Old tool result cleared \u2014 ${d}]`;return u.add(d),h++,{...f,content:C}})});return h>0&&n.onClear?.({clearedRounds:p.length,toolNames:[...u].sort()}),m}function N(e,n=1e5){return e.map(t=>{if(!Array.isArray(t.content))return t;let o=[],r=0;for(let c=0;c<t.content.length;c++){let u=t.content[c];if(u.type==="tool_result"&&typeof u.content=="string"){let h=u.content.length;o.push({index:c,size:h}),r+=h;}}if(r<=n||o.length===0)return t;o.sort((c,u)=>u.size-c.size);let s=r,i=new Set;for(let c of o){if(s<=n)break;i.add(c.index),s-=c.size,s+=200;}if(i.size===0)return t;let p=t.content.map((c,u)=>{if(!i.has(u))return c;let h=typeof c.content=="string"?c.content.slice(0,500):"",m=(c.content.length/1e3).toFixed(0);return {...c,content:`Output too large (${m}KB) \u2014 truncated to fit the per-message budget. Re-run the originating tool if you need the full output.
2
+
3
+ Preview (first 500 chars):
4
+ ${h}`}});return {...t,content:p}})}function U(e,n=3e4){if(e.length<=n)return e;let t=Math.floor(n*.7),o=Math.floor(n*.2),r=e.slice(0,t),s=e.slice(-o);return r+`
5
+
6
+ ... [${e.length-t-o} characters truncated] ...
7
+
8
+ `+s}function F(e){let n=[];for(let t of e)if(typeof t.content=="string")n.push(`[${t.role}]: ${t.content.slice(0,3e3)}`);else for(let o of t.content)if(o.type==="text"&&o.text)n.push(`[${t.role}]: ${o.text.slice(0,3e3)}`);else if(o.type==="tool_use"){let r=JSON.stringify(o.input).slice(0,500);n.push(`[tool_use]: ${o.name}(${r})`);}else if(o.type==="tool_result"){let r=typeof o.content=="string"?o.content:"";n.push(`[tool_result]: ${r.slice(0,1500)}`);}return `Summarize the following conversation into these sections. Be factual. Preserve file paths, function names, and error messages exactly.
9
+
10
+ 1. **Primary Request**: What the user originally asked for
11
+ 2. **Key Concepts**: Important technical terms, patterns, file paths
12
+ 3. **Files Referenced**: List of files read/edited with key content
13
+ 4. **Errors & Fixes**: Any errors encountered and how they were resolved
14
+ 5. **Actions Taken**: Tools used and their outcomes
15
+ 6. **User Messages**: All distinct user requests (verbatim if short)
16
+ 7. **Pending Tasks**: Anything started but not finished
17
+ 8. **Current State**: Where things stand right now
18
+ 9. **Next Steps**: What should happen next
19
+
20
+ Conversation:
21
+
22
+ `+n.join(`
23
+ `)}function G(e,n,t,o){if(e.length<=t+2)return e;let r=e.length-t;if(r=b(e,r),r<=1)return e;let s=e[0],i=e.slice(1,r),p=e.slice(r),c=k(i),u=`This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.
24
+
25
+ ${n}`;o&&(u+=`
26
+
27
+ If you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: ${o}`),c.length>0&&(u+=`
28
+
29
+ Files referenced before compaction (use Read tool if you need their current content):
30
+ `+c.map(m=>`- ${m}`).join(`
31
+ `)),u+=`
32
+
33
+ Recent messages are preserved verbatim below. Continue from where you left off.`;let h={role:"user",content:`<system-reminder>${u}</system-reminder>`};return [s,h,...p]}function R(e){let n=[],t=[];for(let o of e)o.role==="assistant"&&t.length>0?(n.push(t),t=[o]):t.push(o);return t.length>0&&n.push(t),n}function L(e,n){let t=R(e);if(t.length<=n+1)return t[t.length-1];let o=t.slice(n).flat(),r=b(o,0),s=o.slice(r);return s.length>0&&s[0].role==="assistant"&&s.unshift({role:"user",content:"<system-reminder>Earlier conversation context was removed to fit within the context window. Continue from the assistant's response below.</system-reminder>"}),s}function k(e){let n=new Set,t=new Set(["Read","Edit","Write","Glob","Grep"]);for(let o of e)if(Array.isArray(o.content)){for(let r of o.content)if(r.type==="tool_use"&&r.name&&t.has(r.name)&&r.input){let s=r.input,i=s.file_path??s.path;i&&n.add(i);}}return [...n]}var x,J=c(()=>{h();A();a(P,"estimateTokens");a(b,"adjustIndexToPreserveAPIInvariants");a(z,"snipCompact");a(I,"windowCompact");x=new Set(["Read","Glob","Grep","Bash","PowerShell","NotebookEdit","WebFetch","WebSearch","REPL"]);a(E,"buildToolUseIdToNameMap");a(W,"summarizeToolCallArgs");a(B,"microcompact");a(N,"applyToolResultBudget");a(U,"truncateToolResult");a(F,"buildSummarizationPrompt");a(G,"applySummaryCompaction");a(R,"groupMessagesByApiRound");a(L,"dropOldestRounds");a(k,"extractReferencedFilePaths");});export{P as a,b,z as c,I as d,x as e,B as f,N as g,U as h,F as i,G as j,R as k,L as l,k as m,q as n,J as o};
@@ -0,0 +1 @@
1
+ import {h,a}from'./chunk-3QP5BQ3L.js';import {mkdirSync,existsSync,readFileSync,copyFileSync,writeFileSync}from'fs';import {join,resolve}from'path';import {createHash}from'crypto';h();var g=class S{static{a(this,"FileHistory");}historyDir;snapshots=[];constructor(t){this.historyDir=join(t,"file-history"),mkdirSync(this.historyDir,{recursive:true});}saveSnapshot(t){let s=resolve(t);if(!existsSync(s))return null;try{let e=readFileSync(s),i=createHash("md5").update(e).digest("hex"),a=this.snapshots.find(l=>l.filePath===s&&l.hash===i);if(a)return a;let h=Date.now(),d=s.replace(/[/\\:]/g,"_").slice(-100),o=join(this.historyDir,`${h}_${d}`);copyFileSync(s,o);let c={filePath:s,timestamp:h,backupPath:o,hash:i,size:e.length};return this.snapshots.push(c),this.saveIndex(),c}catch{return null}}getSnapshots(t){let s=resolve(t);return this.snapshots.filter(e=>e.filePath===s).sort((e,i)=>i.timestamp-e.timestamp)}restore(t){try{return existsSync(t.backupPath)?(this.saveSnapshot(t.filePath),copyFileSync(t.backupPath,t.filePath),!0):!1}catch{return false}}restoreLatest(t){let s=this.getSnapshots(t);return s.length===0?false:this.restore(s[0])}getTrackedFiles(){return [...new Set(this.snapshots.map(t=>t.filePath))]}saveIndex(){try{let t=join(this.historyDir,"index.json");writeFileSync(t,JSON.stringify(this.snapshots,null,2),"utf-8");}catch{}}static loadFromDir(t){let s=new S(t),e=join(s.historyDir,"index.json");if(existsSync(e))try{s.snapshots=JSON.parse(readFileSync(e,"utf-8"));}catch{}return s}};export{g as a};
@@ -0,0 +1 @@
1
+ import {a as a$2}from'./chunk-O5HFCH2U.js';import {a}from'./chunk-HIJ2XXGX.js';import {c,d,b as b$1}from'./chunk-FU7AHZNN.js';import {b}from'./chunk-B7K2OWKC.js';import {h,a as a$1}from'./chunk-3QP5BQ3L.js';import M from'@anthropic-ai/sdk';h();var C=class extends a{static{a$1(this,"AnthropicClient");}_client=null;constructor(e){super(e);}initClient(){}get client(){return this._client||(this._client=new M({apiKey:this.config.apiKey??process.env.ANTHROPIC_API_KEY,...this.config.baseUrl?{baseURL:this.config.baseUrl}:{},timeout:this.timeout})),this._client}async createMessage(e){return this.withRetry(async()=>{let a=this.buildMessages(e.messages),n=e.tools?this.convertTools(e.tools):void 0,s=b.span("llm.request",{cat:"llm",provider:this.provider,model:this.model,stream:!!(e.stream&&e.onChunk),messageCount:a.length,toolCount:n?.length??0});try{let t=e.stream&&e.onChunk?await this.streamMessage(e,a,n):await this.nonStreamMessage(e,a,n);return s.end({stopReason:t.stopReason,promptTokens:t.usage?.promptTokens,completionTokens:t.usage?.completionTokens,cacheReadTokens:t.usage?.cacheReadTokens,cacheCreationTokens:t.usage?.cacheCreationTokens}),t}catch(t){throw s.fail(t),t}})}async nonStreamMessage(e,a,n){try{let s=await this.client.messages.create({model:this.model,max_tokens:e.maxTokens??this.maxTokens,system:[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}],messages:a,...n?.length?{tools:n}:{},...e.temperature!==void 0?{temperature:e.temperature}:{temperature:this.temperature}},{signal:e.signal}),t={promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cacheReadTokens:s.usage.cache_read_input_tokens,cacheCreationTokens:s.usage.cache_creation_input_tokens};return this.recordUsage(t,e),this.processResponse(s,t)}catch(s){throw this.handleApiError(s),s}}async streamMessage(e,a,n){try{let s=this.client.messages.stream({model:this.model,max_tokens:e.maxTokens??this.maxTokens,system:[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}],messages:a,...n?.length?{tools:n}:{},...e.temperature!==void 0?{temperature:e.temperature}:{temperature:this.temperature}},{signal:e.signal}),t="",o="",c="",l="",x=Date.now(),u=!1;s.on("text",r=>{u||(u=!0,b.debug("llm.first_byte",{cat:"llm",provider:this.provider,model:this.model,ttft_ms:Date.now()-x})),t+=r,e.onChunk?.({type:"text",text:r,tokens:a$2(r)});}),s.on("contentBlock",r=>{r.type==="tool_use"&&(o=r.name,c=r.id,l="",e.onChunk?.({type:"tool_use_start",toolCall:{id:r.id,toolName:r.name,args:{}}}));}),s.on("inputJson",(r,h)=>{l=JSON.stringify(h),c&&e.onChunk?.({type:"tool_use_delta",toolCall:{id:c,toolName:o,args:h??{}}});});let i=await s.finalMessage(),m={promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.input_tokens+i.usage.output_tokens,cacheReadTokens:i.usage.cache_read_input_tokens,cacheCreationTokens:i.usage.cache_creation_input_tokens};return this.recordUsage(m,e),e.onChunk?.({type:"stop",stopReason:i.stop_reason??void 0}),this.processResponse(i,m)}catch(s){throw this.handleApiError(s),s}}processResponse(e,a){let n="",s=[];for(let t of e.content)t.type==="text"?n+=t.text:t.type==="tool_use"&&s.push({id:t.id,toolName:t.name,args:t.input??{}});return {text:n,toolCalls:s,usage:a,stopReason:e.stop_reason??void 0}}buildMessages(e){let a=[];for(let n of e){if(n.role==="system")continue;let s=n.role==="tool"?"user":n.role;if(typeof n.content=="string")a.push({role:s,content:n.content});else {let t=[];for(let o of n.content)o.type==="text"&&o.text?t.push({type:"text",text:o.text}):o.type==="tool_use"&&o.id&&o.name&&o.input?t.push({type:"tool_use",id:o.id,name:o.name,input:o.input}):o.type==="tool_result"&&o.tool_use_id?t.push({type:"tool_result",tool_use_id:o.tool_use_id,content:typeof o.content=="string"?o.content:""}):o.type==="image"&&o.source&&t.push({type:"image",source:{type:"base64",media_type:o.source.media_type,data:o.source.data}});t.length>0&&a.push({role:s,content:t});}}return a}convertTools(e){return e.map(a=>({name:a.name,description:a.description,input_schema:a.inputSchema}))}handleApiError(e){throw e instanceof M.APIError?e.status===429?new c("anthropic"):e.message?.includes("prompt is too long")||e.message?.includes("context_length_exceeded")?new d("anthropic"):new b$1(`Anthropic API error: ${e.message}`,"anthropic",{status:e.status}):e}};export{C as a};
@@ -0,0 +1,4 @@
1
+ import {b}from'./chunk-B7K2OWKC.js';import {h,a}from'./chunk-3QP5BQ3L.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';h();var m=class p{constructor(t){this.toolRegistry=t;p.instance=this;}static{a(this,"MCPManager");}static instance=null;connections=new Map;static getInstance(){if(!p.instance)throw new Error("MCPManager not initialized. Connect to servers first.");return p.instance}async connectAll(t){let e=Object.entries(t);if(e.length===0)return;let s=await Promise.allSettled(e.map(([r,n])=>this.connect(r,n)));for(let r=0;r<s.length;r++){let n=s[r];n.status==="rejected"&&b.warn("mcp.connect_failed",{server:e[r][0],error:n.reason.message});}}async connect(t,e){if(this.connections.has(t)){b.info("mcp.already_connected",{server:t});return}b.info("mcp.connecting",{server:t,transport:e.transport??"stdio"});let s=new Client({name:"code-shell",version:"0.1.0"},{capabilities:{}}),r,n=e.transport??"stdio";if(n==="stdio"){if(!e.command)throw new Error(`MCP server "${t}": command is required for stdio transport`);r=new StdioClientTransport({command:e.command,args:e.args,env:e.env?{...process.env,...e.env}:void 0});}else if(n==="streamable-http"||n==="sse"){if(!e.url)throw new Error(`MCP server "${t}": url is required for ${n} transport`);r=new StreamableHTTPClientTransport(new URL(e.url),{requestInit:e.headers?{headers:e.headers}:void 0});}else throw new Error(`MCP server "${t}": unsupported transport "${n}"`);let i=15e3,o;try{await new Promise((l,c)=>{o=setTimeout(()=>{c(new Error(`MCP server "${t}" connect timed out after ${i}ms`));},i),s.connect(r).then(()=>l(),f=>c(f));});}catch(l){try{await r.close?.();}catch{}throw l}finally{o&&clearTimeout(o);}this.connections.set(t,{client:s,serverName:t,transport:r}),await this.discoverTools(t,s),b.info("mcp.connected",{server:t});}async discoverTools(t,e){let s=await e.listTools();for(let r of s.tools){let n={name:`mcp_${t}_${r.name}`,description:`[${t}] ${r.description??r.name}`,inputSchema:r.inputSchema??{type:"object",properties:{}},source:"mcp",serverName:t,permissionDefault:"ask",isConcurrencySafe:true,isReadOnly:false};this.toolRegistry.registerTool(n,async i=>{let o=await e.callTool({name:r.name,arguments:i}),l=[];if(Array.isArray(o.content))for(let c of o.content)typeof c=="object"&&c!==null&&"text"in c?l.push(String(c.text)):typeof c=="string"&&l.push(c);return l.join(`
2
+ `)||"(no output)"}),b.info("mcp.tool_registered",{server:t,tool:n.name});}}async disconnectAll(){for(let[t,e]of this.connections)try{await e.client.close(),b.info("mcp.disconnected",{server:t});}catch(s){b.warn("mcp.disconnect_error",{server:t,error:s.message});}this.connections.clear();}listServers(){return [...this.connections.keys()]}async callTool(t,e,s){let r=this.connections.get(t);if(!r)throw new Error(`MCP server "${t}" is not connected.`);let n=await r.client.callTool({name:e,arguments:s}),i=[];if(Array.isArray(n.content))for(let o of n.content)typeof o=="object"&&o!==null&&"text"in o?i.push(String(o.text)):typeof o=="string"&&i.push(o);return i.join(`
3
+ `)||"(no output)"}async listResources(t){let e=[],s=t?[t]:[...this.connections.keys()];for(let r of s){let n=this.connections.get(r);if(n)try{let i=await n.client.listResources();for(let o of i.resources)e.push({uri:o.uri,name:o.name??o.uri,description:o.description});}catch{}}return e}async readResource(t,e){let s=this.connections.get(t);if(!s)throw new Error(`MCP server "${t}" is not connected.`);let r=await s.client.readResource({uri:e}),n=[];if(Array.isArray(r.contents))for(let i of r.contents)typeof i=="object"&&i!==null&&"text"in i&&n.push(String(i.text));return n.join(`
4
+ `)||"(no content)"}};export{m as a};