@swifty.js/swifty 0.0.22 → 0.0.24
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.
- package/dist/{agent-5T7KNC7V.js → agent-24XMR2WX.js} +1 -1
- package/dist/anthropic-7QRAPLOY.js +4 -0
- package/dist/{checker-OJFS2MZY.js → checker-3RWAYF2U.js} +1 -1
- package/dist/{chunk-HJIGA37J.js → chunk-5KXBVL2A.js} +1 -1
- package/dist/chunk-FAJYJI6T.js +389 -0
- package/dist/chunk-MWZIARZE.js +130 -0
- package/dist/{chunk-GUXBLUNR.js → chunk-NR62AA5K.js} +1 -1
- package/dist/chunk-QN27QEFS.js +4 -0
- package/dist/{chunk-LX2LK3TF.js → chunk-SIWLMWHH.js} +12 -11
- package/dist/{chunk-NEAR6YPZ.js → chunk-VQUWSKQQ.js} +21 -20
- package/dist/{chunk-NLNH3IRT.js → chunk-W37Y53LX.js} +1 -1
- package/dist/lib/agent-U42LS73D.js +9 -0
- package/dist/lib/{anthropic-GFWP3ORB.js → anthropic-RYPJDHQM.js} +6 -6
- package/dist/lib/{checker-IIXJXQCB.js → checker-6BW4222R.js} +3 -3
- package/dist/lib/{chunk-LUEP4JMF.js → chunk-2AUSNVIB.js} +8 -12
- package/dist/lib/{chunk-C7IHCJZ3.js → chunk-2QILP24G.js} +283 -12
- package/dist/lib/{chunk-6GOWRPYS.js → chunk-3LU4APFB.js} +2 -2
- package/dist/lib/{chunk-EJLGB2EJ.js → chunk-EY7HE52Q.js} +14 -7
- package/dist/lib/{chunk-7URDLWQN.js → chunk-GNI7YX6F.js} +2 -2
- package/dist/lib/{chunk-UMFNTXKA.js → chunk-OO2CLOEE.js} +38 -38
- package/dist/lib/{chunk-GNBXECZN.js → chunk-PZ42NAFA.js} +2 -3
- package/dist/lib/{chunk-RR2CZ6CY.js → chunk-XFSN4LMA.js} +94 -75
- package/dist/lib/{chunk-UHVO63Y7.js → chunk-XG6NELJH.js} +69 -38
- package/dist/lib/index.d.ts +234 -237
- package/dist/lib/index.js +212 -224
- package/dist/lib/{openai-HXRMPNB7.js → openai-VX5VBXZ4.js} +4 -4
- package/dist/main.js +197 -465
- package/dist/{openai-TVUUHRG7.js → openai-6MXNADYN.js} +15 -15
- package/dist/{server-ZTLHJWEQ.js → server-NJ2NXAOI.js} +16 -16
- package/package.json +5 -5
- package/dist/anthropic-P2R4GW6F.js +0 -4
- package/dist/chunk-L73IHJF4.js +0 -386
- package/dist/chunk-YQQVB6VB.js +0 -127
- package/dist/chunk-ZZQE743W.js +0 -4
- package/dist/lib/agent-2AGRYN3R.js +0 -9
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{g as E}from"./chunk-FZPTNGTU.js";import{D as a,I,J as h,N as P,R as U,e as C,f as A}from"./chunk-SIWLMWHH.js";var y=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(t){this.history.push({role:"user",content:t})}addAssistantMessage(t){this.history.push({role:"assistant",content:t})}addToolUseMessage(t,n,o,s){this.history.push({role:"assistant",content:t,toolUses:[{toolUseId:n,toolName:o,arguments:s}]})}addAssistantMessageWithTools(t,n){this.history.push({role:"assistant",content:t,toolUses:n})}addAssistantFull(t,n,o){this.history.push({role:"assistant",content:t,thinkingBlocks:n.length>0?n:void 0,toolUses:o.length>0?o:void 0})}addToolResultMessage(t,n,o,s){this.history.push({role:"user",content:"",toolResults:[{toolUseId:t,content:n,...s?.length?{contentBlocks:s}:{},isError:o}]})}addToolResultsMessage(t){this.history.push({role:"user",content:"",toolResults:t})}addSystemReminder(t){this.history.push({role:"user",content:`<system-reminder>
|
|
5
|
+
${t}
|
|
6
|
+
</system-reminder>`})}hasReminderContaining(t){return this.history.some(n=>n.role==="user"&&h(n.content).includes(t))}injectLongTermMemory(t,n,o=""){if(this.longTermMemoryInjected)return;let s=[];if(t&&s.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
|
+
${t}}`),n&&s.push(`# Auto Memory
|
|
10
|
+
`+n),o&&s.push(`# Available Skills
|
|
11
|
+
`+o),s.length===0)return;let r=new Date().toISOString().split("T")[0];s.push(`# Current Date
|
|
12
|
+
|
|
13
|
+
Today's date is ${r}.`);let i=`
|
|
14
|
+
<system-reminder>
|
|
15
|
+
As you answer the user's questions, you can use the following context:
|
|
16
|
+
|
|
17
|
+
${s.join(`
|
|
18
|
+
|
|
19
|
+
`)}
|
|
20
|
+
|
|
21
|
+
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.
|
|
22
|
+
</system-reminder>`;this.history.unshift({role:"user",content:i}),this.longTermMemoryInjected=!0}appendMessages(t){this.history.push(...t)}len(){return this.history.length}truncateTo(t){t<0&&(t=0),!(t>this.history.length)&&(this.history=this.history.slice(0,t))}reset(){this.history=[],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}getMessages(){return[...this.history]}replaceWithCompacted(t,n){this.history=[{role:"user",content:t},...n],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(t,n,o,s){let r=t+o+s+n;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 oe}from"crypto";import{readFileSync as O,writeFileSync as ne,readdirSync as se,mkdirSync as re,statSync as ie,existsSync as D,unlinkSync as De,rmSync as Fe}from"fs";import{join as k}from"path";function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Z=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function ee(e){return Z.has(e)}function M(e){return T(e)&&e.type==="text"&&typeof e.text=="string"?{type:"text",text:e.text}:null}function v(e){return!T(e)||e.type!=="image"||!T(e.source)?null:e.source.type==="url"&&typeof e.source.url=="string"?{type:"image",source:{type:"url",url:e.source.url}}:e.source.type==="base64"&&typeof e.source.media_type=="string"&&ee(e.source.media_type)&&typeof e.source.data=="string"?{type:"image",source:{type:"base64",media_type:e.source.media_type,data:e.source.data}}:null}function te(e){if(e.type!=="document"||!T(e.source))return null;let t=null;if(e.source.type==="url"&&typeof e.source.url=="string")t={type:"url",url:e.source.url};else if(e.source.type==="base64"&&e.source.media_type==="application/pdf"&&typeof e.source.data=="string")t={type:"base64",media_type:"application/pdf",data:e.source.data};else if(e.source.type==="text"&&e.source.media_type==="text/plain"&&typeof e.source.data=="string")t={type:"text",media_type:"text/plain",data:e.source.data};else if(e.source.type==="content"){if(typeof e.source.content=="string")t={type:"content",content:e.source.content};else if(Array.isArray(e.source.content)){let n=[];for(let o of e.source.content){let s=M(o)??v(o);if(!s)return null;n.push(s)}t={type:"content",content:n}}}return t?{type:"document",source:t,...typeof e.title=="string"||e.title===null?{title:e.title}:{},...typeof e.context=="string"||e.context===null?{context:e.context}:{}}:null}function j(e){let t=M(e);if(t)return t;let n=v(e);if(n)return n;if(!T(e))return null;if(e.type==="tool_reference"&&typeof e.tool_name=="string")return{type:"tool_reference",tool_name:e.tool_name};if(e.type==="search_result"&&typeof e.source=="string"&&typeof e.title=="string"&&Array.isArray(e.content)){let o=[];for(let s of e.content){let r=M(s);if(!r)return null;o.push(r)}return{type:"search_result",source:e.source,title:e.title,content:o}}return te(e)}var je=new Set([".claude",".git",".swifty",".next",".venv",".mypy_cache",".tox","__pycache__","build","dist","node_modules","vendor","venv"]);var S="compact_boundary";var F=a.object({tool_use_id:a.string(),tool_name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),_=a.union([a.string(),a.array(a.record(a.string(),a.unknown()))]),$=a.object({tool_use_id:a.string(),content:_,content_blocks:a.array(a.unknown()).optional(),is_error:a.boolean().optional()}),z=a.object({role:a.string(),content:_.default(""),timestamp:a.number(),type:a.string().optional(),tool_uses:a.array(F).optional(),tool_results:a.array($).optional()}),ae=a.object({role:a.string(),content:_,tool_uses:a.array(F).optional(),tool_results:a.array($).optional()});function q(e){return(e??[]).map(t=>({tool_use_id:t.toolUseId,tool_name:t.toolName,...t.arguments&&Object.keys(t.arguments).length?{arguments:t.arguments}:{}}))}function Y(e){return(e??[]).map(t=>({tool_use_id:t.toolUseId,content:t.content,...t.contentBlocks?.length?{content_blocks:t.contentBlocks}:{},...t.isError?{is_error:!0}:{}}))}var le=a.object({summary:a.string(),keep:a.array(ae)}),R=I({module:"session"});function b(e){return k(e,".swifty","sessions")}function He(e,t){return k(b(e),t+".jsonl")}function We(){let e=Date.now().toString(36),t=oe(4).toString("hex");return`${e}-${t}`}function ce(e,t,n){let o=b(e);re(o,{recursive:!0});let s=k(o,`${t}.jsonl`),r=JSON.stringify(n)+`
|
|
23
|
+
`;ne(s,r,{flag:"a",encoding:"utf-8"})}function Je(e,t,n){ce(e,t,{role:"system",content:JSON.stringify(n),timestamp:Math.floor(Date.now()/1e3),type:S})}function Ge(e,t){let n=k(b(e),`${t}.jsonl`);if(!D(n))return[];let o=[];for(let s of O(n,"utf-8").split(`
|
|
24
|
+
`))if(s.trim())try{let r=JSON.parse(s),{success:l,data:i,error:c}=A(z,r);l?!i.content&&!(i.tool_uses?.length??0)&&!(i.tool_results?.length??0)||o.push(i):R.error({err:c},"session operation failed")}catch(r){R.error({err:r},"session operation failed")}return o}function K(e){return e?.map(t=>({toolUseId:t.tool_use_id,toolName:t.tool_name,arguments:t.arguments}))}function N(e){if(!e)return;let t=[];for(let n of e){let o=j(n);o&&t.push(o)}return t.length>0?t:void 0}function H(e){return e?.map(t=>{let n=Array.isArray(t.content)?N(t.content):void 0,o=N(t.content_blocks)??n;return{toolUseId:t.tool_use_id,content:typeof t.content=="string"?t.content:h(t.content),...o?{contentBlocks:o}:{},isError:t.is_error??!1}})}function Xe(e){let t=-1;for(let o=e.length-1;o>=0;o--)if(e[o].type===S){t=o;break}let n=[];if(t>=0){let o=null;try{let s=e[t].content,r=typeof s=="string"?JSON.parse(s):null;o=C(le,r)}catch{o=null}if(o){let s=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
25
|
+
|
|
26
|
+
`+o.summary;o.keep.length>0&&(s+=`
|
|
27
|
+
|
|
28
|
+
Recent messages have been preserved verbatim.`),n.push({role:"user",content:s});for(let r of o.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||n.push({role:r.role,content:r.content,toolUses:K(r.tool_uses),toolResults:H(r.tool_results)})}for(let s=t+1;s<e.length;s++){let r=e[s];if(r.type===S)continue;let l=L(r);l&&n.push(l)}return n}for(let o of e){let s=L(o);s&&n.push(s)}return n}function L(e){return e.role!=="user"&&e.role!=="assistant"||!e.content&&!(e.tool_uses?.length??0)&&!(e.tool_results?.length??0)?null:{role:e.role,content:e.content,toolUses:K(e.tool_uses),toolResults:H(e.tool_results)}}function Ve(e){let t=b(e);if(!D(t))return[];let n=se(t).filter(s=>s.endsWith(".jsonl")),o=[];for(let s of n){let r=k(t,s),l=ie(r),i=s.replace(".jsonl",""),c="",u=0;try{for(let p of O(r,"utf-8").split(`
|
|
29
|
+
`)){if(!p.trim())continue;let d;try{let f=JSON.parse(p);d=C(z,f)}catch(f){R.error({err:f},"session operation failed");continue}u++,!c&&d.role==="user"&&d.content&&(c=h(d.content).slice(0,100))}}catch(p){R.error({err:p},"session operation failed");continue}o.push({id:i,firstMessage:c,messageCount:u,size:l.size,modTime:l.mtime})}return o.sort((s,r)=>r.modTime.getTime()-s.modTime.getTime()),o}var W=3,ue=3,me="[earlier conversation truncated for compaction retry]",pe=3.5,de=1e4,fe=5,ge=4e4,he=2,ye=2e4,Te=13e3,ke=3e3;function J(e,t,n=!1){return e-Math.min(t,ye)-(n?ke:Te)}var G=class{consecutiveFailures=0},x=7e3;function Re(e){if(typeof e=="string")return e.length;let t=0;for(let n of e)n.type==="text"?t+=U(n,"text").length:n.type==="image"&&(t+=x);return t}function be(e){let t=0,n=0;for(let o of e)switch(o.type){case"text":{t+=o.text.length;break}case"image":{n+=x;break}case"tool_reference":{n+=o.tool_name.length;break}case"search_result":{n+=o.source.length+o.title.length,n+=o.content.reduce((s,r)=>s+r.text.length,0);break}case"document":{switch(o.source.type){case"base64":{n+=x;break}case"url":{n+=o.source.url.length;break}case"text":{n+=o.source.data.length;break}case"content":{if(typeof o.source.content=="string"){n+=o.source.content.length;break}for(let s of o.source.content)n+=s.type==="text"?s.text.length:x;break}}break}}return{textChars:t,richChars:n}}function w(e){let t=0;for(let n of e){if(t+=Re(n.content),n.toolUses&&(t+=JSON.stringify(n.toolUses).length),n.toolResults)for(let o of n.toolResults)if(o.contentBlocks?.length){let s=be(o.contentBlocks);t+=Math.max(o.content.length,s.textChars)+s.richChars}else t+=o.content.length;if(n.thinkingBlocks)for(let o of n.thinkingBlocks)t+=o.thinking.length}return Math.ceil(t/pe)}function xe(e){return w(e.getMessages())}function B(e){return w([e])}function Ce(e){return e.role==="user"&&!!e.toolResults&&e.toolResults.length>0}function Me(e){let t=0,n=0,o=e.length;for(let s=e.length-1;s>=0;s--){let r=B(e[s]);if(n>0&&t+r>ge||(o=s,t+=r,n++,t>=de||n>=fe))break}return o=Se(e,o),o}function Se(e,t){if(t<=0||t>=e.length||!Ce(e[t]))return t;let n=new Set((e[t].toolResults??[]).map(o=>o.toolUseId));for(let o=t-1;o>=0;o--){let s=e[o];if(s.role==="assistant"&&s.toolUses?.some(r=>n.has(r.toolUseId)))return o}return t}function _e(e,t){let n=t??e.usageAnchorState();if(!n)return xe(e);let o=e.getMessages(),s=Math.min(n.anchorCount,o.length);return n.baselineTokens+w(o.slice(s))}async function nt(e,t,n,o,s,r,l,i,c=""){let u=_e(e),p=J(n,o),d=J(n,o,!0);if(u<p)return{compacted:!1,message:""};if(!(u>=d)&&s.consecutiveFailures>=W)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(W)} consecutive failures`};try{let g=await Q(e,t,r,l,i,c);return s.consecutiveFailures=0,g}catch(g){return s.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${P(g)}`}}}async function st(e,t,n,o,s,r=""){return Q(e,t,n,o,s,r)}var X=`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.
|
|
30
|
+
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.
|
|
31
|
+
|
|
32
|
+
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:
|
|
33
|
+
|
|
34
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
35
|
+
- The user's explicit requests and intents
|
|
36
|
+
- Your approach to addressing the user's requests
|
|
37
|
+
- Key decisions, technical concepts and code patterns
|
|
38
|
+
- Specific details like:
|
|
39
|
+
- file names
|
|
40
|
+
- full code snippets
|
|
41
|
+
- function signatures
|
|
42
|
+
- file edits
|
|
43
|
+
- Errors that you ran into and how you fixed them
|
|
44
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
45
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
46
|
+
|
|
47
|
+
After your analysis, output your final summary wrapped in <summary> tags. Your summary should include the following sections:
|
|
48
|
+
|
|
49
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
50
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
51
|
+
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.
|
|
52
|
+
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.
|
|
53
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
54
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
55
|
+
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
56
|
+
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.
|
|
57
|
+
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.
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
Here's an example of how your output should be structured:
|
|
61
|
+
|
|
62
|
+
<example>
|
|
63
|
+
<analysis>
|
|
64
|
+
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
|
65
|
+
</analysis>
|
|
66
|
+
|
|
67
|
+
<summary>
|
|
68
|
+
1. Primary Request and Intent:
|
|
69
|
+
[Detailed description]
|
|
70
|
+
|
|
71
|
+
2. Key Technical Concepts:
|
|
72
|
+
- [Concept 1]
|
|
73
|
+
- [Concept 2]
|
|
74
|
+
- [...]
|
|
75
|
+
|
|
76
|
+
3. Files and Code Sections:
|
|
77
|
+
- [File Name 1]
|
|
78
|
+
- [Summary of why this file is important]
|
|
79
|
+
- [Summary of the changes made to this file, if any]
|
|
80
|
+
- [Important Code Snippet]
|
|
81
|
+
- [File Name 2]
|
|
82
|
+
- [Important Code Snippet]
|
|
83
|
+
- [...]
|
|
84
|
+
|
|
85
|
+
4. Errors and fixes:
|
|
86
|
+
- [Detailed description of error 1]:
|
|
87
|
+
- [How you fixed the error]
|
|
88
|
+
- [User feedback on the error if any]
|
|
89
|
+
- [...]
|
|
90
|
+
|
|
91
|
+
5. Problem Solving:
|
|
92
|
+
[Description of solved problems and ongoing troubleshooting]
|
|
93
|
+
|
|
94
|
+
6. All user messages:
|
|
95
|
+
- [Detailed non tool use user message]
|
|
96
|
+
- [...]
|
|
97
|
+
|
|
98
|
+
7. Pending Tasks:
|
|
99
|
+
- [Task 1]
|
|
100
|
+
- [Task 2]
|
|
101
|
+
- [...]
|
|
102
|
+
|
|
103
|
+
8. Current Work:
|
|
104
|
+
[Precise description of current work]
|
|
105
|
+
|
|
106
|
+
9. Optional Next Step:
|
|
107
|
+
[Optional Next step to take]
|
|
108
|
+
|
|
109
|
+
</summary>
|
|
110
|
+
</example>
|
|
111
|
+
|
|
112
|
+
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function we(e){return X+`
|
|
113
|
+
|
|
114
|
+
`+e}function Be(e){let t=[],n=[],o=!1;for(let s of e)s.role==="assistant"&&o&&n.length>0&&(t.push(n),n=[]),n.push(s),o=!!(s.toolResults&&s.toolResults.length>0);return n.length>0&&t.push(n),t}function Ae(e,t){let n=Be(e);if(n.length<2)return null;let o;if(t>0){let r=0;o=0;for(let l of n)if(r+=l.reduce((i,c)=>i+B(c),0),o++,r>=t)break}else o=Math.max(1,Math.floor(n.length/5));if(o=Math.min(o,n.length-1),o<1)return null;let s=n.slice(o).flat();return s.length>0&&s[0].role!=="user"&&s.unshift({role:"user",content:me}),s}function Ie(e){return e.map(t=>{let n=`[${t.role}]: ${h(t.content)}`;return t.toolUses&&(n+=`
|
|
115
|
+
[tools: ${t.toolUses.map(o=>o.toolName).join(", ")}]`),t.toolResults&&(n+=`
|
|
116
|
+
[tool results]
|
|
117
|
+
${t.toolResults.map(o=>o.content).join(`
|
|
118
|
+
`)}`),n}).join(`
|
|
119
|
+
|
|
120
|
+
`)}function V(e){let t=/<summary>([\s\S]*?)<\/summary>/.exec(e);if(t)return t[1].trim();let n=/<analysis>[\s\S]*?<\/analysis>/.exec(e);return n?e.replace(n[0],"").trim():e.trim()}async function Pe(e,t,n){let o=-1;for(let i=t.length-1;i>=0;i--)if(t[i].role==="assistant"){o=i;break}if(o<0)throw new Error("no assistant message found for cache-sharing compact");let s=new y;s.appendMessages(t.slice(0,o+1)),s.addUserMessage(X);let r="",l=e.stream(s,n);for await(let i of l)i.type==="text_delta"&&(r+=i.text);return V(r)}async function Ue(e,t,n){let o=t;for(let s=0;;s++){let r=Ie(o),l=new y;l.addUserMessage(we(r));try{let i="",c=e.stream(l,n);for await(let u of c)u.type==="text_delta"&&(i+=u.text);return V(i)}catch(i){let c=i instanceof Error?i.message.toLowerCase():"";if(!(c.includes("prompt")&&c.includes("long")||c.includes("too many")||c.includes("context_length"))||s>=ue)throw i;let p=o.reduce((f,g)=>f+B(g),0)/5,d=Ae(o,p);if(!d)throw i;o=d}}}async function Q(e,t,n,o,s,r=""){let l=e.getMessages(),i=Me(l);if(i<=0||i<he)return{compacted:!1,message:`Compaction skipped: only ${String(i)} message(s) to summarize, kept verbatim`};let c=l.slice(0,i),u=l.slice(i),p;try{p=await Pe(t,l,s)}catch(m){if(!(m instanceof E))throw m;p=await Ue(t,c,s)}let d=n?n.buildRecoveryAttachment(o):"",f=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
121
|
+
|
|
122
|
+
`+p;u.length>0&&(f+=`
|
|
123
|
+
|
|
124
|
+
Recent messages have been preserved verbatim.`),r&&(f+=`
|
|
125
|
+
|
|
126
|
+
If you need specific details from before compaction (code snippets, error messages, etc.), use ReadFile to read the full session transcript: ${r}`),d&&(f+=`
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
${d}`),e.replaceWithCompacted(f,u);let g=u.filter(m=>(m.role==="user"||m.role==="assistant")&&(m.content||(m.toolUses?.length??0)||(m.toolResults?.length??0))).map(m=>({role:m.role,content:m.content,...m.toolUses?.length?{tool_uses:q(m.toolUses)}:{},...m.toolResults?.length?{tool_results:Y(m.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(c.length)} messages into summary (${String(p.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:p,keep:g}}}export{y as a,je as b,q as c,Y as d,He as e,We as f,ce as g,Je as h,Ge as i,Xe as j,Ve as k,J as l,G as m,nt as n,st as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{c as F}from"./chunk-
|
|
4
|
+
import{c as F}from"./chunk-QN27QEFS.js";import{a as y}from"./chunk-7MHXMDYC.js";import{D as d,I as D,R as c,e as v}from"./chunk-SIWLMWHH.js";import{b as k}from"./chunk-E55KH72M.js";import{readFileSync as _,writeFileSync as j,mkdirSync as M,statSync as $}from"fs";import{homedir as C,tmpdir as L}from"os";import{join as p,resolve as f,dirname as A}from"path";var E=D({module:"permissions"}),T=[],z=["ls","pwd","echo","cat","head","tail","wc","date","whoami","uname","hostname","which","type","file","git status","git log","git diff","git branch","git show","git rev-parse","git remote","bun test","bun run","npm test","npm run","go test","go build","go vet","python -c","node -e"],O={Bash:"command",PowerShell:"command",ReadFile:"file_path",WriteFile:"file_path",EditFile:"file_path",Glob:"pattern",Grep:"pattern"},Y=[".swifty/config.yaml",".swifty/permissions.local.yaml",".swifty/skills/"];function w(i,e){if(i===k)return F(c(e,"server",""),c(e,"tool",""));let t=O[i];if(!t)return"";let s=e[t];return typeof s=="string"?s:""}var R=class{allowedRoots;denyWritePaths;projectDir;constructor(e){this.projectDir=f(e),this.allowedRoots=[this.projectDir,L()],this.denyWritePaths=Y.map(t=>p(this.projectDir,t))}addRoot(e){this.allowedRoots.push(f(e))}addDenyWrite(e){this.denyWritePaths.push(f(e))}checkDenyWrite(e){let t=f(e);for(let s of this.denyWritePaths)if(t.startsWith(s))return{effect:"deny",reason:`Path ${e} is in deny-write list`};return null}check(e){let t=f(e);for(let s of this.allowedRoots)if(t.startsWith(s))return null;return{effect:"deny",reason:`Path ${e} is outside allowed directories`}}};function B(i,e){let t="^"+i.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$";try{return new RegExp(t).test(e)}catch(s){return E.error({err:s},"permissions operation failed"),!1}}var G=/^(\w+)\((.+)\)$/;function S(i){let e;try{e=_(i,"utf-8")}catch(n){return n.code!=="ENOENT"&&E.error({err:n},"permissions operation failed"),[]}let t=d.object({rule:d.string().optional(),effect:d.string().optional()}),s;try{let n=y.load(e);s=v(d.array(t),n)}catch(n){return E.error({err:n},"permissions operation failed"),[]}let r=[];for(let n of s){if(n.effect!=="allow"&&n.effect!=="deny"&&n.effect!=="ask")continue;let o=G.exec((n.rule??"").trim());o&&r.push({tool:o[1],pattern:o[2],effect:n.effect})}return r}function b(i,e,t){let s=null;for(let r of i)if(!(r.tool!==e&&r.tool!=="*")&&B(r.pattern,t)){if(r.effect==="deny")return"deny";r.effect==="ask"?s="ask":s??="allow"}return s}var P=class{userPath;projectPath;localPath;cache=new Map;constructor(e){this.userPath=p(C(),".swifty","permissions.yaml"),this.projectPath=p(e,".swifty","permissions.yaml"),this.localPath=p(e,".swifty","permissions.local.yaml")}rulesFor(e){let t;try{t=$(e,{bigint:!0})}catch{return this.cache.delete(e),[]}let s=this.cache.get(e);if(s?.mtimeNs===t.mtimeNs&&s.size===t.size)return s.rules;let r=S(e);return this.cache.set(e,{mtimeNs:t.mtimeNs,size:t.size,rules:r}),r}snapshot(){return[this.userPath,this.projectPath,this.localPath].flatMap(e=>this.rulesFor(e))}evaluate(e,t){return b(this.snapshot(),e,t)}appendLocalRule(e){M(A(this.localPath),{recursive:!0});let t=S(this.localPath);if(t.some(n=>n.tool===e.tool&&n.pattern===e.pattern&&n.effect===e.effect))return;t.push(e);let r=t.map(n=>({rule:`${n.tool}(${n.pattern})`,effect:n.effect}));j(this.localPath,y.dump(r),"utf-8")}};function I(i){for(let e of T)if(e.re.test(i))return e.reason;return""}function N(i){let e=i.trim();return e.includes(">")||e.includes("|")||e.includes(";")||e.includes("&&")||e.includes("$(")||e.includes("`")?!1:z.some(t=>e===t||e.startsWith(t+" ")||e.startsWith(t+" "))}function U(i,e){switch(i){case"bypassPermissions":return"allow";case"plan":return e==="read"?"allow":"ask";case"acceptEdits":return e==="command"?"ask":"allow";default:return e==="read"?"allow":"ask"}}var W=class{mode;planFilePath="";sandboxEnabled=!1;sandboxAutoAllow=!1;sandbox;ruleEngine;constructor(e,t="default"){this.mode=t,this.sandbox=new R(e),this.ruleEngine=new P(e)}check(e,t,s){let r=w(e,s),n=null,o=()=>n??=this.ruleEngine.snapshot();if(this.mode==="plan"&&(e==="WriteFile"||e==="EditFile")&&c(s,"file_path","").includes(".swifty/plans/"))return{effect:"allow",reason:"Plan file write allowed in plan mode"};if(t==="command"&&N(r))return{effect:"allow",reason:"Safe read-only command"};let a=t==="command"?I(r):"";if(a)return{effect:"deny",reason:`Dangerous command blocked: ${a}`};if(this.sandboxEnabled&&this.sandboxAutoAllow&&e==="Bash"){let u=c(s,"command").split(/\s*(?:&&|\|\||[;|])\s*/).map(g=>g.trim()).filter(Boolean),l=!1;for(let g of u){let x=b(o(),e,g);if(x==="deny")return{effect:"deny",reason:"Permission rule: deny"};x==="ask"&&(l=!0)}return l?{effect:"ask",reason:"Permission rule: ask (sandbox does not override)"}:{effect:"allow",reason:"Sandbox auto-allow: OS sandbox active"}}let h=c(s,"file_path",c(s,"path",""));if((t==="read"||t==="write")&&h){if(t==="write"){let l=this.sandbox.checkDenyWrite(h);if(l)return l}let u=this.sandbox.check(h);if(u&&this.mode!=="bypassPermissions"){let l=this.ruleEngine.evaluate(e,r);return l?{effect:l,reason:`Permission rule: ${l}`}:{effect:"ask",reason:u.reason}}}let m=b(o(),e,r);return m?{effect:m,reason:`Permission rule: ${m}`}:{effect:U(this.mode,t),reason:`Mode: ${this.mode}`}}allowExtraRoot(e){this.sandbox.addRoot(e)}allowAlways(e,t){let s=w(e,t),r=e==="ReadFile"||e==="WriteFile"||e==="EditFile",n;if(r&&s){let o=f(s),a=!1;try{a=$(o).isDirectory()}catch{}n=p(a?o:A(o),"*")}else n=s.trim().split(/\s+/).slice(0,2).join(" ")+"*";this.ruleEngine.appendLocalRule({tool:e,pattern:n,effect:"allow"})}describeToolAction(e,t){let s=w(e,t);if(s)return s;let r=[];for(let[n,o]of Object.entries(t)){let a=String(o);a.length>80&&(a=a.slice(0,80)+"..."),r.push(`${n}: ${a}`)}return r.join(", ")}};export{w as a,R as b,b as c,P as d,N as e,W as f};
|
|
@@ -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{I as y,L as u,N as T,R as f}from"./chunk-SIWLMWHH.js";import{b as g}from"./chunk-E55KH72M.js";var S=y({module:"mcp"}),p="mcp__",m="__";function a(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function _(e){return p+a(e)+m}function h(e,r){return _(e)+a(r)}var C=class{name;description;category="command";deferred=!0;mcpServerName;client;originalName;inputSchema;constructor(r,t,n){this.name=h(t,n.name),this.description=n.description,this.originalName=n.name,this.client=r,this.inputSchema=n.inputSchema,this.mcpServerName=t}mcpInputSchema(){return this.inputSchema??{}}setDeferLoading(r){this.deferred=r}schema(){return{name:this.name,description:this.description,input_schema:this.inputSchema}}async execute(r,t){try{return await this.client.callTool(this.originalName,t)}catch(n){return S.error({err:n},"mcp operation failed"),{output:`MCP tool error: ${T(n)}`,isError:!0}}}};function x(e,r){if(r==="string"&&typeof e=="number"&&Number.isFinite(e))return String(e);if((r==="integer"||r==="number")&&typeof e=="string"){let t=e.trim();if(t===""||!(r==="integer"?/^[+-]?\d+$/:/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/).test(t))return e;let s=r==="integer"?Number.parseInt(t,10):Number.parseFloat(t);return Number.isNaN(s)?e:s}if(r==="boolean"&&typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}return e}function d(e,r){if(typeof r!="object"||r===null)return e;let t=u(r),n=f(t,"type","");if(n==="object"&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let s=u(t.properties??{}),o={};for(let[i,c]of Object.entries(e))o[i]=i in s?d(c,s[i]):c;return o}if(n==="array"){let s=t.items??{},o=e;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.values(o);i.length===1&&Array.isArray(i[0])&&(o=i[0])}else typeof o=="string"&&(o=o.split(",").map(i=>i.trim()).filter(i=>i!==""));return Array.isArray(o)?o.map(i=>d(i,s)):o}return n!==""?x(e,n):e}function O(e,r){if(r.startsWith(p)){let t=r.slice(p.length),n=t.indexOf(m);if(n>=0)return a(t.slice(0,n))+m+a(t.slice(n+m.length))}return a(e)+m+a(r)}function M(e){return"mcpInputSchema"in e&&typeof e.mcpInputSchema=="function"}var b=class{constructor(r){this.registry=r}registry;name=g;description="Invoke a tool on a connected MCP server. Call ToolSearch first to load the tool's schema, then pass its arguments here exactly as that schema requires, using the same JSON types.";category="command";deferred=!1;schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{server:{type:"string",description:"MCP server name, e.g. 'linear'."},tool:{type:"string",description:"Full tool name as returned by ToolSearch, e.g. 'mcp__linear__create_issue'."},arguments:{type:"object",description:"The target tool's arguments. Must match that tool's input_schema exactly, including JSON types: bare numbers for integer fields, bare true/false for boolean fields, quoted strings for string fields, and plain JSON arrays for array fields."}},required:["server","tool","arguments"]}}}resolve(r,t){let n=this.registry.get(t)??this.registry.get(h(r,t));if(n)return n;let s=m+a(t),o=this.registry.listTools().filter(i=>i.name.startsWith(p)&&i.name.endsWith(s));return o.length===1?o[0]:void 0}availableNames(){return this.registry.listTools().filter(r=>r.name.startsWith(p)).map(r=>r.name).sort()}async execute(r,t){let n=f(t,"server",""),s=f(t,"tool","");if(s==="")return{output:"McpCall requires a 'tool' name",isError:!0};let o=this.resolve(n,s);if(!o){let c=this.availableNames(),l=c.length>0?c.join(", "):"(none connected)";return{output:`Unknown MCP tool '${s}' on server '${n}'. Available tools: ${l}`,isError:!0}}let i={};if(typeof t.arguments=="object"&&t.arguments!==null&&!Array.isArray(t.arguments)&&(i=u(t.arguments)),M(o)){let c=o.mcpInputSchema();if(Object.keys(c).length>0){let l=d(i,c);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(i=u(l))}}return o.execute(r,i)}};export{p as a,C as b,O as c,M as d,b as e};
|