@swifty.js/swifty 0.0.14 → 0.0.15

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.
@@ -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{h as a}from"./chunk-RNUCVDX2.js";import"./chunk-GQ2COSTQ.js";import"./chunk-FZPTNGTU.js";import"./chunk-M5AOLYFS.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
4
+ import{h as a}from"./chunk-CYMOBNZF.js";import"./chunk-6ZXBZB2Y.js";import"./chunk-FZPTNGTU.js";import"./chunk-J5LWUHF6.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{a as K}from"./chunk-MNZYPUTY.js";import{g as P}from"./chunk-H7VXSMJR.js";import{k as C}from"./chunk-6ZXBZB2Y.js";import{e as H,g as Y,h as R}from"./chunk-F24VPQ2I.js";import{b as j,c as W,d as M,e as D,f as F,g as G}from"./chunk-FZPTNGTU.js";import"./chunk-5CPQ6RWA.js";import"./chunk-7MHXMDYC.js";import{C as w,I as N,J as v,K as B,L as U,M as I,N as x,O as $,g as O}from"./chunk-J5LWUHF6.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";function J(o){return o.some(e=>e.defer_loading)}var h=N({module:"llm"});var z=3e3,V=w.object({max_input_tokens:w.coerce.number()});async function pt(o){if(o.protocol!=="anthropic")return 0;let e=R(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,s=new AbortController,r=setTimeout(()=>{s.abort()},z);try{let l=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...e?{"x-api-key":e}:{}},signal:s.signal});if(!l.ok)return 0;let d=await l.json(),{success:f,error:k,data:_}=await O(V,d);if(!f)return h.warn({message:k.message},"model context window schema validation failed"),0;let y=_.max_input_tokens;return Math.max(y,0)}catch(l){return h.error({err:l},"failed to fetch model context window"),0}finally{clearTimeout(r)}}function Q(){return!0}function E(o){return typeof o=="string"?[{type:"text",text:o}]:o}function X(o){let e=[];for(let t of o)if(t.role==="assistant"){let n=[];if(t.thinkingBlocks)for(let r of t.thinkingBlocks)n.push({type:"thinking",thinking:r.thinking,signature:r.signature});let s=typeof t.content=="string"?t.content:B(t.content);if(s&&n.push({type:"text",text:s}),t.toolUses)for(let r of t.toolUses)n.push({type:"tool_use",id:r.toolUseId,name:r.toolName,input:r.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 s of t.toolResults)n.push({type:"tool_result",tool_use_id:s.toolUseId,is_error:s.isError,content:s.content});e.push({role:"user",content:n})}else{if(e.length===0){e.push({role:"user",content:E(t.content)});continue}let n=!1,s=e[e.length-1],r=s.content;s.role==="user"&&(typeof r=="string"||Array.isArray(r)&&r.length>0&&(r[0].type==="text"||r[0].type==="image"))&&(n=!0),n?(typeof r=="string"&&(r=s.content=r.trim().length>0?[{type:"text",text:r}]:[]),r.push(...E(t.content))):e.push({role:"user",content:E(t.content)})}return e}var q=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(e,t){let n=R(e);if(!n)throw new M("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=Y(e),this.contextWindow=H(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,n){let s=X(j(e.getMessages())),r=J(t),l=t.map(c=>{let p=c.input_schema,u={name:c.name,description:c.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}};return c.defer_loading===!0&&(u.defer_loading=!0),u});l.length>0&&(l[l.length-1].cache_control={type:"ephemeral"}),Z(s);let d={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:s,...l.length>0?{tools:l}:{}};this.thinking?Q()&&(d.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):d.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let f=0,k=0,_=0,y=0,L="end_turn",T="",b="",A=!1,S=0;try{let c=this.client.messages.stream(d,{...n?{signal:n}:{},...r?{headers:{"anthropic-beta":K}}:{}}),p="",u="",m="";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"&&(u=a.id,p=a.name,m="",yield{type:"tool_call_start",toolName:p,toolId:u});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"?(h.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"&&(m+=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(m)try{let g=JSON.parse(m);a=U(g)?I(g):{[v]:m}}catch(g){h.error({err:g},"llm operation failed"),a={[v]:m}}yield{type:"tool_call_complete",toolId:u,toolName:p,arguments:a},p="",u="",m=""}break}case"message_delta":{i.delta.stop_reason&&(L=i.delta.stop_reason),i.usage.output_tokens&&(k=i.usage.output_tokens,i.usage.input_tokens&&(f=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(_=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(y=i.usage.cache_creation_input_tokens));break}case"message_start":{S=Date.now(),f=i.message.usage.input_tokens,k=i.message.usage.output_tokens,_=i.message.usage.cache_read_input_tokens??0,y=i.message.usage.cache_creation_input_tokens??0;break}case"message_stop":{let g=Date.now()-S;h.debug({elapsedMs:g},"message stream complete");break}}yield{type:"stream_end",stopReason:L,usage:{inputTokens:f,outputTokens:k,cacheReadInputTokens:_,cacheCreationInputTokens:y}}}catch(c){throw h.error({err:c},"llm operation failed"),tt(c)}}};function Z(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 s=t.length-1;s>=0;s--)if(t[s].type!=="image"){n=t[s];break}Reflect.set(n,"cache_control",{type:"ephemeral"})}}function tt(o){if(o instanceof P.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new G(`Prompt too long: ${o.message}`);if(o.status===401)return new M(`Invalid API key: ${o.message}`);if(o.status===429){let e=I(o.headers)["retry-after"],t="Rate Limited";if(e){let n=Number.parseInt(x(e));Number.isNaN(n)&&(t+=", please wait."),t+=`, retry after ${x(n)}s.`}else t+=", please wait.";return new D(t,e?x(e):void 0)}return new W(`Anthropic API error (${x(o.status)}): ${o.message}`)}return new F(`Network error: ${$(o)}`)}export{q as AnthropicClient,X as buildAnthropicMessages,pt as fetchModelContextWindow,Z as markLastUserTailForCache,J as needsToolSearchBeta};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{a,b,c,d,e}from"./chunk-32AZCTP4.js";import"./chunk-5CPQ6RWA.js";import"./chunk-7MHXMDYC.js";import"./chunk-J5LWUHF6.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
@@ -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{c as F}from"./chunk-5CPQ6RWA.js";import{a as w}from"./chunk-7MHXMDYC.js";import{D as d,I as D,S as l,e as k}from"./chunk-J5LWUHF6.js";import{b as x}from"./chunk-E55KH72M.js";import{readFileSync as _,writeFileSync as j,mkdirSync as M,statSync as $}from"fs";import{homedir as C,tmpdir as L}from"os";import{join as p,resolve as f,dirname as A}from"path";var E=D({module:"permissions"}),T=[{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"],O={Bash:"command",ReadFile:"file_path",WriteFile:"file_path",EditFile:"file_path",Glob:"pattern",Grep:"pattern"},Y=[".swifty/config.yaml",".swifty/permissions.local.yaml",".swifty/skills/"];function y(i,e){if(i===x)return F(l(e,"server",""),l(e,"tool",""));let t=O[i];if(!t)return"";let s=e[t];return typeof s=="string"?s:""}var R=class{allowedRoots;denyWritePaths;projectDir;constructor(e){this.projectDir=f(e),this.allowedRoots=[this.projectDir,L()],this.denyWritePaths=Y.map(t=>p(this.projectDir,t))}addRoot(e){this.allowedRoots.push(f(e))}addDenyWrite(e){this.denyWritePaths.push(f(e))}checkDenyWrite(e){let t=f(e);for(let s of this.denyWritePaths)if(t.startsWith(s))return{effect:"deny",reason:`Path ${e} is in deny-write list`};return null}check(e){let t=f(e);for(let s of this.allowedRoots)if(t.startsWith(s))return null;return{effect:"deny",reason:`Path ${e} is outside allowed directories`}}};function N(i,e){let t="^"+i.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$";try{return new RegExp(t).test(e)}catch(s){return E.error({err:s},"permissions operation failed"),!1}}var G=/^(\w+)\((.+)\)$/;function S(i){let e;try{e=_(i,"utf-8")}catch(r){return r.code!=="ENOENT"&&E.error({err:r},"permissions operation failed"),[]}let t=d.object({rule:d.string().optional(),effect:d.string().optional()}),s;try{let r=w.load(e);s=k(d.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=G.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!=="*")&&N(n.pattern,t)){if(n.effect==="deny")return"deny";n.effect==="ask"?s="ask":s??="allow"}return s}var P=class{userPath;projectPath;localPath;cache=new Map;constructor(e){this.userPath=p(C(),".swifty","permissions.yaml"),this.projectPath=p(e,".swifty","permissions.yaml"),this.localPath=p(e,".swifty","permissions.local.yaml")}rulesFor(e){let t;try{t=$(e,{bigint:!0})}catch{return this.cache.delete(e),[]}let s=this.cache.get(e);if(s?.mtimeNs===t.mtimeNs&&s.size===t.size)return s.rules;let n=S(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){M(A(this.localPath),{recursive:!0});let t=S(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 I(i){for(let e of T)if(e.re.test(i))return e.reason;return""}function U(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 B(i,e){switch(i){case"bypassPermissions":return"allow";case"plan":return e==="read"?"allow":"ask";case"acceptEdits":return e==="command"?"ask":"allow";default:return e==="read"?"allow":"ask"}}var W=class{mode;planFilePath="";sandboxEnabled=!1;sandboxAutoAllow=!1;sandbox;ruleEngine;constructor(e,t="default"){this.mode=t,this.sandbox=new R(e),this.ruleEngine=new P(e)}check(e,t,s){let n=y(e,s),r=null,o=()=>r??=this.ruleEngine.snapshot();if(this.mode==="plan"&&(e==="WriteFile"||e==="EditFile")&&l(s,"file_path","").includes(".swifty/plans/"))return{effect:"allow",reason:"Plan file write allowed in plan mode"};if(t==="command"&&U(n))return{effect:"allow",reason:"Safe read-only command"};let a=t==="command"?I(n):"";if(a)return{effect:"deny",reason:`Dangerous command blocked: ${a}`};if(this.sandboxEnabled&&this.sandboxAutoAllow&&t==="command"){let u=l(s,"command").split(/\s*(?:&&|\|\||[;|])\s*/).map(g=>g.trim()).filter(Boolean),c=!1;for(let g of u){let v=b(o(),e,g);if(v==="deny")return{effect:"deny",reason:"Permission rule: deny"};v==="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 h=l(s,"file_path",l(s,"path",""));if((t==="read"||t==="write")&&h){if(t==="write"){let c=this.sandbox.checkDenyWrite(h);if(c)return c}let u=this.sandbox.check(h);if(u&&this.mode!=="bypassPermissions"){let c=this.ruleEngine.evaluate(e,n);return c?{effect:c,reason:`Permission rule: ${c}`}:{effect:"ask",reason:u.reason}}}let m=b(o(),e,n);return m?{effect:m,reason:`Permission rule: ${m}`}:{effect:B(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=f(s),a=!1;try{a=$(o).isDirectory()}catch{}r=p(a?o:A(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,P as d,W as e};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{I as y,M as u,O as T,S as f}from"./chunk-J5LWUHF6.js";import{b as g}from"./chunk-E55KH72M.js";var S=y({module:"mcp"}),p="mcp__",m="__";function a(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function _(e){return p+a(e)+m}function h(e,r){return _(e)+a(r)}var C=class{name;description;category="command";deferred=!0;mcpServerName;client;originalName;inputSchema;constructor(r,t,n){this.name=h(t,n.name),this.description=n.description,this.originalName=n.name,this.client=r,this.inputSchema=n.inputSchema,this.mcpServerName=t}mcpInputSchema(){return this.inputSchema??{}}setDeferLoading(r){this.deferred=r}schema(){return{name:this.name,description:this.description,input_schema:this.inputSchema}}async execute(r,t){try{let{output:n,isError:s}=await this.client.callTool(this.originalName,t);return{output:n,isError:s}}catch(n){return S.error({err:n},"mcp operation failed"),{output:`MCP tool error: ${T(n)}`,isError:!0}}}};function x(e,r){if(r==="string"&&typeof e=="number"&&Number.isFinite(e))return String(e);if((r==="integer"||r==="number")&&typeof e=="string"){let t=e.trim();if(t===""||!(r==="integer"?/^[+-]?\d+$/:/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/).test(t))return e;let s=r==="integer"?Number.parseInt(t,10):Number.parseFloat(t);return Number.isNaN(s)?e:s}if(r==="boolean"&&typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}return e}function d(e,r){if(typeof r!="object"||r===null)return e;let t=u(r),n=f(t,"type","");if(n==="object"&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let s=u(t.properties??{}),o={};for(let[i,c]of Object.entries(e))o[i]=i in s?d(c,s[i]):c;return o}if(n==="array"){let s=t.items??{},o=e;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.values(o);i.length===1&&Array.isArray(i[0])&&(o=i[0])}else typeof o=="string"&&(o=o.split(",").map(i=>i.trim()).filter(i=>i!==""));return Array.isArray(o)?o.map(i=>d(i,s)):o}return n!==""?x(e,n):e}function O(e,r){if(r.startsWith(p)){let t=r.slice(p.length),n=t.indexOf(m);if(n>=0)return a(t.slice(0,n))+m+a(t.slice(n+m.length))}return a(e)+m+a(r)}function M(e){return"mcpInputSchema"in e&&typeof e.mcpInputSchema=="function"}var b=class{constructor(r){this.registry=r}registry;name=g;description="Invoke a tool on a connected MCP server. Call ToolSearch first to load the tool's schema, then pass its arguments here exactly as that schema requires, using the same JSON types.";category="command";deferred=!1;schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{server:{type:"string",description:"MCP server name, e.g. 'linear'."},tool:{type:"string",description:"Full tool name as returned by ToolSearch, e.g. 'mcp__linear__create_issue'."},arguments:{type:"object",description:"The target tool's arguments. Must match that tool's input_schema exactly, including JSON types: bare numbers for integer fields, bare true/false for boolean fields, quoted strings for string fields, and plain JSON arrays for array fields."}},required:["server","tool","arguments"]}}}resolve(r,t){let n=this.registry.get(t)??this.registry.get(h(r,t));if(n)return n;let s=m+a(t),o=this.registry.listTools().filter(i=>i.name.startsWith(p)&&i.name.endsWith(s));return o.length===1?o[0]:void 0}availableNames(){return this.registry.listTools().filter(r=>r.name.startsWith(p)).map(r=>r.name).sort()}async execute(r,t){let n=f(t,"server",""),s=f(t,"tool","");if(s==="")return{output:"McpCall requires a 'tool' name",isError:!0};let o=this.resolve(n,s);if(!o){let c=this.availableNames(),l=c.length>0?c.join(", "):"(none connected)";return{output:`Unknown MCP tool '${s}' on server '${n}'. Available tools: ${l}`,isError:!0}}let i={};if(typeof t.arguments=="object"&&t.arguments!==null&&!Array.isArray(t.arguments)&&(i=u(t.arguments)),M(o)){let c=o.mcpInputSchema();if(Object.keys(c).length>0){let l=d(i,c);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(i=u(l))}}return o.execute(r,i)}};export{p as a,C as b,O as c,M as d,b as e};