@swifty.js/swifty 0.0.2 → 0.0.3

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{a as w}from"./chunk-7MHXMDYC.js";import{I as u,R as d,e as k,j as D}from"./chunk-4KVSJNS6.js";import{readFileSync as $,writeFileSync as j,mkdirSync as A,statSync as S}from"fs";import{join as h,resolve as l,dirname as W}from"path";import{homedir as _,tmpdir as M}from"os";var E=k({module:"permissions"}),T=[{re:/rm\s+(-rf?|--recursive)\s+[/~]/,reason:"recursive force delete root"},{re:/rm\s+-rf?\s+\*/,reason:"recursive force delete wildcard"},{re:/mkfs\./,reason:"format disk"},{re:/dd\s+if=/,reason:"direct write to disk device"},{re:/>\s*\/dev\/sd/,reason:"overwrite disk device"},{re:/chmod\s+-R?\s*777\s+\//,reason:"recursive chmod root"},{re:/:\(\)\{\s*:\|\s*:\s*&\s*\}\s*;/,reason:"fork bomb"},{re:/curl\s+.*\|\s*(ba)?sh/,reason:"pipe remote script"},{re:/wget\s+.*\|\s*(ba)?sh/,reason:"pipe remote script"},{re:/git\s+push\s+.*--force/,reason:"force push"},{re:/git\s+reset\s+--hard/,reason:"hard reset"},{re:/git\s+clean\s+-f/,reason:"force clean untracked files"},{re:/git\s+checkout\s+\./,reason:"discard all changes"},{re:/git\s+branch\s+-D/,reason:"force delete branch"}],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"],L={Bash:"command",ReadFile:"file_path",WriteFile:"file_path",EditFile:"file_path",Glob:"pattern",Grep:"pattern"},C=[".swifty/config.yaml",".swifty/permissions.local.yaml",".swifty/skills/"];function y(i,e){let t=L[i];if(!t)return"";let s=e[t];return typeof s=="string"?s:""}var R=class{allowedRoots;denyWritePaths;projectDir;constructor(e){this.projectDir=l(e),this.allowedRoots=[this.projectDir,M()],this.denyWritePaths=C.map(t=>h(this.projectDir,t))}addRoot(e){this.allowedRoots.push(l(e))}addDenyWrite(e){this.denyWritePaths.push(l(e))}checkDenyWrite(e){let t=l(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=l(e);for(let s of this.allowedRoots)if(t.startsWith(s))return null;return{effect:"deny",reason:`Path ${e} is outside allowed directories`}}};function O(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 Y=/^(\w+)\((.+)\)$/;function x(i){let e;try{e=$(i,"utf-8")}catch(r){return r.code!=="ENOENT"&&E.error({err:r},"permissions operation failed"),[]}let t=u.object({rule:u.string().optional(),effect:u.string().optional()}),s;try{let r=w.load(e);s=D(u.array(t),r)}catch(r){return E.error({err:r},"permissions operation failed"),[]}let n=[];for(let r of s){if(r.effect!=="allow"&&r.effect!=="deny"&&r.effect!=="ask")continue;let o=Y.exec((r.rule??"").trim());o&&n.push({tool:o[1],pattern:o[2],effect:r.effect})}return n}function b(i,e,t){let s=null;for(let n of i)if(!(n.tool!==e&&n.tool!=="*")&&O(n.pattern,t)){if(n.effect==="deny")return"deny";n.effect==="ask"?s="ask":s??="allow"}return s}var v=class{userPath;projectPath;localPath;cache=new Map;constructor(e){this.userPath=h(_(),".swifty","permissions.yaml"),this.projectPath=h(e,".swifty","permissions.yaml"),this.localPath=h(e,".swifty","permissions.local.yaml")}rulesFor(e){let t;try{t=S(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 n=x(e);return this.cache.set(e,{mtimeNs:t.mtimeNs,size:t.size,rules:n}),n}snapshot(){return[this.userPath,this.projectPath,this.localPath].flatMap(e=>this.rulesFor(e))}evaluate(e,t){return b(this.snapshot(),e,t)}appendLocalRule(e){A(W(this.localPath),{recursive:!0});let t=x(this.localPath);if(t.some(r=>r.tool===e.tool&&r.pattern===e.pattern&&r.effect===e.effect))return;t.push(e);let n=t.map(r=>({rule:`${r.tool}(${r.pattern})`,effect:r.effect}));j(this.localPath,w.dump(n),"utf-8")}};function N(i){for(let e of T)if(e.re.test(i))return e.reason;return""}function G(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 I(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 F=class{mode;planFilePath="";sandboxEnabled=!1;sandboxAutoAllow=!1;sandbox;ruleEngine;constructor(e,t="default"){this.mode=t,this.sandbox=new R(e),this.ruleEngine=new v(e)}check(e,t,s){let n=y(e,s),r=null,o=()=>r??=this.ruleEngine.snapshot();if(this.mode==="plan"&&(e==="WriteFile"||e==="EditFile")&&d(s,"file_path","").includes(".swifty/plans/"))return{effect:"allow",reason:"Plan file write allowed in plan mode"};if(t==="command"&&G(n))return{effect:"allow",reason:"Safe read-only command"};let a=t==="command"?N(n):"";if(a)return{effect:"deny",reason:`Dangerous command blocked: ${a}`};if(this.sandboxEnabled&&this.sandboxAutoAllow&&t==="command"){let f=d(s,"command").split(/\s*(?:&&|\|\||[;|])\s*/).map(g=>g.trim()).filter(Boolean),c=!1;for(let g of f){let P=b(o(),e,g);if(P==="deny")return{effect:"deny",reason:"Permission rule: deny"};P==="ask"&&(c=!0)}return c?{effect:"ask",reason:"Permission rule: ask (sandbox does not override)"}:{effect:"allow",reason:"Sandbox auto-allow: OS sandbox active"}}let p=d(s,"file_path",d(s,"path",""));if((t==="read"||t==="write")&&p){if(t==="write"){let c=this.sandbox.checkDenyWrite(p);if(c)return c}let f=this.sandbox.check(p);if(f&&this.mode!=="bypassPermissions"){let c=this.ruleEngine.evaluate(e,n);return c?{effect:c,reason:`Permission rule: ${c}`}:{effect:"ask",reason:f.reason}}}let m=b(o(),e,n);return m?{effect:m,reason:`Permission rule: ${m}`}:{effect:I(this.mode,t),reason:`Mode: ${this.mode}`}}allowExtraRoot(e){this.sandbox.addRoot(e)}allowAlways(e,t){let s=y(e,t),n=e==="ReadFile"||e==="WriteFile"||e==="EditFile",r;if(n&&s){let o=l(s),a=!1;try{a=S(o).isDirectory()}catch{}r=h(a?o:W(o),"*")}else r=s.trim().split(/\s+/).slice(0,2).join(" ")+"*";this.ruleEngine.appendLocalRule({tool:e,pattern:r,effect:"allow"})}describeToolAction(e,t){let s=y(e,t);if(s)return s;let n=[];for(let[r,o]of Object.entries(t)){let a=String(o);a.length>80&&(a=a.slice(0,80)+"..."),n.push(`${r}: ${a}`)}return n.join(", ")}};export{y as a,R as b,b as c,v as d,F as e};
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{I as i,N as U,e as y,j as M,k as A}from"./chunk-4KVSJNS6.js";var T=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(e,s){this.history.push({role:"user",content:e,...s?.length?{images:s}:{}})}addAssistantMessage(e){this.history.push({role:"assistant",content:e})}addToolUseMessage(e,s,o,n){this.history.push({role:"assistant",content:e,toolUses:[{toolUseId:s,toolName:o,arguments:n}]})}addAssistantMessageWithTools(e,s){this.history.push({role:"assistant",content:e,toolUses:s})}addAssistantFull(e,s,o){this.history.push({role:"assistant",content:e,thinkingBlocks:s.length>0?s:void 0,toolUses:o.length>0?o:void 0})}addToolResultMessage(e,s,o){this.history.push({role:"user",content:"",toolResults:[{toolUseId:e,content:s,isError:o}]})}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,s){if(this.longTermMemoryInjected)return;let o=[];if(e&&o.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),s&&o.push(`# Auto Memory
10
+ `+s),o.length===0)return;let n=new Date().toISOString().split("T")[0];o.push(`# Current Date
11
+ Today's date is `+n+".");let a=`
12
+ <system-reminder>
13
+ As you answer the user's questions, you can use the following context:
14
+
15
+ ${o.join(`
16
+
17
+ `)}
18
+
19
+ 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.
20
+ </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,s){this.history=[{role:"user",content:e},...s],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,s,o,n){let r=e+o+n+s;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{createHash as Z}from"crypto";import{existsSync as ee,mkdirSync as te,readFileSync as se,writeFileSync as oe}from"fs";import{join as E}from"path";function P(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var j=y({module:"images"}),ne={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"};function re(t,e){return E(t,".swifty","sessions",e||"default","images")}function b(t,e,s){let o=re(t,e),n=[];for(let r of s)try{let a=Buffer.from(r.data,"base64"),l=Z("sha256").update(a).digest("hex").slice(0,16),c=ne[r.mediaType]??"png",u=E(o,`${l}.${c}`);ee(u)||(te(o,{recursive:!0}),oe(u,a)),n.push({path:u,media_type:r.mediaType,...r.sourcePath?{source_path:r.sourcePath}:{}})}catch(a){j.error({err:a},"failed to persist session image")}return n}function N(t){try{let e=se(t.path);return{mediaType:P(t.media_type),data:e.toString("base64"),sourcePath:t.source_path,byteLength:e.length}}catch(e){return j.warn({err:e,path:t.path},"failed to restore session image"),null}}import{readFileSync as L,writeFileSync as ie,readdirSync as ae,mkdirSync as le,statSync as ce,existsSync as O,unlinkSync as ze,rmSync as Ke}from"fs";import{basename as k,dirname as I,join as f}from"path";import{randomBytes as ue}from"crypto";var x="compact_boundary";var D=i.object({tool_use_id:i.string(),tool_name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),w=i.object({path:i.string(),media_type:i.string(),source_path:i.string().optional()}),F=i.object({tool_use_id:i.string(),content:i.string(),is_error:i.boolean().optional(),images:i.array(w).optional()}),$=i.object({role:i.string(),content:i.string().default(""),timestamp:i.number(),type:i.string().optional(),tool_uses:i.array(D).optional(),tool_results:i.array(F).optional(),images:i.array(w).optional()}),me=i.object({role:i.string(),content:i.string(),tool_uses:i.array(D).optional(),tool_results:i.array(F).optional(),images:i.array(w).optional()});function Y(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 q(t,e){return(t??[]).map(s=>({tool_use_id:s.toolUseId,content:s.content,...s.isError?{is_error:!0}:{},...e&&s.images?.length?{images:b(e.workDir,e.sessionId,s.images)}:{}}))}function _(t){if(!t?.length)return{images:[],note:""};let e=[];for(let o of t){let n=N(o);n&&e.push(n)}let s=t.length-e.length;return{images:e,note:s>0?`
21
+ [note: ${String(s)} image(s) from this message could not be restored]`:""}}var ge=i.object({summary:i.string(),keep:i.array(me)}),R=y({module:"session"});function S(t){return f(t,".swifty","sessions")}function Ve(t,e){return f(S(t),e+".jsonl")}function z(t){let e=k(t);if(!e.endsWith(".jsonl"))return null;let s=I(t),o=I(s);return k(s)!=="sessions"||k(o)!==".swifty"?null:{workDir:I(o),sessionId:e.slice(0,-6)}}function Qe(){let t=Date.now().toString(36),e=ue(4).toString("hex");return`${t}-${e}`}function de(t,e,s){let o=S(t);le(o,{recursive:!0});let n=f(o,`${e}.jsonl`),r=JSON.stringify(s)+`
22
+ `;ie(n,r,{flag:"a",encoding:"utf-8"})}function Ze(t,e,s){de(t,e,{role:"system",content:JSON.stringify(s),timestamp:Math.floor(Date.now()/1e3),type:x})}function et(t,e){let s=f(S(t),`${e}.jsonl`);if(!O(s))return[];let o=[];for(let n of L(s,"utf-8").split(`
23
+ `))if(n.trim())try{let r=JSON.parse(n),{success:a,data:l,error:c}=A($,r);a?!l.content&&!(l.tool_uses?.length??0)&&!(l.tool_results?.length??0)&&!(l.images?.length??0)||o.push(l):R.error({err:c},"session operation failed")}catch(r){R.error({err:r},"session operation failed")}return o}function K(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function H(t){return t?.map(e=>{let s=_(e.images);return{toolUseId:e.tool_use_id,content:e.content+s.note,isError:e.is_error,...s.images.length?{images:s.images}:{}}})}function tt(t){let e=-1;for(let o=t.length-1;o>=0;o--)if(t[o].type===x){e=o;break}let s=[];if(e>=0){let o=null;try{let n=JSON.parse(t[e].content);o=M(ge,n)}catch{o=null}if(o){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
+ `+o.summary;o.keep.length>0&&(n+=`
26
+
27
+ Recent messages have been preserved verbatim.`),s.push({role:"user",content:n});for(let r of o.keep){if(r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)&&!(r.images?.length??0))continue;let a=_(r.images);s.push({role:r.role,content:r.content+a.note,toolUses:K(r.tool_uses),toolResults:H(r.tool_results),...a.images.length?{images:a.images}:{}})}}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===x)continue;let a=B(r);a&&s.push(a)}return s}for(let o of t){let n=B(o);n&&s.push(n)}return s}function B(t){if(t.role!=="user"&&t.role!=="assistant"||!t.content&&!(t.tool_uses?.length??0)&&!(t.tool_results?.length??0)&&!(t.images?.length??0))return null;let e=_(t.images);return{role:t.role,content:t.content+e.note,toolUses:K(t.tool_uses),toolResults:H(t.tool_results),...e.images.length?{images:e.images}:{}}}function st(t){let e=S(t);if(!O(e))return[];let s=ae(e).filter(n=>n.endsWith(".jsonl")),o=[];for(let n of s){let r=f(e,n),a=ce(r),l=n.replace(".jsonl",""),c="",u=0;try{for(let g of L(r,"utf-8").split(`
28
+ `)){if(!g.trim())continue;let d;try{let h=JSON.parse(g);d=M($,h)}catch(h){R.error({err:h},"session operation failed");continue}u++,!c&&d.role==="user"&&d.content&&(c=d.content.slice(0,100))}}catch(g){R.error({err:g},"session operation failed");continue}o.push({id:l,firstMessage:c,messageCount:u,size:a.size,modTime:a.mtime})}return o.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),o}var W=3,he=3,pe="[earlier conversation truncated for compaction retry]",fe=3.5,ye=1e4,Te=5,be=4e4,Re=2,Se=2e4,Me=13e3,ke=3e3;function J(t,e,s=!1){return t-Math.min(e,Se)-(s?ke:Me)}var X=class{consecutiveFailures=0},G=7e3;function C(t){let e=0;for(let s of t){if(e+=s.content.length,s.images&&(e+=s.images.length*G),s.toolUses&&(e+=JSON.stringify(s.toolUses).length),s.toolResults)for(let o of s.toolResults)e+=o.content.length,e+=(o.images?.length??0)*G;if(s.thinkingBlocks)for(let o of s.thinkingBlocks)e+=o.thinking.length}return Math.ceil(e/fe)}function Ie(t){return C(t.getMessages())}function v(t){return C([t])}function xe(t){return t.role==="user"&&!!t.toolResults&&t.toolResults.length>0}function we(t){let e=0,s=0,o=t.length;for(let n=t.length-1;n>=0;n--){let r=v(t[n]);if(s>0&&e+r>be||(o=n,e+=r,s++,e>=ye||s>=Te))break}return o=_e(t,o),o}function _e(t,e){if(e<=0||e>=t.length||!xe(t[e]))return e;let s=new Set((t[e].toolResults??[]).map(o=>o.toolUseId));for(let o=e-1;o>=0;o--){let n=t[o];if(n.role==="assistant"&&n.toolUses?.some(r=>s.has(r.toolUseId)))return o}return e}function Ce(t,e){let s=e??t.usageAnchorState();if(!s)return Ie(t);let o=t.getMessages(),n=Math.min(s.anchorCount,o.length);return s.baselineTokens+C(o.slice(n))}async function lt(t,e,s,o,n,r,a,l,c=""){let u=Ce(t),g=J(s,o),d=J(s,o,!0);if(u<g)return{compacted:!1,message:""};if(!(u>=d)&&n.consecutiveFailures>=W)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(W)} consecutive failures`};try{let p=await V(t,e,r,a,l,c);return n.consecutiveFailures=0,p}catch(p){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${U(p)}`}}}async function ct(t,e,s,o,n,r=""){return V(t,e,s,o,n,r)}var ve=`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 Ae(t){return ve+`
112
+
113
+ `+t}function Ue(t){let e=[],s=[],o=!1;for(let n of t)n.role==="assistant"&&o&&s.length>0&&(e.push(s),s=[]),s.push(n),o=!!(n.toolResults&&n.toolResults.length>0);return s.length>0&&e.push(s),e}function Pe(t,e){let s=Ue(t);if(s.length<2)return null;let o;if(e>0){let r=0;o=0;for(let a of s)if(r+=a.reduce((l,c)=>l+v(c),0),o++,r>=e)break}else o=Math.max(1,Math.floor(s.length/5));if(o=Math.min(o,s.length-1),o<1)return null;let n=s.slice(o).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:pe}),n}function Ee(t){return t.map(e=>{let s=`[${e.role}]: ${e.content}`;return e.images?.length&&(s+=`
114
+ [attached images: ${e.images.map(o=>o.sourcePath??"image").join(", ")}]`),e.toolUses&&(s+=`
115
+ [tools: ${e.toolUses.map(o=>o.toolName).join(", ")}]`),s}).join(`
116
+
117
+ `)}async function je(t,e,s){let o=e;for(let n=0;;n++){let r=Ee(o),a=new T;a.addUserMessage(Ae(r));try{let l="",c=t.stream(a,s);for await(let g of c)g.type==="text_delta"&&(l+=g.text);let u=/<summary>([\s\S]*?)<\/summary>/.exec(l);return u?u[1].trim():l}catch(l){let c=l instanceof Error?l.message.toLowerCase():"";if(!(c.includes("prompt")&&c.includes("long")||c.includes("too many")||c.includes("context_length"))||n>=he)throw l;let g=o.reduce((h,p)=>h+v(p),0)/5,d=Pe(o,g);if(!d)throw l;o=d}}}async function V(t,e,s,o,n,r=""){let a=t.getMessages(),l=we(a);if(l<=0||l<Re)return{compacted:!1,message:`Compaction skipped: only ${String(l)} message(s) to summarize, kept verbatim`};let c=a.slice(0,l),u=a.slice(l),g=await je(e,c,n),d=s?s.buildRecoveryAttachment(o):"",h=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
118
+
119
+ `+g;u.length>0&&(h+=`
120
+
121
+ Recent messages have been preserved verbatim.`),r&&(h+=`
122
+
123
+ If you need specific details from before compaction (code snippets, error messages, etc.), use ReadFile to read the full session transcript: ${r}`),d&&(h+=`
124
+
125
+ ---
126
+
127
+ ${d}`),t.replaceWithCompacted(h,u);let p=r?z(r):null,Q=u.filter(m=>(m.role==="user"||m.role==="assistant")&&(m.content||(m.toolUses?.length??0)||(m.toolResults?.length??0)||(m.images?.length??0))).map(m=>({role:m.role,content:m.images?.length&&!p?m.content+`
128
+ [note: ${String(m.images.length)} image(s) omitted from compaction]`:m.content,...m.toolUses?.length?{tool_uses:Y(m.toolUses)}:{},...m.toolResults?.length?{tool_results:q(m.toolResults,p??void 0)}:{},...p&&m.images?.length?{images:b(p.workDir,p.sessionId,m.images)}:{}}));return{compacted:!0,message:`Compacted ${String(c.length)} messages into summary (${String(g.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:g,keep:Q}}}export{T as a,b,Y as c,q as d,Ve as e,Qe as f,de as g,Ze as h,et as i,tt as j,st as k,J as l,X as m,lt as n,ct 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
- var l=class{tools=new Map;discovered=new Set;register(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}listTools(){return[...this.tools.values()]}getAllSchemas(e="anthropic"){let o=[];for(let t of this.tools.values()){if(t.deferred&&!this.discovered.has(t.name))continue;let s=t.schema();e==="anthropic"?o.push({name:s.name,description:s.description,input_schema:{type:"object",properties:s.input_schema.properties,required:s.input_schema.required??[]}}):o.push({strict:!1,type:"function",name:s.name,description:s.description,parameters:s.input_schema})}return o}getDeferredToolNames(){let e=[];for(let o of this.tools.values())o.deferred&&!this.discovered.has(o.name)&&e.push(o.name);return e}getDeferredTools(){return[...this.tools.values()].filter(e=>e.deferred&&!this.discovered.has(e.name))}searchDeferred(e,o=5){let t=e.toLowerCase(),s=[];for(let r of this.tools.values())if(!(!r.deferred||this.discovered.has(r.name))&&(r.name.toLowerCase().includes(t)||r.description.toLowerCase().includes(t))&&(s.push(r),s.length>=o))break;return s}findDeferredByNames(e){let o=new Map;for(let[t,s]of this.tools)o.set(t.toLowerCase(),s);return e.map(t=>o.get(t.toLowerCase())).filter(t=>t?.deferred??!1)}markDiscovered(e){this.discovered.add(e)}isDiscovered(e){return this.discovered.has(e)}};var f=new Set(["TaskOutput","ExitPlanMode","EnterPlanMode","Agent","AskUserQuestion","TaskStop","Workflow"]),u=new Set(["TaskOutput","ExitPlanMode","EnterPlanMode","Agent","AskUserQuestion","TaskStop","Workflow"]),h=new Set(["ReadFile","WebSearch","TodoWrite","Grep","WebFetch","Glob","Bash","EditFile","WriteFile","NotebookEdit","Skill","LoadSkill","SyntheticOutput","ToolSearch","EnterWorktree","ExitWorktree"]);function T(n){return n.startsWith("mcp__")}function S(n,e,o,t,s=!1){let r=new Set(o??[]),a=new Set(e??[]),d=a.size>0&&!(a.size===1&&a.has("*")),c=new l;for(let p of n.listTools()){let i=p.name;if(T(i)){c.register(p);continue}f.has(i)||s&&u.has(i)||t&&!h.has(i)||r.has(i)||d&&!a.has(i)||c.register(p)}return c}var m="agent:builtin:fork";function O(n){let e=new l;for(let o of n.listTools())if(o.name==="Agent"&&"querySource"in o){let t=Object.create(Object.getPrototypeOf(o),Object.getOwnPropertyDescriptors(o));t.querySource=m,e.register(t)}else e.register(o);return e}export{l as a,f as b,u as c,h as d,S as e,m as f,O as g};
4
+ var l=class{tools=new Map;discovered=new Set;register(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}listTools(){return[...this.tools.values()]}getAllSchemas(e="anthropic"){let o=[];for(let t of this.tools.values()){if(t.deferred&&!this.discovered.has(t.name))continue;let s=t.schema();e==="anthropic"?o.push({name:s.name,description:s.description,input_schema:{type:"object",properties:s.input_schema.properties,required:s.input_schema.required??[]}}):o.push({strict:!1,type:"function",name:s.name,description:s.description,parameters:s.input_schema})}return o}getDeferredToolNames(){let e=[];for(let o of this.tools.values())o.deferred&&!this.discovered.has(o.name)&&e.push(o.name);return e}getDeferredTools(){return[...this.tools.values()].filter(e=>e.deferred&&!this.discovered.has(e.name))}searchDeferred(e,o=5){let t=e.toLowerCase(),s=[];for(let r of this.tools.values())if(!(!r.deferred||this.discovered.has(r.name))&&(r.name.toLowerCase().includes(t)||r.description.toLowerCase().includes(t))&&(s.push(r),s.length>=o))break;return s}findDeferredByNames(e){let o=new Map;for(let[t,s]of this.tools)o.set(t.toLowerCase(),s);return e.map(t=>o.get(t.toLowerCase())).filter(t=>t?.deferred??!1)}markDiscovered(e){this.discovered.add(e)}isDiscovered(e){return this.discovered.has(e)}};var f=new Set(["TaskOutput","ExitPlanMode","EnterPlanMode","Agent","AskUserQuestion","TaskStop","Workflow"]),S=new Set(["TeamCreate","TeamDelete"]),u=new Set(["TaskOutput","ExitPlanMode","EnterPlanMode","Agent","AskUserQuestion","TaskStop","Workflow"]),h=new Set(["ReadFile","WebSearch","TodoWrite","Grep","WebFetch","Glob","Bash","EditFile","WriteFile","NotebookEdit","Skill","LoadSkill","SyntheticOutput","ToolSearch","EnterWorktree","ExitWorktree"]);function T(n){return n.startsWith("mcp__")}function O(n,e,o,t,s=!1){let r=new Set(o??[]),a=new Set(e??[]),d=a.size>0&&!(a.size===1&&a.has("*")),c=new l;for(let p of n.listTools()){let i=p.name;if(T(i)){c.register(p);continue}f.has(i)||s&&u.has(i)||t&&!h.has(i)||r.has(i)||d&&!a.has(i)||c.register(p)}return c}var m="agent:builtin:fork";function w(n){let e=new l;for(let o of n.listTools())if(o.name==="Agent"&&"querySource"in o){let t=Object.create(Object.getPrototypeOf(o),Object.getOwnPropertyDescriptors(o));t.querySource=m,e.register(t)}else e.register(o);return e}export{l as a,f as b,S as c,u as d,h as e,O as f,m as g,w as h};
@@ -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{a as S}from"./chunk-7MHXMDYC.js";import{H as o,e as x,g as u,h as m}from"./chunk-4KVSJNS6.js";import{existsSync as E,readFileSync as I}from"fs";import{homedir as N}from"os";import{join as d}from"path";function p(e){return!!e._zod}function f(e,n){return p(e)?u(e,n):e.safeParse(n)}async function ee(e,n){return p(e)?await m(e,n):await e.safeParseAsync(n)}function oe(e){if(!e)return;let n;if(p(e)?n=e._zod?.def?.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function ne(e){if(p(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(r!==void 0)return r}var g=x({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function V(e){return _.has(e)}var _=new Set(Object.keys(A)),l=class extends Error{constructor(n){super(n),this.name="ConfigError"}},P=o.object({name:o.string(),protocol:o.enum(["anthropic","openai","openai-compat"]),base_url:o.string(),model:o.string(),api_key:o.string().optional(),thinking:o.boolean().optional(),context_window:o.coerce.number().optional(),max_output_tokens:o.coerce.number().optional()}),T=[["1m",1e6],["gpt-4.1",1e6],["gpt-4o",128e3],["gpt-4-turbo",128e3],["o1",2e5],["o3",2e5],["o4",2e5],["gpt-3.5",16385],["claude",2e5]];function j(e){let n=e.toLowerCase();for(let[t,r]of T)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function le(e){return e.context_window&&e.context_window>0?e.context_window:j(e.model)}var w=new Map;async function pe(e,n){if(e.context_window&&e.context_window>0)return e.context_window;if(e.protocol==="anthropic"){let t=`${e.name}-${e.model}`,r=w.get(t);if(r===void 0){try{r=await(n??(await import("./anthropic-JDAGNAPR.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(t,r)}if(r&&r>0)return r}return j(e.model)}function ue(e){return e.max_output_tokens&&e.max_output_tokens>0?e.max_output_tokens:e.thinking?64e3:8192}function me(e){if(e.api_key)return e.api_key;let n=V(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var z=o.object({name:o.string(),command:o.string().optional(),args:o.array(o.string()).optional(),url:o.string().optional(),transport:o.string().optional(),headers:o.record(o.string(),o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),O=o.object({id:o.string().optional(),event:o.string(),condition:o.string().optional(),action:o.object({type:o.string(),command:o.string().optional(),url:o.string().optional(),method:o.string().optional(),prompt:o.string().optional()}),reject:o.boolean().optional(),once:o.boolean().optional(),async:o.boolean().optional(),on_error:o.string().optional()}),M=o.object({enabled:o.boolean().optional(),auto_allow:o.boolean().optional(),network_enabled:o.boolean().optional()}),Y=o.object({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(z).default([]),hooks:o.array(O).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function K(e){return typeof e=="object"&&e!==null}function C(e){let n=I(e,"utf-8"),t=S.load(n);if(!K(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=f(Y,t);if(r.success){let a=r.data;return{providers:a.providers,permission_mode:a.permission_mode,mcp_servers:a.mcp_servers,hooks:a.hooks}}g.error({error:r.error},"config error");let i=[],s,c=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=f(o.array(P),t.providers);a.success&&(i=a.data)}if("permission_mode"in t&&typeof t.permission_mode=="string"&&(s=t.permission_mode),"mcp_servers"in t){let a=f(o.array(z),t.mcp_servers);a.success&&(c=a.data)}if("hooks"in t){let a=f(o.array(O),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=f(M,t.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in t&&(b=!!t.enable_coordinator_mode),"enable_fork"in t&&(h=!!t.enable_fork),{providers:i,permission_mode:s,mcp_servers:c,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function W(e,n){if(n.providers.length>0&&(e.providers=n.providers),n.permission_mode&&(e.permission_mode=n.permission_mode),n.mcp_servers.length>0){let t=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];t.set(i.name,r)}for(let r of n.mcp_servers){let i=t.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),t.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...n.hooks],n.sandbox&&(e.sandbox={...e.sandbox,...n.sandbox}),n.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),n.enable_fork!==void 0&&(e.enable_fork=n.enable_fork),e}function k(e){if(e.providers.length===0)throw new l("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"];for(let t=0;t<e.providers.length;t++){let r=e.providers[t],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=n.filter(c=>!(c in i));if(s.length>0)throw new l(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new l(`Provider #${String(t+1)}: invalid protocol '${r.protocol}', MUST be one of: ${Array.from(_).join(", ")}`)}}function _e(e){if(e){let s=C(e);return k(s),s}let n=process.cwd(),t=N(),r=[d(t,".swifty","config.yml"),d(t,".swifty","config.yaml"),d(n,".swifty","config.yml"),d(n,".swifty","config.yaml"),d(n,".swifty","config.local.yml"),d(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let c=C(s);i?i=W(i,c):i=c}if(!i)throw new l("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{p as a,f as b,ee as c,oe as d,ne as e,le as f,pe as g,ue as h,me as i,ge as j,_e as k};
4
+ import{a as S}from"./chunk-7MHXMDYC.js";import{H as o,e as x,g as u,h as m}from"./chunk-4KVSJNS6.js";import{existsSync as E,readFileSync as I}from"fs";import{homedir as N}from"os";import{join as d}from"path";function p(e){return!!e._zod}function f(e,n){return p(e)?u(e,n):e.safeParse(n)}async function ee(e,n){return p(e)?await m(e,n):await e.safeParseAsync(n)}function oe(e){if(!e)return;let n;if(p(e)?n=e._zod?.def?.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function ne(e){if(p(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(r!==void 0)return r}var g=x({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function V(e){return _.has(e)}var _=new Set(Object.keys(A)),l=class extends Error{constructor(n){super(n),this.name="ConfigError"}},P=o.object({name:o.string(),protocol:o.enum(["anthropic","openai","openai-compat"]),base_url:o.string(),model:o.string(),api_key:o.string().optional(),thinking:o.boolean().optional(),context_window:o.coerce.number().optional(),max_output_tokens:o.coerce.number().optional()}),T=[["1m",1e6],["gpt-4.1",1e6],["gpt-4o",128e3],["gpt-4-turbo",128e3],["o1",2e5],["o3",2e5],["o4",2e5],["gpt-3.5",16385],["claude",2e5]];function j(e){let n=e.toLowerCase();for(let[t,r]of T)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function le(e){return e.context_window&&e.context_window>0?e.context_window:j(e.model)}var w=new Map;async function pe(e,n){if(e.context_window&&e.context_window>0)return e.context_window;if(e.protocol==="anthropic"){let t=`${e.name}-${e.model}`,r=w.get(t);if(r===void 0){try{r=await(n??(await import("./anthropic-PWUGDLNY.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(t,r)}if(r&&r>0)return r}return j(e.model)}function ue(e){return e.max_output_tokens&&e.max_output_tokens>0?e.max_output_tokens:e.thinking?64e3:8192}function me(e){if(e.api_key)return e.api_key;let n=V(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var z=o.object({name:o.string(),command:o.string().optional(),args:o.array(o.string()).optional(),url:o.string().optional(),transport:o.string().optional(),headers:o.record(o.string(),o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),O=o.object({id:o.string().optional(),event:o.string(),condition:o.string().optional(),action:o.object({type:o.string(),command:o.string().optional(),url:o.string().optional(),method:o.string().optional(),prompt:o.string().optional()}),reject:o.boolean().optional(),once:o.boolean().optional(),async:o.boolean().optional(),on_error:o.string().optional()}),M=o.object({enabled:o.boolean().optional(),auto_allow:o.boolean().optional(),network_enabled:o.boolean().optional()}),Y=o.object({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(z).default([]),hooks:o.array(O).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function K(e){return typeof e=="object"&&e!==null}function C(e){let n=I(e,"utf-8"),t=S.load(n);if(!K(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=f(Y,t);if(r.success){let a=r.data;return{providers:a.providers,permission_mode:a.permission_mode,mcp_servers:a.mcp_servers,hooks:a.hooks}}g.error({error:r.error},"config error");let i=[],s,c=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=f(o.array(P),t.providers);a.success&&(i=a.data)}if("permission_mode"in t&&typeof t.permission_mode=="string"&&(s=t.permission_mode),"mcp_servers"in t){let a=f(o.array(z),t.mcp_servers);a.success&&(c=a.data)}if("hooks"in t){let a=f(o.array(O),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=f(M,t.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in t&&(b=!!t.enable_coordinator_mode),"enable_fork"in t&&(h=!!t.enable_fork),{providers:i,permission_mode:s,mcp_servers:c,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function W(e,n){if(n.providers.length>0&&(e.providers=n.providers),n.permission_mode&&(e.permission_mode=n.permission_mode),n.mcp_servers.length>0){let t=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];t.set(i.name,r)}for(let r of n.mcp_servers){let i=t.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),t.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...n.hooks],n.sandbox&&(e.sandbox={...e.sandbox,...n.sandbox}),n.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),n.enable_fork!==void 0&&(e.enable_fork=n.enable_fork),e}function k(e){if(e.providers.length===0)throw new l("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"];for(let t=0;t<e.providers.length;t++){let r=e.providers[t],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=n.filter(c=>!(c in i));if(s.length>0)throw new l(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new l(`Provider #${String(t+1)}: invalid protocol '${r.protocol}', MUST be one of: ${Array.from(_).join(", ")}`)}}function _e(e){if(e){let s=C(e);return k(s),s}let n=process.cwd(),t=N(),r=[d(t,".swifty","config.yml"),d(t,".swifty","config.yaml"),d(n,".swifty","config.yml"),d(n,".swifty","config.yaml"),d(n,".swifty","config.local.yml"),d(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let c=C(s);i?i=W(i,c):i=c}if(!i)throw new l("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{p as a,f as b,ee as c,oe as d,ne as e,le as f,pe as g,ue as h,me as i,ge as j,_e as k};
Binary file