@swifty.js/swifty 0.0.8 → 0.0.10

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 hangtiancheng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -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{j as a}from"./chunk-A6H62GTA.js";import"./chunk-OXEMDMZF.js";import"./chunk-FZPTNGTU.js";import"./chunk-ISXLT3QN.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
4
+ import{h as a}from"./chunk-SM5OVMF6.js";import"./chunk-OKI2P5FO.js";import"./chunk-FZPTNGTU.js";import"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.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{l as C}from"./chunk-OKI2P5FO.js";import{e as F,g as G,h as R}from"./chunk-OZOP4GVS.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-XYSBNUNB.js";import"./chunk-MQ5XOYLD.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};
File without changes
@@ -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,b,c,d,e}from"./chunk-ZSJ2I5WM.js";import"./chunk-7MHXMDYC.js";import"./chunk-ISXLT3QN.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
4
+ import{a,b,c,d,e}from"./chunk-2BJOFNPI.js";import"./chunk-7MHXMDYC.js";import"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
@@ -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 w}from"./chunk-7MHXMDYC.js";import{D as u,I as D,R as d,e as k}from"./chunk-ISXLT3QN.js";import{readFileSync as $,writeFileSync as j,mkdirSync as A,statSync as S}from"fs";import{homedir as _,tmpdir as M}from"os";import{join as h,resolve as l,dirname as W}from"path";var E=D({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=k(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};
4
+ import{a as w}from"./chunk-7MHXMDYC.js";import{D as u,I as D,S as d,e as k}from"./chunk-XYSBNUNB.js";import{readFileSync as $,writeFileSync as j,mkdirSync as A,statSync as S}from"fs";import{homedir as _,tmpdir as M}from"os";import{join as h,resolve as l,dirname as W}from"path";var E=D({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=k(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};
File without changes
File without changes
File without changes
File without changes
@@ -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 a,I as y,K as T,L as A,O as E,S as B,e as w,f as P}from"./chunk-XYSBNUNB.js";var R=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,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,o=""){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),s&&n.push(`# Auto Memory
10
+ `+s),o&&n.push(`# availableSkills
11
+ `+o),n.length===0)return;let r=new Date().toISOString().split("T")[0];n.push(`# Current Date
12
+ Today's date is `+r+".");let i=`
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:i}),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{randomBytes as me}from"crypto";import{readFileSync as $,writeFileSync as de,readdirSync as pe,mkdirSync as fe,statSync as he,existsSync as Y,unlinkSync as Ze,rmSync as et}from"fs";import{basename as k,dirname as x,join as h}from"path";import{createHash as ne}from"crypto";import{existsSync as re,mkdirSync as ie,readFileSync as ae,writeFileSync as ce}from"fs";import{join as j}from"path";function oe(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 N=y({module:"images"}),le={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"};function ue(t,e){return j(t,".swifty","sessions",e||"default","images")}function ge(t,e,s,o){let n=Buffer.from(s,"base64"),r=ne("sha256").update(n).digest("hex").slice(0,16),c=le[o]??"png",i=ue(t,e),l=j(i,`${r}.${c}`);return re(l)||(ie(i,{recursive:!0}),ce(l,n)),l}var L="image_ref";function O(t,e,s){return s.map(o=>{if(o.type!=="image"||!A(o.source)||o.source.type!=="base64")return o;let n=o.source.data,r=o.source.media_type;if(typeof n!="string"||typeof r!="string")return o;try{let c=ge(t,e,n,r);return{type:L,path:c,media_type:r}}catch(c){return N.error({err:c},"failed to persist session image"),o}})}function F(t){return t.map(e=>{if(e.type!==L||typeof e.path!="string")return e;try{let s=ae(e.path);return{type:"image",source:{type:"base64",media_type:typeof e.media_type=="string"?e.media_type:"image/png",data:s.toString("base64")}}}catch(s){return N.warn({err:s,path:e.path},"failed to restore session image"),{type:"text",text:"[note: an image from this tool result could not be restored]"}}})}var _="compact_boundary";var q=a.object({tool_use_id:a.string(),tool_name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),C=a.union([a.string(),a.array(a.record(a.string(),a.unknown()))]),K=a.object({tool_use_id:a.string(),content:C,is_error:a.boolean().optional()}),z=a.object({role:a.string(),content:C.default(""),timestamp:a.number(),type:a.string().optional(),tool_uses:a.array(q).optional(),tool_results:a.array(K).optional()}),ye=a.object({role:a.string(),content:C,tool_uses:a.array(q).optional(),tool_results:a.array(K).optional()});function H(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 W(t,e){return(e??[]).map(s=>({tool_use_id:s.toolUseId,content:M(s.content,t),...s.isError?{is_error:!0}:{}}))}function M(t,e){return typeof t=="string"?t:e?O(e.workDir,e.sessionId,t):t.map(s=>s.type==="image"?{type:"text",text:"[note: image omitted (no session storage available)]"}:s)}var Te=a.object({summary:a.string(),keep:a.array(ye)}),b=y({module:"session"});function S(t){return h(t,".swifty","sessions")}function it(t,e){return h(S(t),e+".jsonl")}function J(t){let e=k(t);if(!e.endsWith(".jsonl"))return null;let s=x(t),o=x(s);return k(s)!=="sessions"||k(o)!==".swifty"?null:{workDir:x(o),sessionId:e.slice(0,-6)}}function at(){let t=Date.now().toString(36),e=me(4).toString("hex");return`${t}-${e}`}function Re(t,e,s){let o=S(t);fe(o,{recursive:!0});let n=h(o,`${e}.jsonl`),r={...s,content:M(s.content,{workDir:t,sessionId:e})},c=JSON.stringify(r)+`
22
+ `;de(n,c,{flag:"a",encoding:"utf-8"})}function ct(t,e,s){Re(t,e,{role:"system",content:JSON.stringify(s),timestamp:Math.floor(Date.now()/1e3),type:_})}function lt(t,e){let s=h(S(t),`${e}.jsonl`);if(!Y(s))return[];let o=[];for(let n of $(s,"utf-8").split(`
23
+ `))if(n.trim())try{let r=JSON.parse(n),{success:c,data:i,error:l}=P(z,r);c?!i.content&&!(i.tool_uses?.length??0)&&!(i.tool_results?.length??0)||o.push(i):b.error({err:l},"session operation failed")}catch(r){b.error({err:r},"session operation failed")}return o}function v(t){return typeof t=="string"?t:F(t)}function G(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function X(t){return t?.map(e=>({toolUseId:e.tool_use_id,content:v(e.content),isError:e.is_error}))}function ut(t){let e=-1;for(let o=t.length-1;o>=0;o--)if(t[o].type===_){e=o;break}let s=[];if(e>=0){let o=null;try{let n=t[e].content,r=typeof n=="string"?JSON.parse(n):null;o=w(Te,r)}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)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||s.push({role:r.role,content:v(r.content),toolUses:G(r.tool_uses),toolResults:X(r.tool_results)})}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===_)continue;let c=D(r);c&&s.push(c)}return s}for(let o of t){let n=D(o);n&&s.push(n)}return s}function D(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:v(t.content),toolUses:G(t.tool_uses),toolResults:X(t.tool_results)}}function gt(t){let e=S(t);if(!Y(e))return[];let s=pe(e).filter(n=>n.endsWith(".jsonl")),o=[];for(let n of s){let r=h(e,n),c=he(r),i=n.replace(".jsonl",""),l="",u=0;try{for(let g of $(r,"utf-8").split(`
28
+ `)){if(!g.trim())continue;let m;try{let p=JSON.parse(g);m=w(z,p)}catch(p){b.error({err:p},"session operation failed");continue}u++,!l&&m.role==="user"&&m.content&&(l=T(m.content).slice(0,100))}}catch(g){b.error({err:g},"session operation failed");continue}o.push({id:i,firstMessage:l,messageCount:u,size:c.size,modTime:c.mtime})}return o.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),o}var V=3,be=3,Me="[earlier conversation truncated for compaction retry]",Se=3.5,we=1e4,ke=5,xe=4e4,_e=2,Ce=2e4,ve=13e3,Ie=3e3;function Q(t,e,s=!1){return t-Math.min(e,Ce)-(s?Ie:ve)}var Z=class{consecutiveFailures=0},Ue=7e3;function ee(t){if(typeof t=="string")return t.length;let e=0;for(let s of t)s.type==="text"?e+=B(s,"text").length:s.type==="image"&&(e+=Ue);return e}function I(t){let e=0;for(let s of t){if(e+=ee(s.content),s.toolUses&&(e+=JSON.stringify(s.toolUses).length),s.toolResults)for(let o of s.toolResults)e+=ee(o.content);if(s.thinkingBlocks)for(let o of s.thinkingBlocks)e+=o.thinking.length}return Math.ceil(e/Se)}function Pe(t){return I(t.getMessages())}function U(t){return I([t])}function Ae(t){return t.role==="user"&&!!t.toolResults&&t.toolResults.length>0}function Ee(t){let e=0,s=0,o=t.length;for(let n=t.length-1;n>=0;n--){let r=U(t[n]);if(s>0&&e+r>xe||(o=n,e+=r,s++,e>=we||s>=ke))break}return o=Be(t,o),o}function Be(t,e){if(e<=0||e>=t.length||!Ae(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 je(t,e){let s=e??t.usageAnchorState();if(!s)return Pe(t);let o=t.getMessages(),n=Math.min(s.anchorCount,o.length);return s.baselineTokens+I(o.slice(n))}async function ht(t,e,s,o,n,r,c,i,l=""){let u=je(t),g=Q(s,o),m=Q(s,o,!0);if(u<g)return{compacted:!1,message:""};if(!(u>=m)&&n.consecutiveFailures>=V)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(V)} consecutive failures`};try{let f=await te(t,e,r,c,i,l);return n.consecutiveFailures=0,f}catch(f){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${E(f)}`}}}async function yt(t,e,s,o,n,r=""){return te(t,e,s,o,n,r)}var Ne=`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 Le(t){return Ne+`
112
+
113
+ `+t}function Oe(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 Fe(t,e){let s=Oe(t);if(s.length<2)return null;let o;if(e>0){let r=0;o=0;for(let c of s)if(r+=c.reduce((i,l)=>i+U(l),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:Me}),n}function De(t){return t.map(e=>{let s=`[${e.role}]: ${T(e.content)}`;return e.toolUses&&(s+=`
114
+ [tools: ${e.toolUses.map(o=>o.toolName).join(", ")}]`),s}).join(`
115
+
116
+ `)}async function $e(t,e,s){let o=e;for(let n=0;;n++){let r=De(o),c=new R;c.addUserMessage(Le(r));try{let i="",l=t.stream(c,s);for await(let g of l)g.type==="text_delta"&&(i+=g.text);let u=/<summary>([\s\S]*?)<\/summary>/.exec(i);return u?u[1].trim():i}catch(i){let l=i instanceof Error?i.message.toLowerCase():"";if(!(l.includes("prompt")&&l.includes("long")||l.includes("too many")||l.includes("context_length"))||n>=be)throw i;let g=o.reduce((p,f)=>p+U(f),0)/5,m=Fe(o,g);if(!m)throw i;o=m}}}async function te(t,e,s,o,n,r=""){let c=t.getMessages(),i=Ee(c);if(i<=0||i<_e)return{compacted:!1,message:`Compaction skipped: only ${String(i)} message(s) to summarize, kept verbatim`};let l=c.slice(0,i),u=c.slice(i),g=await $e(e,l,n),m=s?s.buildRecoveryAttachment(o):"",p=`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
+ `+g;u.length>0&&(p+=`
119
+
120
+ Recent messages have been preserved verbatim.`),r&&(p+=`
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&&(p+=`
123
+
124
+ ---
125
+
126
+ ${m}`),t.replaceWithCompacted(p,u);let f=r?J(r)??void 0:void 0,se=u.filter(d=>(d.role==="user"||d.role==="assistant")&&(d.content||(d.toolUses?.length??0)||(d.toolResults?.length??0))).map(d=>({role:d.role,content:M(d.content,f),...d.toolUses?.length?{tool_uses:H(d.toolUses)}:{},...d.toolResults?.length?{tool_results:W(f,d.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(l.length)} messages into summary (${String(g.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:g,keep:se}}}export{R as a,oe as b,H as c,W as d,it as e,at as f,Re as g,ct as h,lt as i,ut as j,gt as k,Q as l,Z as m,ht as n,yt 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{a as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as u,c as m}from"./chunk-ISXLT3QN.js";import{existsSync as E,readFileSync as $}from"fs";import{homedir as I}from"os";import{join as l}from"path";function p(e){return!!e._zod}function c(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=S({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function N(e){return _.has(e)}var _=new Set(Object.keys(A)),d=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()}),V=[["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 V)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function de(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-GAI75HYJ.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=N(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var O=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()}),z=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()}),T=o.looseObject({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(O).default([]),hooks:o.array(z).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function Y(e){return typeof e=="object"&&e!==null}function C(e){let n=$(e,"utf-8"),t=x.load(n);if(!Y(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=c(T,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,f=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=c(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=c(o.array(O),t.mcp_servers);a.success&&(f=a.data)}if("hooks"in t){let a=c(o.array(z),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=c(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:f,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(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 d("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(f=>!(f in i));if(s.length>0)throw new d(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new d(`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=I(),r=[l(t,".swifty","config.yml"),l(t,".swifty","config.yaml"),l(n,".swifty","config.yml"),l(n,".swifty","config.yaml"),l(n,".swifty","config.local.yml"),l(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let f=C(s);i?i=K(i,f):i=f}if(!i)throw new d("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{c as a,ee as b,oe as c,ne as d,de as e,pe as f,ue as g,me as h,ge as i,_e as j};
4
+ import{a as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as u,c as m}from"./chunk-XYSBNUNB.js";import{existsSync as E,readFileSync as $}from"fs";import{homedir as I}from"os";import{join as l}from"path";function p(e){return!!e._zod}function c(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=S({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function N(e){return _.has(e)}var _=new Set(Object.keys(A)),d=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()}),V=[["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 V)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function de(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-DFGYPMNW.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=N(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var O=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()}),z=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()}),T=o.looseObject({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(O).default([]),hooks:o.array(z).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function Y(e){return typeof e=="object"&&e!==null}function C(e){let n=$(e,"utf-8"),t=x.load(n);if(!Y(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=c(T,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,f=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=c(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=c(o.array(O),t.mcp_servers);a.success&&(f=a.data)}if("hooks"in t){let a=c(o.array(z),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=c(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:f,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(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 d("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(f=>!(f in i));if(s.length>0)throw new d(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new d(`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=I(),r=[l(t,".swifty","config.yml"),l(t,".swifty","config.yaml"),l(n,".swifty","config.yml"),l(n,".swifty","config.yaml"),l(n,".swifty","config.local.yml"),l(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let f=C(s);i?i=K(i,f):i=f}if(!i)throw new d("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{c as a,ee as b,oe as c,ne as d,de as e,pe as f,ue as g,me as h,ge as i,_e as j};