@swifty.js/swifty 0.0.10 → 0.0.11

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.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{h as a}from"./chunk-RNUCVDX2.js";import"./chunk-GQ2COSTQ.js";import"./chunk-FZPTNGTU.js";import"./chunk-M5AOLYFS.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{g as P}from"./chunk-H7VXSMJR.js";import{k as C}from"./chunk-GQ2COSTQ.js";import{e as F,g as G,h as R}from"./chunk-MSJOPX6X.js";import{b as O,c as $,d as I,e as K,f as W,g as D}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{C as w,I as N,J as v,K as j,L as B,M,N as k,O as U,g as S}from"./chunk-M5AOLYFS.js";import"./chunk-X3UA5OZL.js";var x=N({module:"llm"});var Y=3e3,q=w.object({max_input_tokens:w.coerce.number()});async function at(o){if(o.protocol!=="anthropic")return 0;let e=R(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,r=new AbortController,s=setTimeout(()=>{r.abort()},Y);try{let l=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...e?{"x-api-key":e}:{}},signal:r.signal});if(!l.ok)return 0;let g=await l.json(),{success:h,error:f,data:d}=await S(q,g);if(!h)return console.error(f.message),0;let y=d.max_input_tokens;return Math.max(y,0)}catch(l){return console.error(l),0}finally{clearTimeout(s)}}function J(){return!0}function L(o){return typeof o=="string"?[{type:"text",text:o}]:o}function z(o){let e=[];for(let t of o)if(t.role==="assistant"){let n=[];if(t.thinkingBlocks)for(let s of t.thinkingBlocks)n.push({type:"thinking",thinking:s.thinking,signature:s.signature});let r=typeof t.content=="string"?t.content:j(t.content);if(r&&n.push({type:"text",text:r}),t.toolUses)for(let s of t.toolUses)n.push({type:"tool_use",id:s.toolUseId,name:s.toolName,input:s.arguments});n.length===0&&n.push({type:"text",text:""}),e.push({role:"assistant",content:n})}else if(t.toolResults&&t.toolResults.length>0){let n=[];for(let r of t.toolResults)n.push({type:"tool_result",tool_use_id:r.toolUseId,is_error:r.isError,content:r.content});e.push({role:"user",content:n})}else{if(e.length===0){e.push({role:"user",content:L(t.content)});continue}let n=!1,r=e[e.length-1],s=r.content;r.role==="user"&&(typeof s=="string"||Array.isArray(s)&&s.length>0&&(s[0].type==="text"||s[0].type==="image"))&&(n=!0),n?(typeof s=="string"&&(s=r.content=s.trim().length>0?[{type:"text",text:s}]:[]),s.push(...L(t.content))):e.push({role:"user",content:L(t.content)})}return e}var H=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(e,t){let n=R(e);if(!n)throw new I("Anthropic API key not found, set ANTHROPIC_API_KEY in .swifty/config.y(a)ml, or via ANTHROPIC_API_KEY env variable.");this.client=new P({apiKey:n,baseURL:e.base_url}),this.model=e.model,this.thinking=e.thinking??!0,this.systemPrompt=t,this.maxOutputTokens=G(e),this.contextWindow=F(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,n){let r=z(O(e.getMessages())),s=t.map(c=>{let p=c.input_schema;return{name:c.name,description:c.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}}});s.length>0&&(s[s.length-1].cache_control={type:"ephemeral"}),Q(r);let l={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:r,...s.length>0?{tools:s}:{}};this.thinking?J()&&(l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let g=0,h=0,f=0,d=0,y="end_turn",T="",b="",A=!1,E=0;try{let c=this.client.messages.stream(l,{...n?{signal:n}:{}}),p="",_="",u="";for await(let i of c)switch(i.type){case"content_block_start":{let a=i.content_block;a.type==="thinking"?(A=!0,T="",b=""):a.type==="tool_use"&&(_=a.id,p=a.name,u="",yield{type:"tool_call_start",toolName:p,toolId:_});break}case"content_block_delta":{let a=i.delta;a.type==="thinking_delta"?(T+=a.thinking,yield{type:"thinking_delta",text:a.thinking}):a.type==="signature_delta"?(x.debug({signature:a.signature},"thinking signature received"),b=a.signature):a.type==="text_delta"?yield{type:"text_delta",text:a.text}:a.type==="input_json_delta"&&(u+=a.partial_json,yield{type:"tool_call_delta",text:a.partial_json});break}case"content_block_stop":{if(A&&(yield{type:"thinking_complete",thinking:T,signature:b},A=!1),p){let a={};if(u)try{let m=JSON.parse(u);a=B(m)?M(m):{[v]:u}}catch(m){x.error({err:m},"llm operation failed"),a={[v]:u}}yield{type:"tool_call_complete",toolId:_,toolName:p,arguments:a},p="",_="",u=""}break}case"message_delta":{i.delta.stop_reason&&(y=i.delta.stop_reason),i.usage.output_tokens&&(h=i.usage.output_tokens,i.usage.input_tokens&&(g=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(f=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(d=i.usage.cache_creation_input_tokens));break}case"message_start":{E=Date.now(),g=i.message.usage.input_tokens,h=i.message.usage.output_tokens,f=i.message.usage.cache_read_input_tokens??0,d=i.message.usage.cache_creation_input_tokens??0;break}case"message_stop":{let m=Date.now()-E;x.debug({elapsedMs:m},"message stream complete");break}}yield{type:"stream_end",stopReason:y,usage:{inputTokens:g,outputTokens:h,cacheReadInputTokens:f,cacheCreationInputTokens:d}}}catch(c){throw x.error({err:c},"llm operation failed"),V(c)}}};function Q(o){for(let e=o.length-1;e>=0;e--){if(o[e].role!=="user")continue;let t=o[e].content;if(typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0)return;typeof t=="string"&&(t=o[e].content=[{type:"text",text:t}]);let n=t[t.length-1];for(let r=t.length-1;r>=0;r--)if(t[r].type!=="image"){n=t[r];break}Reflect.set(n,"cache_control",{type:"ephemeral"})}}function V(o){if(o instanceof P.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new D(`Prompt too long: ${o.message}`);if(o.status===401)return new I(`Invalid API key: ${o.message}`);if(o.status===429){let e=M(o.headers)["retry-after"],t="Rate Limited";if(e){let n=Number.parseInt(k(e));Number.isNaN(n)&&(t+=", please wait."),t+=`, retry after ${k(n)}s.`}else t+=", please wait.";return new K(t,e?k(e):void 0)}return new $(`Anthropic API error (${k(o.status)}): ${o.message}`)}return new W(`Network error: ${U(o)}`)}export{H as AnthropicClient,z as buildAnthropicMessages,at as fetchModelContextWindow,Q as markLastUserTailForCache};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{a,b,c,d,e}from"./chunk-R7VREEYH.js";import"./chunk-7MHXMDYC.js";import"./chunk-M5AOLYFS.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{D as i,I as v,K as y,O as _,S as U,e as M,f as x}from"./chunk-M5AOLYFS.js";var T=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(e){this.history.push({role:"user",content:e})}addAssistantMessage(e){this.history.push({role:"assistant",content:e})}addToolUseMessage(e,o,s,n){this.history.push({role:"assistant",content:e,toolUses:[{toolUseId:o,toolName:s,arguments:n}]})}addAssistantMessageWithTools(e,o){this.history.push({role:"assistant",content:e,toolUses:o})}addAssistantFull(e,o,s){this.history.push({role:"assistant",content:e,thinkingBlocks:o.length>0?o:void 0,toolUses:s.length>0?s:void 0})}addToolResultMessage(e,o,s){this.history.push({role:"user",content:"",toolResults:[{toolUseId:e,content:o,isError:s}]})}addToolResultsMessage(e){this.history.push({role:"user",content:"",toolResults:e})}addSystemReminder(e){this.history.push({role:"user",content:`<system-reminder>
5
+ ${e}
6
+ </system-reminder>`})}injectLongTermMemory(e,o,s=""){if(this.longTermMemoryInjected)return;let n=[];if(e&&n.push(`# SWIFTY.md
7
+ Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.
8
+
9
+ `+e),o&&n.push(`# Auto Memory
10
+ `+o),s&&n.push(`# availableSkills
11
+ `+s),n.length===0)return;let r=new Date().toISOString().split("T")[0];n.push(`# Current Date
12
+ Today's date is `+r+".");let a=`
13
+ <system-reminder>
14
+ As you answer the user's questions, you can use the following context:
15
+
16
+ ${n.join(`
17
+
18
+ `)}
19
+
20
+ IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
21
+ </system-reminder>`;this.history.unshift({role:"user",content:a}),this.longTermMemoryInjected=!0}len(){return this.history.length}truncateTo(e){e<0&&(e=0),!(e>this.history.length)&&(this.history=this.history.slice(0,e))}getMessages(){return[...this.history]}replaceWithCompacted(e,o){this.history=[{role:"user",content:e},...o],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,o,s,n){let r=e+s+n+o;r<=0||(this.baselineTokens=r,this._anchorCount=this.history.length)}clearUsageAnchor(){this.baselineTokens=0,this._anchorCount=0}usageAnchorState(){return this.baselineTokens<=0?null:{baselineTokens:this.baselineTokens,anchorCount:this._anchorCount}}};import{randomBytes as z}from"crypto";import{readFileSync as I,writeFileSync as H,readdirSync as W,mkdirSync as J,statSync as X,existsSync as A,unlinkSync as we,rmSync as Ce}from"fs";import{join as p}from"path";var S="compact_boundary";var E=i.object({tool_use_id:i.string(),tool_name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),k=i.union([i.string(),i.array(i.record(i.string(),i.unknown()))]),N=i.object({tool_use_id:i.string(),content:k,is_error:i.boolean().optional()}),B=i.object({role:i.string(),content:k.default(""),timestamp:i.number(),type:i.string().optional(),tool_uses:i.array(E).optional(),tool_results:i.array(N).optional()}),G=i.object({role:i.string(),content:k,tool_uses:i.array(E).optional(),tool_results:i.array(N).optional()});function O(t){return(t??[]).map(e=>({tool_use_id:e.toolUseId,tool_name:e.toolName,...e.arguments&&Object.keys(e.arguments).length?{arguments:e.arguments}:{}}))}function L(t){return(t??[]).map(e=>({tool_use_id:e.toolUseId,content:e.content,...e.isError?{is_error:!0}:{}}))}var V=i.object({summary:i.string(),keep:i.array(G)}),b=v({module:"session"});function R(t){return p(t,".swifty","sessions")}function Pe(t,e){return p(R(t),e+".jsonl")}function Ie(){let t=Date.now().toString(36),e=z(4).toString("hex");return`${t}-${e}`}function Q(t,e,o){let s=R(t);J(s,{recursive:!0});let n=p(s,`${e}.jsonl`),r=JSON.stringify(o)+`
22
+ `;H(n,r,{flag:"a",encoding:"utf-8"})}function Ae(t,e,o){Q(t,e,{role:"system",content:JSON.stringify(o),timestamp:Math.floor(Date.now()/1e3),type:S})}function Ee(t,e){let o=p(R(t),`${e}.jsonl`);if(!A(o))return[];let s=[];for(let n of I(o,"utf-8").split(`
23
+ `))if(n.trim())try{let r=JSON.parse(n),{success:l,data:a,error:c}=x(B,r);l?!a.content&&!(a.tool_uses?.length??0)&&!(a.tool_results?.length??0)||s.push(a):b.error({err:c},"session operation failed")}catch(r){b.error({err:r},"session operation failed")}return s}function j(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function F(t){return t?.map(e=>({toolUseId:e.tool_use_id,content:e.content,isError:e.is_error}))}function Ne(t){let e=-1;for(let s=t.length-1;s>=0;s--)if(t[s].type===S){e=s;break}let o=[];if(e>=0){let s=null;try{let n=t[e].content,r=typeof n=="string"?JSON.parse(n):null;s=M(V,r)}catch{s=null}if(s){let n=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
24
+
25
+ `+s.summary;s.keep.length>0&&(n+=`
26
+
27
+ Recent messages have been preserved verbatim.`),o.push({role:"user",content:n});for(let r of s.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||o.push({role:r.role,content:r.content,toolUses:j(r.tool_uses),toolResults:F(r.tool_results)})}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===S)continue;let l=P(r);l&&o.push(l)}return o}for(let s of t){let n=P(s);n&&o.push(n)}return o}function P(t){return t.role!=="user"&&t.role!=="assistant"||!t.content&&!(t.tool_uses?.length??0)&&!(t.tool_results?.length??0)?null:{role:t.role,content:t.content,toolUses:j(t.tool_uses),toolResults:F(t.tool_results)}}function Be(t){let e=R(t);if(!A(e))return[];let o=W(e).filter(n=>n.endsWith(".jsonl")),s=[];for(let n of o){let r=p(e,n),l=X(r),a=n.replace(".jsonl",""),c="",u=0;try{for(let d of I(r,"utf-8").split(`
28
+ `)){if(!d.trim())continue;let m;try{let g=JSON.parse(d);m=M(B,g)}catch(g){b.error({err:g},"session operation failed");continue}u++,!c&&m.role==="user"&&m.content&&(c=y(m.content).slice(0,100))}}catch(d){b.error({err:d},"session operation failed");continue}s.push({id:a,firstMessage:c,messageCount:u,size:l.size,modTime:l.mtime})}return s.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),s}var D=3,Z=3,ee="[earlier conversation truncated for compaction retry]",te=3.5,oe=1e4,se=5,ne=4e4,re=2,ie=2e4,ae=13e3,le=3e3;function $(t,e,o=!1){return t-Math.min(e,ie)-(o?le:ae)}var q=class{consecutiveFailures=0},ce=7e3;function Y(t){if(typeof t=="string")return t.length;let e=0;for(let o of t)o.type==="text"?e+=U(o,"text").length:o.type==="image"&&(e+=ce);return e}function w(t){let e=0;for(let o of t){if(e+=Y(o.content),o.toolUses&&(e+=JSON.stringify(o.toolUses).length),o.toolResults)for(let s of o.toolResults)e+=Y(s.content);if(o.thinkingBlocks)for(let s of o.thinkingBlocks)e+=s.thinking.length}return Math.ceil(e/te)}function ue(t){return w(t.getMessages())}function C(t){return w([t])}function de(t){return t.role==="user"&&!!t.toolResults&&t.toolResults.length>0}function me(t){let e=0,o=0,s=t.length;for(let n=t.length-1;n>=0;n--){let r=C(t[n]);if(o>0&&e+r>ne||(s=n,e+=r,o++,e>=oe||o>=se))break}return s=he(t,s),s}function he(t,e){if(e<=0||e>=t.length||!de(t[e]))return e;let o=new Set((t[e].toolResults??[]).map(s=>s.toolUseId));for(let s=e-1;s>=0;s--){let n=t[s];if(n.role==="assistant"&&n.toolUses?.some(r=>o.has(r.toolUseId)))return s}return e}function ge(t,e){let o=e??t.usageAnchorState();if(!o)return ue(t);let s=t.getMessages(),n=Math.min(o.anchorCount,s.length);return o.baselineTokens+w(s.slice(n))}async function De(t,e,o,s,n,r,l,a,c=""){let u=ge(t),d=$(o,s),m=$(o,s,!0);if(u<d)return{compacted:!1,message:""};if(!(u>=m)&&n.consecutiveFailures>=D)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(D)} consecutive failures`};try{let f=await K(t,e,r,l,a,c);return n.consecutiveFailures=0,f}catch(f){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${_(f)}`}}}async function $e(t,e,o,s,n,r=""){return K(t,e,o,s,n,r)}var fe=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
29
+ This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
30
+
31
+ Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
32
+
33
+ 1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
34
+ - The user's explicit requests and intents
35
+ - Your approach to addressing the user's requests
36
+ - Key decisions, technical concepts and code patterns
37
+ - Specific details like:
38
+ - file names
39
+ - full code snippets
40
+ - function signatures
41
+ - file edits
42
+ - Errors that you ran into and how you fixed them
43
+ - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
44
+ 2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
45
+
46
+ After your analysis, output your final summary wrapped in <summary> tags. Your summary should include the following sections:
47
+
48
+ 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
49
+ 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
50
+ 3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
51
+ 4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
52
+ 5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
53
+ 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
54
+ 7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
55
+ 8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
56
+ 9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
57
+ If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
58
+
59
+ Here's an example of how your output should be structured:
60
+
61
+ <example>
62
+ <analysis>
63
+ [Your thought process, ensuring all points are covered thoroughly and accurately]
64
+ </analysis>
65
+
66
+ <summary>
67
+ 1. Primary Request and Intent:
68
+ [Detailed description]
69
+
70
+ 2. Key Technical Concepts:
71
+ - [Concept 1]
72
+ - [Concept 2]
73
+ - [...]
74
+
75
+ 3. Files and Code Sections:
76
+ - [File Name 1]
77
+ - [Summary of why this file is important]
78
+ - [Summary of the changes made to this file, if any]
79
+ - [Important Code Snippet]
80
+ - [File Name 2]
81
+ - [Important Code Snippet]
82
+ - [...]
83
+
84
+ 4. Errors and fixes:
85
+ - [Detailed description of error 1]:
86
+ - [How you fixed the error]
87
+ - [User feedback on the error if any]
88
+ - [...]
89
+
90
+ 5. Problem Solving:
91
+ [Description of solved problems and ongoing troubleshooting]
92
+
93
+ 6. All user messages:
94
+ - [Detailed non tool use user message]
95
+ - [...]
96
+
97
+ 7. Pending Tasks:
98
+ - [Task 1]
99
+ - [Task 2]
100
+ - [...]
101
+
102
+ 8. Current Work:
103
+ [Precise description of current work]
104
+
105
+ 9. Optional Next Step:
106
+ [Optional Next step to take]
107
+
108
+ </summary>
109
+ </example>
110
+
111
+ Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function pe(t){return fe+`
112
+
113
+ `+t}function ye(t){let e=[],o=[],s=!1;for(let n of t)n.role==="assistant"&&s&&o.length>0&&(e.push(o),o=[]),o.push(n),s=!!(n.toolResults&&n.toolResults.length>0);return o.length>0&&e.push(o),e}function Te(t,e){let o=ye(t);if(o.length<2)return null;let s;if(e>0){let r=0;s=0;for(let l of o)if(r+=l.reduce((a,c)=>a+C(c),0),s++,r>=e)break}else s=Math.max(1,Math.floor(o.length/5));if(s=Math.min(s,o.length-1),s<1)return null;let n=o.slice(s).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:ee}),n}function be(t){return t.map(e=>{let o=`[${e.role}]: ${y(e.content)}`;return e.toolUses&&(o+=`
114
+ [tools: ${e.toolUses.map(s=>s.toolName).join(", ")}]`),o}).join(`
115
+
116
+ `)}async function Re(t,e,o){let s=e;for(let n=0;;n++){let r=be(s),l=new T;l.addUserMessage(pe(r));try{let a="",c=t.stream(l,o);for await(let d of c)d.type==="text_delta"&&(a+=d.text);let u=/<summary>([\s\S]*?)<\/summary>/.exec(a);return u?u[1].trim():a}catch(a){let c=a instanceof Error?a.message.toLowerCase():"";if(!(c.includes("prompt")&&c.includes("long")||c.includes("too many")||c.includes("context_length"))||n>=Z)throw a;let d=s.reduce((g,f)=>g+C(f),0)/5,m=Te(s,d);if(!m)throw a;s=m}}}async function K(t,e,o,s,n,r=""){let l=t.getMessages(),a=me(l);if(a<=0||a<re)return{compacted:!1,message:`Compaction skipped: only ${String(a)} message(s) to summarize, kept verbatim`};let c=l.slice(0,a),u=l.slice(a),d=await Re(e,c,n),m=o?o.buildRecoveryAttachment(s):"",g=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
117
+
118
+ `+d;u.length>0&&(g+=`
119
+
120
+ Recent messages have been preserved verbatim.`),r&&(g+=`
121
+
122
+ If you need specific details from before compaction (code snippets, error messages, etc.), use ReadFile to read the full session transcript: ${r}`),m&&(g+=`
123
+
124
+ ---
125
+
126
+ ${m}`),t.replaceWithCompacted(g,u);let f=u.filter(h=>(h.role==="user"||h.role==="assistant")&&(h.content||(h.toolUses?.length??0)||(h.toolResults?.length??0))).map(h=>({role:h.role,content:h.content,...h.toolUses?.length?{tool_uses:O(h.toolUses)}:{},...h.toolResults?.length?{tool_results:L(h.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(c.length)} messages into summary (${String(d.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:d,keep:f}}}export{T as a,O as b,L as c,Pe as d,Ie as e,Q as f,Ae as g,Ee as h,Ne as i,Be as j,$ as k,q as l,De as m,$e as n};