@swifty.js/swifty 0.0.21 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-ZCMBUWLZ.js → agent-RABW3Z3R.js} +1 -1
- package/dist/anthropic-V22T6E6E.js +4 -0
- package/dist/{checker-OJFS2MZY.js → checker-3RWAYF2U.js} +1 -1
- package/dist/{chunk-Y5WGBAGP.js → chunk-5KXBVL2A.js} +1 -1
- package/dist/{chunk-MUPVOATV.js → chunk-CV7OKXYC.js} +1 -1
- package/dist/chunk-MJR2C7S7.js +130 -0
- package/dist/{chunk-GUXBLUNR.js → chunk-NR62AA5K.js} +1 -1
- package/dist/{chunk-S6ZADC7C.js → chunk-OCQ6TYLT.js} +21 -20
- package/dist/chunk-QN27QEFS.js +4 -0
- package/dist/{chunk-LX2LK3TF.js → chunk-SIWLMWHH.js} +12 -11
- package/dist/chunk-Y43POSIW.js +389 -0
- package/dist/lib/agent-GHXYOARN.js +9 -0
- package/dist/lib/anthropic-7YEN2QTU.js +22 -0
- package/dist/lib/bwrap-QRGPUP4J.js +6 -0
- package/dist/lib/checker-6BW4222R.js +19 -0
- package/dist/lib/chunk-7IZEK7X5.js +545 -0
- package/dist/lib/chunk-BN4Q54G2.js +1096 -0
- package/dist/lib/chunk-BO76JDFZ.js +617 -0
- package/dist/lib/chunk-CYDNMEBC.js +339 -0
- package/dist/lib/chunk-EY7HE52Q.js +384 -0
- package/dist/lib/chunk-GHF2PSEW.js +8 -0
- package/dist/lib/chunk-GNI7YX6F.js +426 -0
- package/dist/lib/chunk-HK2Z6WP4.js +223 -0
- package/dist/lib/chunk-MF3YLQDS.js +1277 -0
- package/dist/lib/chunk-OO2CLOEE.js +88 -0
- package/dist/lib/chunk-ORSYNBMM.js +38 -0
- package/dist/lib/chunk-PZ42NAFA.js +242 -0
- package/dist/lib/chunk-VUD72RTY.js +39 -0
- package/dist/lib/glob.wasm +0 -0
- package/dist/lib/index.d.ts +5347 -0
- package/dist/lib/index.js +11990 -0
- package/dist/lib/openai-RDHZFJUT.js +15 -0
- package/dist/lib/seatbelt-FT5IY73W.js +6 -0
- package/dist/lib/tool-filter-VF7TZRE5.js +19 -0
- package/dist/main.js +204 -466
- package/dist/{openai-HXD52MZB.js → openai-6NWVJ5LI.js} +15 -15
- package/dist/{server-VMHWEO2Y.js → server-KQTLAXC6.js} +17 -17
- package/package.json +18 -6
- package/dist/anthropic-4ZVG7AMA.js +0 -4
- package/dist/chunk-6E6UA7MT.js +0 -126
- package/dist/chunk-DDBH5AEN.js +0 -386
- package/dist/chunk-ZZQE743W.js +0 -4
|
@@ -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{
|
|
4
|
+
import{i as a}from"./chunk-OCQ6TYLT.js";import"./chunk-MJR2C7S7.js";import"./chunk-FZPTNGTU.js";import"./chunk-SIWLMWHH.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 U}from"./chunk-5KXBVL2A.js";import{g as P}from"./chunk-H7VXSMJR.js";import{l as M}from"./chunk-MJR2C7S7.js";import{e as H,g as q,h as C}from"./chunk-CV7OKXYC.js";import{b as O,c as $,d as I,e as K,f as W,g as F}from"./chunk-FZPTNGTU.js";import"./chunk-QN27QEFS.js";import"./chunk-7MHXMDYC.js";import{C as w,I as L,J as N,K as B,L as v,M as _,N as j,g as S}from"./chunk-SIWLMWHH.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";function Y(o){for(let t=o.length-1;t>=0;t--){let e=o[t];if(e.defer_loading!==!0){e.cache_control={type:"ephemeral"};return}}}function z(o){return o.some(t=>t.defer_loading)}var x=L({module:"llm"});var D=3e3,J=w.object({max_input_tokens:w.coerce.number()});async function ct(o){if(o.protocol!=="anthropic")return 0;let t=C(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,s=new AbortController,r=setTimeout(()=>{s.abort()},D);try{let c=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...t?{"x-api-key":t}:{}},signal:s.signal});if(!c.ok)return 0;let m=await c.json(),{success:h,error:g,data:f}=await S(J,m);if(!h)return x.warn({message:g.message},"model context window schema validation failed"),0;let d=f.max_input_tokens;return Math.max(d,0)}catch(c){return x.error({err:c},"failed to fetch model context window"),0}finally{clearTimeout(r)}}function V(){return!0}function E(o){return typeof o=="string"?[{type:"text",text:o}]:o}function Q(o){let t=[];for(let e of o)if(e.role==="assistant"){let n=[];if(e.thinkingBlocks)for(let r of e.thinkingBlocks)n.push({type:"thinking",thinking:r.thinking,signature:r.signature});let s=typeof e.content=="string"?e.content:N(e.content);if(s&&n.push({type:"text",text:s}),e.toolUses)for(let r of e.toolUses)n.push({type:"tool_use",id:r.toolUseId,name:r.toolName,input:r.arguments});n.length===0&&n.push({type:"text",text:""}),t.push({role:"assistant",content:n})}else if(e.toolResults&&e.toolResults.length>0){let n=[];for(let s of e.toolResults)n.push({type:"tool_result",tool_use_id:s.toolUseId,is_error:s.isError,content:s.contentBlocks?.length?s.contentBlocks:s.content});t.push({role:"user",content:n})}else{if(t.length===0){t.push({role:"user",content:E(e.content)});continue}let n=!1,s=t[t.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(e.content))):t.push({role:"user",content:E(e.content)})}return t}var G=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(t,e){let n=C(t);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:t.base_url}),this.model=t.model,this.thinking=t.thinking??!0,this.systemPrompt=e,this.maxOutputTokens=q(t),this.contextWindow=H(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.maxOutputTokens=t}async*stream(t,e,n){let s=Q(O(t.getMessages())),r=z(e),c=e.map(l=>{let p=l.input_schema,u={name:l.name,description:l.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}};return l.defer_loading===!0&&(u.defer_loading=!0),u});Y(c),X(s);let m={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:s,...c.length>0?{tools:c}:{}};this.thinking?V()&&(m.thinking={type:"enabled",budget_tokens:M(this.contextWindow,this.maxOutputTokens)}):m.thinking={type:"enabled",budget_tokens:M(this.contextWindow,this.maxOutputTokens)};let h=0,g=0,f=0,d=0,R="end_turn",T="",b="",A=!1;try{let l=this.client.messages.stream(m,{...n?{signal:n}:{},...r?{headers:{"anthropic-beta":U}}:{}}),p="",u="",k="";for await(let i of l)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,k="",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"?b=a.signature:a.type==="text_delta"?yield{type:"text_delta",text:a.text}:a.type==="input_json_delta"&&(k+=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(k)try{let y=JSON.parse(k);a=B(y)?v(y):{}}catch(y){x.error({err:y},"llm operation failed"),a={}}yield{type:"tool_call_complete",toolId:u,toolName:p,arguments:a},p="",u="",k=""}break}case"message_delta":{i.delta.stop_reason&&(R=i.delta.stop_reason),i.usage.output_tokens&&(g=i.usage.output_tokens,i.usage.input_tokens&&(h=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":{h=i.message.usage.input_tokens,g=i.message.usage.output_tokens,f=i.message.usage.cache_read_input_tokens??0,d=i.message.usage.cache_creation_input_tokens??0;break}}yield{type:"stream_end",stopReason:R,usage:{inputTokens:h,outputTokens:g,cacheReadInputTokens:f,cacheCreationInputTokens:d}}}catch(l){throw x.error({err:l},"llm operation failed"),Z(l)}}};function X(o){for(let t=o.length-1;t>=0;t--){if(o[t].role!=="user")continue;let e=o[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=o[t].content=[{type:"text",text:e}]);let n=e[e.length-1];for(let s=e.length-1;s>=0;s--)if(e[s].type!=="image"){n=e[s];break}Reflect.set(n,"cache_control",{type:"ephemeral"})}}function Z(o){if(o instanceof P.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new F(`Prompt too long: ${o.message}`);if(o.status===401)return new I(`Invalid API key: ${o.message}`);if(o.status===429){let t=v(o.headers)["retry-after"],e="Rate Limited";if(t){let n=Number.parseInt(_(t));Number.isNaN(n)&&(e+=", please wait."),e+=`, retry after ${_(n)}s.`}else e+=", please wait.";return new K(e,t?_(t):void 0)}return new $(`Anthropic API error (${_(o.status)}): ${o.message}`)}return new W(`Network error: ${j(o)}`)}export{G as AnthropicClient,Q as buildAnthropicMessages,ct as fetchModelContextWindow,X as markLastUserTailForCache,Y as markToolsForCache,z as needsToolSearchBeta};
|
|
@@ -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,f}from"./chunk-
|
|
4
|
+
import{a,b,c,d,e,f}from"./chunk-NR62AA5K.js";import"./chunk-QN27QEFS.js";import"./chunk-7MHXMDYC.js";import"./chunk-SIWLMWHH.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,f as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent,e as isSafeCommand};
|
|
@@ -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 i,d as s}from"./chunk-
|
|
4
|
+
import{a as i,d as s}from"./chunk-QN27QEFS.js";var a=10,p=2.5,E="advanced-tool-use-2025-11-20",f=new Set(["api.anthropic.com"]),d="SWIFTY_MCP_LOADING";function u(o){if(!o)return!0;try{return f.has(new URL(o).hostname.toLowerCase())}catch{return!1}}function l(o){return Math.floor(o/p)}function m(o,t,e,n=a){let r=(process.env[d]??"").trim().toLowerCase();if(r==="eager"||r==="native"||r==="dispatch")return r;if(e<=0)return"eager";let c=t*n/100;return l(e)<c?"eager":u(o)?"native":"dispatch"}function g(o){let t=0;for(let e of o.listTools())if(e.name.startsWith(i))try{t+=JSON.stringify(e.schema()).length}catch{t+=e.name.length+(e.description?.length??0)}return t}function T(o,t){o.mcpLoadingMode=t;let e=t==="eager";for(let n of o.listTools())s(n)&&typeof n.setDeferLoading=="function"&&n.setDeferLoading(!e);o.exposeToolSearch=!e,o.exposeMcpCall=t==="dispatch"}function M(o,t,e){let n=m(t,e,g(o));return T(o,n),n}export{E as a,T as b,M as c};
|
|
@@ -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 p,c as u}from"./chunk-
|
|
4
|
+
import{a as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as p,c as u}from"./chunk-SIWLMWHH.js";import{existsSync as E,readFileSync as $}from"fs";import{homedir as I}from"os";import{join as m}from"path";function l(e){return!!e._zod}function f(e,t){return l(e)?p(e,t):e.safeParse(t)}async function ee(e,t){return l(e)?await u(e,t):await e.safeParseAsync(t)}function oe(e){if(!e)return;let t;if(l(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function ne(e){if(l(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 n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.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(t){super(t),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 t=e.toLowerCase();for(let[n,r]of V)if(t.includes(n))return r;return t.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,t){if(e.context_window&&e.context_window>0)return e.context_window;if(e.protocol==="anthropic"){let n=`${e.name}-${e.model}`,r=w.get(n);if(r===void 0){try{r=await(t??(await import("./anthropic-V22T6E6E.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(n,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 t=N(e.protocol)?A[e.protocol]:"";return t?process.env[t]??"":""}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 t=$(e,"utf-8"),n=x.load(t);if(!Y(n))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=f(T,n);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 n){let a=f(o.array(P),n.providers);a.success&&(i=a.data)}if("permission_mode"in n&&typeof n.permission_mode=="string"&&(s=n.permission_mode),"mcp_servers"in n){let a=f(o.array(O),n.mcp_servers);a.success&&(c=a.data)}if("hooks"in n){let a=f(o.array(z),n.hooks);a.success&&(y=a.data)}if("sandbox"in n){let a=f(M,n.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in n&&(b=!!n.enable_coordinator_mode),"enable_fork"in n&&(h=!!n.enable_fork),{providers:i,permission_mode:s,mcp_servers:c,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(e,t){if(t.providers.length>0&&(e.providers=t.providers),t.permission_mode&&(e.permission_mode=t.permission_mode),t.mcp_servers.length>0){let n=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];n.set(i.name,r)}for(let r of t.mcp_servers){let i=n.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),n.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...t.hooks],t.sandbox&&(e.sandbox={...e.sandbox,...t.sandbox}),t.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),t.enable_fork!==void 0&&(e.enable_fork=t.enable_fork),e}function k(e){if(e.providers.length===0)throw new d("At least one provider MUST be configured.");let t=["name","protocol","base_url","model"];for(let n=0;n<e.providers.length;n++){let r=e.providers[n],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=t.filter(c=>!(c in i));if(s.length>0)throw new d(`Provider #${String(n+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new d(`Provider #${String(n+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 t=process.cwd(),n=I(),r=[m(n,".swifty","config.yaml"),m(t,".swifty","config.yaml"),m(t,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let c=C(s);i?i=K(i,c):i=c}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{f as a,ee as b,oe as c,ne as d,le as e,pe as f,ue as g,me as h,ge as i,_e as j};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{g as E}from"./chunk-FZPTNGTU.js";import{D as a,I,J as h,N as P,R as U,e as C,f as A}from"./chunk-SIWLMWHH.js";var y=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(t){this.history.push({role:"user",content:t})}addAssistantMessage(t){this.history.push({role:"assistant",content:t})}addToolUseMessage(t,n,o,s){this.history.push({role:"assistant",content:t,toolUses:[{toolUseId:n,toolName:o,arguments:s}]})}addAssistantMessageWithTools(t,n){this.history.push({role:"assistant",content:t,toolUses:n})}addAssistantFull(t,n,o){this.history.push({role:"assistant",content:t,thinkingBlocks:n.length>0?n:void 0,toolUses:o.length>0?o:void 0})}addToolResultMessage(t,n,o,s){this.history.push({role:"user",content:"",toolResults:[{toolUseId:t,content:n,...s?.length?{contentBlocks:s}:{},isError:o}]})}addToolResultsMessage(t){this.history.push({role:"user",content:"",toolResults:t})}addSystemReminder(t){this.history.push({role:"user",content:`<system-reminder>
|
|
5
|
+
${t}
|
|
6
|
+
</system-reminder>`})}hasReminderContaining(t){return this.history.some(n=>n.role==="user"&&h(n.content).includes(t))}injectLongTermMemory(t,n,o=""){if(this.longTermMemoryInjected)return;let s=[];if(t&&s.push(`# SWIFTY.md
|
|
7
|
+
Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.
|
|
8
|
+
|
|
9
|
+
${t}}`),n&&s.push(`# Auto Memory
|
|
10
|
+
`+n),o&&s.push(`# Available Skills
|
|
11
|
+
`+o),s.length===0)return;let r=new Date().toISOString().split("T")[0];s.push(`# Current Date
|
|
12
|
+
|
|
13
|
+
Today's date is ${r}.`);let i=`
|
|
14
|
+
<system-reminder>
|
|
15
|
+
As you answer the user's questions, you can use the following context:
|
|
16
|
+
|
|
17
|
+
${s.join(`
|
|
18
|
+
|
|
19
|
+
`)}
|
|
20
|
+
|
|
21
|
+
IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
|
|
22
|
+
</system-reminder>`;this.history.unshift({role:"user",content:i}),this.longTermMemoryInjected=!0}appendMessages(t){this.history.push(...t)}len(){return this.history.length}truncateTo(t){t<0&&(t=0),!(t>this.history.length)&&(this.history=this.history.slice(0,t))}reset(){this.history=[],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}getMessages(){return[...this.history]}replaceWithCompacted(t,n){this.history=[{role:"user",content:t},...n],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(t,n,o,s){let r=t+o+s+n;r<=0||(this.baselineTokens=r,this._anchorCount=this.history.length)}clearUsageAnchor(){this.baselineTokens=0,this._anchorCount=0}usageAnchorState(){return this.baselineTokens<=0?null:{baselineTokens:this.baselineTokens,anchorCount:this._anchorCount}}};import{randomBytes as oe}from"crypto";import{readFileSync as O,writeFileSync as ne,readdirSync as se,mkdirSync as re,statSync as ie,existsSync as D,unlinkSync as De,rmSync as Fe}from"fs";import{join as k}from"path";function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Z=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function ee(e){return Z.has(e)}function M(e){return T(e)&&e.type==="text"&&typeof e.text=="string"?{type:"text",text:e.text}:null}function v(e){return!T(e)||e.type!=="image"||!T(e.source)?null:e.source.type==="url"&&typeof e.source.url=="string"?{type:"image",source:{type:"url",url:e.source.url}}:e.source.type==="base64"&&typeof e.source.media_type=="string"&&ee(e.source.media_type)&&typeof e.source.data=="string"?{type:"image",source:{type:"base64",media_type:e.source.media_type,data:e.source.data}}:null}function te(e){if(e.type!=="document"||!T(e.source))return null;let t=null;if(e.source.type==="url"&&typeof e.source.url=="string")t={type:"url",url:e.source.url};else if(e.source.type==="base64"&&e.source.media_type==="application/pdf"&&typeof e.source.data=="string")t={type:"base64",media_type:"application/pdf",data:e.source.data};else if(e.source.type==="text"&&e.source.media_type==="text/plain"&&typeof e.source.data=="string")t={type:"text",media_type:"text/plain",data:e.source.data};else if(e.source.type==="content"){if(typeof e.source.content=="string")t={type:"content",content:e.source.content};else if(Array.isArray(e.source.content)){let n=[];for(let o of e.source.content){let s=M(o)??v(o);if(!s)return null;n.push(s)}t={type:"content",content:n}}}return t?{type:"document",source:t,...typeof e.title=="string"||e.title===null?{title:e.title}:{},...typeof e.context=="string"||e.context===null?{context:e.context}:{}}:null}function j(e){let t=M(e);if(t)return t;let n=v(e);if(n)return n;if(!T(e))return null;if(e.type==="tool_reference"&&typeof e.tool_name=="string")return{type:"tool_reference",tool_name:e.tool_name};if(e.type==="search_result"&&typeof e.source=="string"&&typeof e.title=="string"&&Array.isArray(e.content)){let o=[];for(let s of e.content){let r=M(s);if(!r)return null;o.push(r)}return{type:"search_result",source:e.source,title:e.title,content:o}}return te(e)}var je=new Set([".claude",".git",".swifty",".next",".venv",".mypy_cache",".tox","__pycache__","build","dist","node_modules","vendor","venv"]);var S="compact_boundary";var F=a.object({tool_use_id:a.string(),tool_name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),_=a.union([a.string(),a.array(a.record(a.string(),a.unknown()))]),$=a.object({tool_use_id:a.string(),content:_,content_blocks:a.array(a.unknown()).optional(),is_error:a.boolean().optional()}),z=a.object({role:a.string(),content:_.default(""),timestamp:a.number(),type:a.string().optional(),tool_uses:a.array(F).optional(),tool_results:a.array($).optional()}),ae=a.object({role:a.string(),content:_,tool_uses:a.array(F).optional(),tool_results:a.array($).optional()});function q(e){return(e??[]).map(t=>({tool_use_id:t.toolUseId,tool_name:t.toolName,...t.arguments&&Object.keys(t.arguments).length?{arguments:t.arguments}:{}}))}function Y(e){return(e??[]).map(t=>({tool_use_id:t.toolUseId,content:t.content,...t.contentBlocks?.length?{content_blocks:t.contentBlocks}:{},...t.isError?{is_error:!0}:{}}))}var le=a.object({summary:a.string(),keep:a.array(ae)}),R=I({module:"session"});function b(e){return k(e,".swifty","sessions")}function He(e,t){return k(b(e),t+".jsonl")}function We(){let e=Date.now().toString(36),t=oe(4).toString("hex");return`${e}-${t}`}function ce(e,t,n){let o=b(e);re(o,{recursive:!0});let s=k(o,`${t}.jsonl`),r=JSON.stringify(n)+`
|
|
23
|
+
`;ne(s,r,{flag:"a",encoding:"utf-8"})}function Je(e,t,n){ce(e,t,{role:"system",content:JSON.stringify(n),timestamp:Math.floor(Date.now()/1e3),type:S})}function Ge(e,t){let n=k(b(e),`${t}.jsonl`);if(!D(n))return[];let o=[];for(let s of O(n,"utf-8").split(`
|
|
24
|
+
`))if(s.trim())try{let r=JSON.parse(s),{success:l,data:i,error:c}=A(z,r);l?!i.content&&!(i.tool_uses?.length??0)&&!(i.tool_results?.length??0)||o.push(i):R.error({err:c},"session operation failed")}catch(r){R.error({err:r},"session operation failed")}return o}function K(e){return e?.map(t=>({toolUseId:t.tool_use_id,toolName:t.tool_name,arguments:t.arguments}))}function N(e){if(!e)return;let t=[];for(let n of e){let o=j(n);o&&t.push(o)}return t.length>0?t:void 0}function H(e){return e?.map(t=>{let n=Array.isArray(t.content)?N(t.content):void 0,o=N(t.content_blocks)??n;return{toolUseId:t.tool_use_id,content:typeof t.content=="string"?t.content:h(t.content),...o?{contentBlocks:o}:{},isError:t.is_error??!1}})}function Xe(e){let t=-1;for(let o=e.length-1;o>=0;o--)if(e[o].type===S){t=o;break}let n=[];if(t>=0){let o=null;try{let s=e[t].content,r=typeof s=="string"?JSON.parse(s):null;o=C(le,r)}catch{o=null}if(o){let s=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
25
|
+
|
|
26
|
+
`+o.summary;o.keep.length>0&&(s+=`
|
|
27
|
+
|
|
28
|
+
Recent messages have been preserved verbatim.`),n.push({role:"user",content:s});for(let r of o.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||n.push({role:r.role,content:r.content,toolUses:K(r.tool_uses),toolResults:H(r.tool_results)})}for(let s=t+1;s<e.length;s++){let r=e[s];if(r.type===S)continue;let l=L(r);l&&n.push(l)}return n}for(let o of e){let s=L(o);s&&n.push(s)}return n}function L(e){return e.role!=="user"&&e.role!=="assistant"||!e.content&&!(e.tool_uses?.length??0)&&!(e.tool_results?.length??0)?null:{role:e.role,content:e.content,toolUses:K(e.tool_uses),toolResults:H(e.tool_results)}}function Ve(e){let t=b(e);if(!D(t))return[];let n=se(t).filter(s=>s.endsWith(".jsonl")),o=[];for(let s of n){let r=k(t,s),l=ie(r),i=s.replace(".jsonl",""),c="",u=0;try{for(let p of O(r,"utf-8").split(`
|
|
29
|
+
`)){if(!p.trim())continue;let d;try{let f=JSON.parse(p);d=C(z,f)}catch(f){R.error({err:f},"session operation failed");continue}u++,!c&&d.role==="user"&&d.content&&(c=h(d.content).slice(0,100))}}catch(p){R.error({err:p},"session operation failed");continue}o.push({id:i,firstMessage:c,messageCount:u,size:l.size,modTime:l.mtime})}return o.sort((s,r)=>r.modTime.getTime()-s.modTime.getTime()),o}var W=3,ue=3,me="[earlier conversation truncated for compaction retry]",pe=3.5,de=1e4,fe=5,ge=4e4,he=2,ye=2e4,Te=13e3,ke=3e3;function J(e,t,n=!1){return e-Math.min(t,ye)-(n?ke:Te)}var G=class{consecutiveFailures=0},x=7e3;function Re(e){if(typeof e=="string")return e.length;let t=0;for(let n of e)n.type==="text"?t+=U(n,"text").length:n.type==="image"&&(t+=x);return t}function be(e){let t=0,n=0;for(let o of e)if(o.type==="text")t+=o.text.length;else if(o.type==="image")n+=x;else if(o.type==="tool_reference")n+=o.tool_name.length;else if(o.type==="search_result")n+=o.source.length+o.title.length,n+=o.content.reduce((s,r)=>s+r.text.length,0);else if(o.source.type==="base64")n+=x;else if(o.source.type==="url")n+=o.source.url.length;else if(o.source.type==="text")n+=o.source.data.length;else if(typeof o.source.content=="string")n+=o.source.content.length;else for(let s of o.source.content)n+=s.type==="text"?s.text.length:x;return{textChars:t,richChars:n}}function w(e){let t=0;for(let n of e){if(t+=Re(n.content),n.toolUses&&(t+=JSON.stringify(n.toolUses).length),n.toolResults)for(let o of n.toolResults)if(o.contentBlocks?.length){let s=be(o.contentBlocks);t+=Math.max(o.content.length,s.textChars)+s.richChars}else t+=o.content.length;if(n.thinkingBlocks)for(let o of n.thinkingBlocks)t+=o.thinking.length}return Math.ceil(t/pe)}function xe(e){return w(e.getMessages())}function B(e){return w([e])}function Ce(e){return e.role==="user"&&!!e.toolResults&&e.toolResults.length>0}function Me(e){let t=0,n=0,o=e.length;for(let s=e.length-1;s>=0;s--){let r=B(e[s]);if(n>0&&t+r>ge||(o=s,t+=r,n++,t>=de||n>=fe))break}return o=Se(e,o),o}function Se(e,t){if(t<=0||t>=e.length||!Ce(e[t]))return t;let n=new Set((e[t].toolResults??[]).map(o=>o.toolUseId));for(let o=t-1;o>=0;o--){let s=e[o];if(s.role==="assistant"&&s.toolUses?.some(r=>n.has(r.toolUseId)))return o}return t}function _e(e,t){let n=t??e.usageAnchorState();if(!n)return xe(e);let o=e.getMessages(),s=Math.min(n.anchorCount,o.length);return n.baselineTokens+w(o.slice(s))}async function nt(e,t,n,o,s,r,l,i,c=""){let u=_e(e),p=J(n,o),d=J(n,o,!0);if(u<p)return{compacted:!1,message:""};if(!(u>=d)&&s.consecutiveFailures>=W)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(W)} consecutive failures`};try{let g=await Q(e,t,r,l,i,c);return s.consecutiveFailures=0,g}catch(g){return s.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${P(g)}`}}}async function st(e,t,n,o,s,r=""){return Q(e,t,n,o,s,r)}var X=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
30
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
31
|
+
|
|
32
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
33
|
+
|
|
34
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
35
|
+
- The user's explicit requests and intents
|
|
36
|
+
- Your approach to addressing the user's requests
|
|
37
|
+
- Key decisions, technical concepts and code patterns
|
|
38
|
+
- Specific details like:
|
|
39
|
+
- file names
|
|
40
|
+
- full code snippets
|
|
41
|
+
- function signatures
|
|
42
|
+
- file edits
|
|
43
|
+
- Errors that you ran into and how you fixed them
|
|
44
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
45
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
46
|
+
|
|
47
|
+
After your analysis, output your final summary wrapped in <summary> tags. Your summary should include the following sections:
|
|
48
|
+
|
|
49
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
50
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
51
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
52
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
53
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
54
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
55
|
+
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
56
|
+
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
57
|
+
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
|
|
58
|
+
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
|
|
59
|
+
|
|
60
|
+
Here's an example of how your output should be structured:
|
|
61
|
+
|
|
62
|
+
<example>
|
|
63
|
+
<analysis>
|
|
64
|
+
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
|
65
|
+
</analysis>
|
|
66
|
+
|
|
67
|
+
<summary>
|
|
68
|
+
1. Primary Request and Intent:
|
|
69
|
+
[Detailed description]
|
|
70
|
+
|
|
71
|
+
2. Key Technical Concepts:
|
|
72
|
+
- [Concept 1]
|
|
73
|
+
- [Concept 2]
|
|
74
|
+
- [...]
|
|
75
|
+
|
|
76
|
+
3. Files and Code Sections:
|
|
77
|
+
- [File Name 1]
|
|
78
|
+
- [Summary of why this file is important]
|
|
79
|
+
- [Summary of the changes made to this file, if any]
|
|
80
|
+
- [Important Code Snippet]
|
|
81
|
+
- [File Name 2]
|
|
82
|
+
- [Important Code Snippet]
|
|
83
|
+
- [...]
|
|
84
|
+
|
|
85
|
+
4. Errors and fixes:
|
|
86
|
+
- [Detailed description of error 1]:
|
|
87
|
+
- [How you fixed the error]
|
|
88
|
+
- [User feedback on the error if any]
|
|
89
|
+
- [...]
|
|
90
|
+
|
|
91
|
+
5. Problem Solving:
|
|
92
|
+
[Description of solved problems and ongoing troubleshooting]
|
|
93
|
+
|
|
94
|
+
6. All user messages:
|
|
95
|
+
- [Detailed non tool use user message]
|
|
96
|
+
- [...]
|
|
97
|
+
|
|
98
|
+
7. Pending Tasks:
|
|
99
|
+
- [Task 1]
|
|
100
|
+
- [Task 2]
|
|
101
|
+
- [...]
|
|
102
|
+
|
|
103
|
+
8. Current Work:
|
|
104
|
+
[Precise description of current work]
|
|
105
|
+
|
|
106
|
+
9. Optional Next Step:
|
|
107
|
+
[Optional Next step to take]
|
|
108
|
+
|
|
109
|
+
</summary>
|
|
110
|
+
</example>
|
|
111
|
+
|
|
112
|
+
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function we(e){return X+`
|
|
113
|
+
|
|
114
|
+
`+e}function Be(e){let t=[],n=[],o=!1;for(let s of e)s.role==="assistant"&&o&&n.length>0&&(t.push(n),n=[]),n.push(s),o=!!(s.toolResults&&s.toolResults.length>0);return n.length>0&&t.push(n),t}function Ae(e,t){let n=Be(e);if(n.length<2)return null;let o;if(t>0){let r=0;o=0;for(let l of n)if(r+=l.reduce((i,c)=>i+B(c),0),o++,r>=t)break}else o=Math.max(1,Math.floor(n.length/5));if(o=Math.min(o,n.length-1),o<1)return null;let s=n.slice(o).flat();return s.length>0&&s[0].role!=="user"&&s.unshift({role:"user",content:me}),s}function Ie(e){return e.map(t=>{let n=`[${t.role}]: ${h(t.content)}`;return t.toolUses&&(n+=`
|
|
115
|
+
[tools: ${t.toolUses.map(o=>o.toolName).join(", ")}]`),t.toolResults&&(n+=`
|
|
116
|
+
[tool results]
|
|
117
|
+
${t.toolResults.map(o=>o.content).join(`
|
|
118
|
+
`)}`),n}).join(`
|
|
119
|
+
|
|
120
|
+
`)}function V(e){let t=/<summary>([\s\S]*?)<\/summary>/.exec(e);if(t)return t[1].trim();let n=/<analysis>[\s\S]*?<\/analysis>/.exec(e);return n?e.replace(n[0],"").trim():e.trim()}async function Pe(e,t,n){let o=-1;for(let i=t.length-1;i>=0;i--)if(t[i].role==="assistant"){o=i;break}if(o<0)throw new Error("no assistant message found for cache-sharing compact");let s=new y;s.appendMessages(t.slice(0,o+1)),s.addUserMessage(X);let r="",l=e.stream(s,n);for await(let i of l)i.type==="text_delta"&&(r+=i.text);return V(r)}async function Ue(e,t,n){let o=t;for(let s=0;;s++){let r=Ie(o),l=new y;l.addUserMessage(we(r));try{let i="",c=e.stream(l,n);for await(let u of c)u.type==="text_delta"&&(i+=u.text);return V(i)}catch(i){let c=i instanceof Error?i.message.toLowerCase():"";if(!(c.includes("prompt")&&c.includes("long")||c.includes("too many")||c.includes("context_length"))||s>=ue)throw i;let p=o.reduce((f,g)=>f+B(g),0)/5,d=Ae(o,p);if(!d)throw i;o=d}}}async function Q(e,t,n,o,s,r=""){let l=e.getMessages(),i=Me(l);if(i<=0||i<he)return{compacted:!1,message:`Compaction skipped: only ${String(i)} message(s) to summarize, kept verbatim`};let c=l.slice(0,i),u=l.slice(i),p;try{p=await Pe(t,l,s)}catch(m){if(!(m instanceof E))throw m;p=await Ue(t,c,s)}let d=n?n.buildRecoveryAttachment(o):"",f=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
121
|
+
|
|
122
|
+
`+p;u.length>0&&(f+=`
|
|
123
|
+
|
|
124
|
+
Recent messages have been preserved verbatim.`),r&&(f+=`
|
|
125
|
+
|
|
126
|
+
If you need specific details from before compaction (code snippets, error messages, etc.), use ReadFile to read the full session transcript: ${r}`),d&&(f+=`
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
${d}`),e.replaceWithCompacted(f,u);let g=u.filter(m=>(m.role==="user"||m.role==="assistant")&&(m.content||(m.toolUses?.length??0)||(m.toolResults?.length??0))).map(m=>({role:m.role,content:m.content,...m.toolUses?.length?{tool_uses:q(m.toolUses)}:{},...m.toolResults?.length?{tool_results:Y(m.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(c.length)} messages into summary (${String(p.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:p,keep:g}}}export{y as a,je as b,q as c,Y as d,He as e,We as f,ce as g,Je as h,Ge as i,Xe as j,Ve as k,J as l,G as m,nt as n,st as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{c as F}from"./chunk-
|
|
4
|
+
import{c as F}from"./chunk-QN27QEFS.js";import{a as y}from"./chunk-7MHXMDYC.js";import{D as d,I as D,R as c,e as v}from"./chunk-SIWLMWHH.js";import{b as k}from"./chunk-E55KH72M.js";import{readFileSync as _,writeFileSync as j,mkdirSync as M,statSync as $}from"fs";import{homedir as C,tmpdir as L}from"os";import{join as p,resolve as f,dirname as A}from"path";var E=D({module:"permissions"}),T=[],z=["ls","pwd","echo","cat","head","tail","wc","date","whoami","uname","hostname","which","type","file","git status","git log","git diff","git branch","git show","git rev-parse","git remote","bun test","bun run","npm test","npm run","go test","go build","go vet","python -c","node -e"],O={Bash:"command",PowerShell:"command",ReadFile:"file_path",WriteFile:"file_path",EditFile:"file_path",Glob:"pattern",Grep:"pattern"},Y=[".swifty/config.yaml",".swifty/permissions.local.yaml",".swifty/skills/"];function w(i,e){if(i===k)return F(c(e,"server",""),c(e,"tool",""));let t=O[i];if(!t)return"";let s=e[t];return typeof s=="string"?s:""}var R=class{allowedRoots;denyWritePaths;projectDir;constructor(e){this.projectDir=f(e),this.allowedRoots=[this.projectDir,L()],this.denyWritePaths=Y.map(t=>p(this.projectDir,t))}addRoot(e){this.allowedRoots.push(f(e))}addDenyWrite(e){this.denyWritePaths.push(f(e))}checkDenyWrite(e){let t=f(e);for(let s of this.denyWritePaths)if(t.startsWith(s))return{effect:"deny",reason:`Path ${e} is in deny-write list`};return null}check(e){let t=f(e);for(let s of this.allowedRoots)if(t.startsWith(s))return null;return{effect:"deny",reason:`Path ${e} is outside allowed directories`}}};function B(i,e){let t="^"+i.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$";try{return new RegExp(t).test(e)}catch(s){return E.error({err:s},"permissions operation failed"),!1}}var G=/^(\w+)\((.+)\)$/;function S(i){let e;try{e=_(i,"utf-8")}catch(n){return n.code!=="ENOENT"&&E.error({err:n},"permissions operation failed"),[]}let t=d.object({rule:d.string().optional(),effect:d.string().optional()}),s;try{let n=y.load(e);s=v(d.array(t),n)}catch(n){return E.error({err:n},"permissions operation failed"),[]}let r=[];for(let n of s){if(n.effect!=="allow"&&n.effect!=="deny"&&n.effect!=="ask")continue;let o=G.exec((n.rule??"").trim());o&&r.push({tool:o[1],pattern:o[2],effect:n.effect})}return r}function b(i,e,t){let s=null;for(let r of i)if(!(r.tool!==e&&r.tool!=="*")&&B(r.pattern,t)){if(r.effect==="deny")return"deny";r.effect==="ask"?s="ask":s??="allow"}return s}var P=class{userPath;projectPath;localPath;cache=new Map;constructor(e){this.userPath=p(C(),".swifty","permissions.yaml"),this.projectPath=p(e,".swifty","permissions.yaml"),this.localPath=p(e,".swifty","permissions.local.yaml")}rulesFor(e){let t;try{t=$(e,{bigint:!0})}catch{return this.cache.delete(e),[]}let s=this.cache.get(e);if(s?.mtimeNs===t.mtimeNs&&s.size===t.size)return s.rules;let r=S(e);return this.cache.set(e,{mtimeNs:t.mtimeNs,size:t.size,rules:r}),r}snapshot(){return[this.userPath,this.projectPath,this.localPath].flatMap(e=>this.rulesFor(e))}evaluate(e,t){return b(this.snapshot(),e,t)}appendLocalRule(e){M(A(this.localPath),{recursive:!0});let t=S(this.localPath);if(t.some(n=>n.tool===e.tool&&n.pattern===e.pattern&&n.effect===e.effect))return;t.push(e);let r=t.map(n=>({rule:`${n.tool}(${n.pattern})`,effect:n.effect}));j(this.localPath,y.dump(r),"utf-8")}};function I(i){for(let e of T)if(e.re.test(i))return e.reason;return""}function N(i){let e=i.trim();return e.includes(">")||e.includes("|")||e.includes(";")||e.includes("&&")||e.includes("$(")||e.includes("`")?!1:z.some(t=>e===t||e.startsWith(t+" ")||e.startsWith(t+" "))}function U(i,e){switch(i){case"bypassPermissions":return"allow";case"plan":return e==="read"?"allow":"ask";case"acceptEdits":return e==="command"?"ask":"allow";default:return e==="read"?"allow":"ask"}}var W=class{mode;planFilePath="";sandboxEnabled=!1;sandboxAutoAllow=!1;sandbox;ruleEngine;constructor(e,t="default"){this.mode=t,this.sandbox=new R(e),this.ruleEngine=new P(e)}check(e,t,s){let r=w(e,s),n=null,o=()=>n??=this.ruleEngine.snapshot();if(this.mode==="plan"&&(e==="WriteFile"||e==="EditFile")&&c(s,"file_path","").includes(".swifty/plans/"))return{effect:"allow",reason:"Plan file write allowed in plan mode"};if(t==="command"&&N(r))return{effect:"allow",reason:"Safe read-only command"};let a=t==="command"?I(r):"";if(a)return{effect:"deny",reason:`Dangerous command blocked: ${a}`};if(this.sandboxEnabled&&this.sandboxAutoAllow&&e==="Bash"){let u=c(s,"command").split(/\s*(?:&&|\|\||[;|])\s*/).map(g=>g.trim()).filter(Boolean),l=!1;for(let g of u){let x=b(o(),e,g);if(x==="deny")return{effect:"deny",reason:"Permission rule: deny"};x==="ask"&&(l=!0)}return l?{effect:"ask",reason:"Permission rule: ask (sandbox does not override)"}:{effect:"allow",reason:"Sandbox auto-allow: OS sandbox active"}}let h=c(s,"file_path",c(s,"path",""));if((t==="read"||t==="write")&&h){if(t==="write"){let l=this.sandbox.checkDenyWrite(h);if(l)return l}let u=this.sandbox.check(h);if(u&&this.mode!=="bypassPermissions"){let l=this.ruleEngine.evaluate(e,r);return l?{effect:l,reason:`Permission rule: ${l}`}:{effect:"ask",reason:u.reason}}}let m=b(o(),e,r);return m?{effect:m,reason:`Permission rule: ${m}`}:{effect:U(this.mode,t),reason:`Mode: ${this.mode}`}}allowExtraRoot(e){this.sandbox.addRoot(e)}allowAlways(e,t){let s=w(e,t),r=e==="ReadFile"||e==="WriteFile"||e==="EditFile",n;if(r&&s){let o=f(s),a=!1;try{a=$(o).isDirectory()}catch{}n=p(a?o:A(o),"*")}else n=s.trim().split(/\s+/).slice(0,2).join(" ")+"*";this.ruleEngine.appendLocalRule({tool:e,pattern:n,effect:"allow"})}describeToolAction(e,t){let s=w(e,t);if(s)return s;let r=[];for(let[n,o]of Object.entries(t)){let a=String(o);a.length>80&&(a=a.slice(0,80)+"..."),r.push(`${n}: ${a}`)}return r.join(", ")}};export{w as a,R as b,b as c,P as d,N as e,W as f};
|
|
@@ -1,17 +1,17 @@
|
|
|
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{
|
|
5
|
-
\u2026 (content truncated)
|
|
4
|
+
import{c as D,d as O,e as U,g as W,m as B,n as Y,o as j}from"./chunk-MJR2C7S7.js";import{a as C,e as M,g as L}from"./chunk-FZPTNGTU.js";import{I as f,L as A,N as F,O as N,R as E}from"./chunk-SIWLMWHH.js";function x(n){return n?Math.floor(n.length/3.5):0}function T(n,e){if(e<=0||!n||x(n)<=e)return n;let t=Math.floor(e*3.5);if(t<=0||t>=n.length)return n;let o=`
|
|
5
|
+
\u2026 (content truncated)`;return t<=o.length?o.slice(0,t):n.slice(0,t-o.length)+o}var b=class{files=new Map;skills=new Map;recordFileRead(e,t){for(this.files.delete(e),this.files.set(e,{path:e,content:T(t,5e3),timestamp:Date.now()});this.files.size>5;){let o=this.files.keys().next().value;if(typeof o!="string")break;this.files.delete(o)}}recordSkillInvocation(e,t){this.skills.set(e,{name:e,body:t,timestamp:Date.now()})}snapshotFiles(e=5){return[...this.files.values()].sort((o,r)=>r.timestamp-o.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],o=this.snapshotFiles();if(o.length>0){t.push(`## Recently read files
|
|
6
6
|
`),t.push(`These snapshots are what the file-reading tool last returned. Re-open with the tool if you need the current bytes.
|
|
7
|
-
`);for(let
|
|
7
|
+
`);for(let s of o){let i=T(s.content,5e3),l=new Date(s.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${s.path} (read ${l})
|
|
8
8
|
|
|
9
9
|
\`\`\`
|
|
10
10
|
${i}${i.endsWith(`
|
|
11
11
|
`)?"":`
|
|
12
|
-
`}\`\`\``)}}let
|
|
12
|
+
`}\`\`\``)}}let r=this.snapshotSkills();if(r.length>0){let s=0,i=[];i.push(`## Active skills
|
|
13
13
|
`),i.push(`These skills were invoked earlier in the session. Continue to follow each SOP when its triggering condition applies.
|
|
14
|
-
`);let l=!1;for(let
|
|
14
|
+
`);let l=!1;for(let d of r){let u=T(d.body,5e3),g=x(u)+x(d.name)+8;if(s+g>25e3)break;s+=g,i.push(`### ${d.name}
|
|
15
15
|
|
|
16
16
|
${u}`),l=!0}l&&t.push(i.join(`
|
|
17
17
|
|
|
@@ -19,12 +19,12 @@ ${u}`),l=!0}l&&t.push(i.join(`
|
|
|
19
19
|
|
|
20
20
|
You still have access to the following tools \u2014 call them directly when the task needs one:
|
|
21
21
|
|
|
22
|
-
`+e.map(
|
|
22
|
+
`+e.map(s=>`- ${s}`).join(`
|
|
23
23
|
`)),t.length===0?"":(t.push(`## Note
|
|
24
24
|
|
|
25
25
|
Everything above the divider is reconstructed context. For exact code, error strings, or user-typed text, re-read the source rather than guess from the summary.`),t.join(`
|
|
26
26
|
|
|
27
|
-
`))}};import{readFileSync as de,writeFileSync as pe,mkdirSync as me,existsSync as
|
|
27
|
+
`))}};import{readFileSync as de,writeFileSync as pe,mkdirSync as me,existsSync as I}from"fs";import{join as $,resolve as H}from"path";var G=f({module:"plan-file"}),V=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],q=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function ge(){let n=V[Math.floor(Math.random()*V.length)],e=q[Math.floor(Math.random()*q.length)],t=Date.now().toString(36).slice(-4);return`${n}-${e}-${t}`}var m=null;function K(n,e){let t=H(e,".swifty","plans");return H(n).startsWith(t+"/")}function z(n){if(m&&I(m))if(!K(m,n))G.warn({planPath:m,workDir:n},"current plan path is not under work dir");else return m;let e=$(n,".swifty","plans");me(e,{recursive:!0});let t=ge();return m=$(e,`${t}.md`),pe(m,"","utf-8"),m}function Ne(){return!m||!I(m)?null:de(m,"utf-8")}function X(n){return!m||!I(m)?!1:K(m,n)?!0:(G.warn({planPath:m,workDir:n},"current plan path is not under work dir"),!1)}function Me(){m=null}var fe=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
|
|
28
28
|
|
|
29
29
|
## 1. Your Role
|
|
30
30
|
|
|
@@ -177,7 +177,7 @@ You:
|
|
|
177
177
|
|
|
178
178
|
SendMessage({ to: "investigator", message: "Fix the null pointer in src/auth/validate.ts:42. Add a null check before accessing user.id \u2014 if null, return 401. Commit and report the hash." })
|
|
179
179
|
|
|
180
|
-
Fix is in progress.`,ye="Coordinator mode still active (see full instructions earlier in conversation). You cannot read files, run commands, or edit code \u2014 send a worker instead. Tools: Agent, SendMessage, TaskStop, SyntheticOutput, TeamDelete. Address workers by the name in the from= field of a team-notification. Synthesize worker findings yourself before directing follow-up work.";function J(
|
|
180
|
+
Fix is in progress.`,ye="Coordinator mode still active (see full instructions earlier in conversation). You cannot read files, run commands, or edit code \u2014 send a worker instead. Tools: Agent, SendMessage, TaskStop, SyntheticOutput, TeamDelete. Address workers by the name in the from= field of a team-notification. Synthesize worker findings yourself before directing follow-up work.";function J(n=1){return n<=1||(n-1)%5===0?fe:ye}var ke=`Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
181
181
|
|
|
182
182
|
## Plan File Info:
|
|
183
183
|
|
|
@@ -220,18 +220,19 @@ Goal: Write your final plan to the plan file (the only file you can edit).
|
|
|
220
220
|
### Phase 5: Call ExitPlanMode
|
|
221
221
|
|
|
222
222
|
At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ExitPlanMode.
|
|
223
|
-
`,
|
|
223
|
+
`,ve="Plan mode still active (see full instructions earlier in conversation). Read-only except plan file (%PLAN_PATH%). Follow 5-phase workflow. End turns with AskUserQuestion (for clarifications) or ExitPlanMode (for plan approval). Never ask about plan approval via text or AskUserQuestion.",we=`## Exited Plan Mode
|
|
224
224
|
|
|
225
|
-
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,Re="You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.";function Q(
|
|
226
|
-
A plan file already exists at ${
|
|
227
|
-
No plan file exists yet. You should create your plan at ${
|
|
228
|
-
|
|
225
|
+
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,Re="You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.";function Q(n,e,t){let o=`Plan file: ${n}`;return e?o+=`
|
|
226
|
+
A plan file already exists at ${n}. You can read it and make incremental edits using the EditFile tool.`:o+=`
|
|
227
|
+
No plan file exists yet. You should create your plan at ${n} using the WriteFile tool.`,(t-1)%5===0?ke.replace("%PLAN_FILE_INFO%",o):ve.replace("%PLAN_PATH%",n)}function Oe(n,e){let t="";return e&&(t=` The plan file is located at ${n} if you need to reference it.`),we.replace("%EXTRA%",t)}function Ue(n,e){return e?Re.replace("%PLAN_PATH%",n):""}import{writeFileSync as be,mkdirSync as Se}from"fs";import{join as te,resolve as Z}from"path";var Ee=f({module:"tool-result"}),ee=2e5,y=2e3;function oe(n,e){return te(n,".swifty","sessions",e||"default","tool-results")}function ne(n,e,t,o){let r=oe(n,e);Se(r,{recursive:!0});let s=te(r,t+".txt");try{be(s,o,{encoding:"utf-8",flag:"wx"})}catch(i){if(Ee.error({err:i},"tool-result operation failed"),N(i)&&"code"in i&&i.code!=="EEXIST")throw i}return s}function He(n){return n.length<=y?n:n.slice(0,y)+`
|
|
228
|
+
\u2026 ${String(n.length-y)} chars omitted from transcript`}function _(n,e){n.content=e,n.contentBlocks?.length&&(n.contentBlocks=[{type:"text",text:e},...n.contentBlocks.filter(t=>t.type!=="text")])}function se(n,e){let t=Math.floor(n.length/1024),o=n.slice(0,y),r=n.length>y,s=`<persisted-output>
|
|
229
|
+
`;return s+=`Output too large (${String(t)}KB). Full content saved to:
|
|
229
230
|
${e}
|
|
230
231
|
|
|
231
|
-
`,
|
|
232
|
-
${
|
|
233
|
-
...`),
|
|
234
|
-
</persisted-output>`,
|
|
235
|
-
`+
|
|
236
|
-
`)),this.announcedDeferred=
|
|
237
|
-
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let
|
|
232
|
+
`,s+=`Preview (first 2KB):
|
|
233
|
+
${o}`,r&&(s+=`
|
|
234
|
+
...`),s+=`
|
|
235
|
+
</persisted-output>`,s}function re(n,e,t,o){if(n!=="ReadFile"||!e)return!1;let r=e.file_path;return typeof r!="string"||!r?!1:Z(r).startsWith(Z(oe(t,o)))}function ie(n,e,t,o){let r=n.reduce((i,l)=>i+l.content.length,0);if(r<=ee)return;let s=n.toSorted((i,l)=>l.content.length-i.content.length);for(let i of s){if(r<=ee)break;if(o?.has(i.toolUseId))continue;let l=i.content;if(l.length<=y)continue;let d;try{d=ne(e,t,i.toolUseId,l)}catch{continue}let u=se(l,d);r-=l.length-u.length,_(i,u)}}function ae(n,e,t,o){let r;try{r=ne(n,e,t,o)}catch{return o}return se(o,r)}var Te=f({module:"agent"}),S=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,o){this.pending.push({toolId:e,toolName:t,arguments:o})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async o=>{let r=this.registry.get(o.toolName),s=Date.now();if(!r)return{toolId:o.toolId,toolName:o.toolName,result:{output:`Error: unknown tool '${o.toolName}'`,isError:!0},elapsed:0};try{let i=await r.execute(this.ctx,o.arguments);return{toolId:o.toolId,toolName:o.toolName,result:i,elapsed:(Date.now()-s)/1e3}}catch(i){return Te.error({err:i},"agent operation failed"),{toolId:o.toolId,toolName:o.toolName,result:{output:`Error executing ${o.toolName}: ${F(i)}`,isError:!0},elapsed:(Date.now()-s)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};var xe=64e3,le=3,Ie=5e4,ce="The following deferred tools are available via ToolSearch.",he=class{announcedDeferred=[];client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new B;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;skillSection;skillDeltaFn;memoryRecallPromise;memoryRecallConsumed=!1;memoryRecallSettled=!1;memoryRecallValue;onMemoriesSurfaced;constructor(e){this.client=e.client,this.registry=e.registry,this.checker=e.checker,this.conversation=e.conversation,this.workDir=e.workDir,this.sessionId=e.sessionId??"",this.sessionFilePath=e.sessionId?U(e.workDir,e.sessionId):"",this.hookEngine=e.hookEngine,this.fileHistory=e.fileHistory,this.fileStateCache=e.fileStateCache,this.abortSignal=e.abortSignal,this.contextWindow=e.contextWindow??2e5,this.maxOutput=e.maxOutput??8192,this.recoveryState=e.recoveryState??new b,this.maxIterations=e.maxIterations??0,this.notificationFn=e.notificationFn,this.onLoopComplete=e.onLoopComplete,this.onPermissionRequest=e.onPermissionRequest,this.activeSkills=e.activeSkills??new Map,this.toolFilter=e.toolFilter,this.coordinatorActiveFn=e.coordinatorActiveFn,this.instructions=e.instructions??"",this.memoryContent=e.memoryContent??"",this.skillSection=e.skillSection??"",this.skillDeltaFn=e.skillDeltaFn,this.memoryRecallPromise=e.memoryRecallPromise,this.onMemoriesSurfaced=e.onMemoriesSurfaced,this.memoryRecallPromise?.then(t=>{this.memoryRecallValue=t,this.memoryRecallSettled=!0},()=>{this.memoryRecallSettled=!0})}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(i=>this.toolFilter?.(i.name)));let t=this.registry.listTools().map(i=>i.name),o=!1,r=0,s=0;await this.fireLifecycle("session_start");try{let i=!0;for(;i;){if(s++,this.maxIterations>0&&s>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",d=[],u=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let c=z(this.workDir);this.checker.planFilePath=c,this.conversation.addSystemReminder(Q(c,X(this.workDir),s))}this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(J(s));let k=this.registry.getDeferredToolNames();if(k.length>0&&(k.length!==this.announcedDeferred.length||k.some((a,v)=>a!==this.announcedDeferred[v])||!this.conversation.hasReminderContaining(ce))){let a=ce+' Their schemas are NOT loaded - use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas';a+=this.registry.mcpLoadingMode==="dispatch"?", then invoke them with the mcp_call tool":" before calling them",this.conversation.addSystemReminder(a+`:
|
|
236
|
+
`+k.join(`
|
|
237
|
+
`)),this.announcedDeferred=k}if(this.hookEngine)for(let c of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(c);if(this.notificationFn)for(let c of this.notificationFn())this.conversation.addSystemReminder(c);if(this.skillDeltaFn){let c=this.skillDeltaFn();c&&this.conversation.addSystemReminder(`The following skills became available:
|
|
238
|
+
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let R=await Y(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);R.message&&(yield{type:"compact",message:R.message,boundary:R.boundary}),R.compacted&&this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection);try{let c=this.client.stream(this.conversation,e,this.abortSignal);for await(let a of c){if(this.abortSignal?.aborted){i=!1;break}switch(a.type){case"text_delta":l+=a.text,yield{type:"stream_text",text:a.text};break;case"thinking_delta":yield{type:"thinking_text",text:a.text};break;case"thinking_complete":d.push({thinking:a.thinking,signature:a.signature}),yield{type:"thinking_complete",thinking:a.thinking,signature:a.signature};break;case"tool_call_start":break;case"tool_call_complete":u.push({toolUseId:a.toolId,toolName:a.toolName,arguments:a.arguments}),yield{type:"tool_use",toolName:a.toolName,toolId:a.toolId,args:a.arguments};break;case"stream_end":g=a.stopReason,p=a.usage,yield{type:"usage",usage:a.usage};break}}}catch(c){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(c instanceof L)try{let a=await j(this.conversation,this.client,this.recoveryState,t,e,this.sessionFilePath);this.conversation.clearUsageAnchor(),this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection),yield{type:"compact",message:"Auto-compacted due to context length: "+a.message,boundary:a.boundary};continue}catch{yield{type:"error",error:c};return}if(c instanceof M){let a=_e(E(A(c),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:a},await this.interruptibleSleep(a)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}yield{type:"error",error:c instanceof Error?c:new Error(JSON.stringify(c))};return}if(this.abortSignal?.aborted){l&&(this.conversation.addAssistantFull(l,d,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),g==="max_tokens")if(o){if(r<le){r++,this.conversation.addAssistantFull(l,d,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces."),yield{type:"retry",reason:`max_tokens recovery ${String(r)}/${String(le)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(xe),o=!0,l&&(this.conversation.addAssistantFull(l,d,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else r=0;if(this.conversation.addAssistantFull(l,d,u),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),u.length>0){let c=await this.executeTools(u);for(let h of c)yield h;let a=new Set;for(let h of u)re(h.toolName,h.arguments,this.workDir,this.sessionId)&&a.add(h.toolUseId);let v=[];for(let h of c)if(h.type==="tool_result"){let w={toolUseId:h.toolId,content:h.output,...h.contentBlocks?.length?{contentBlocks:h.contentBlocks}:{},isError:h.isError};if(w.content.length>Ie&&!a.has(h.toolId)){let P=ae(this.workDir,this.sessionId,h.toolId,w.content);P!==w.content&&_(w,P),a.add(h.toolId)}v.push(w)}ie(v,this.workDir,this.sessionId,a);let ue=u.some(h=>h.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(v),this.persistLastMessage(),this.abortSignal?.aborted){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"interrupted"};return}if(this.memoryRecallPromise&&!this.memoryRecallConsumed&&this.memoryRecallSettled){let h=this.memoryRecallValue;h?.reminder&&(this.conversation.addSystemReminder(h.reminder),this.onMemoriesSurfaced?.(h.paths)),this.memoryRecallConsumed=!0}if(ue){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},await this.fireLifecycle("turn_end")}else{if(i=!1,this.fileHistory){let c=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),c)}if(yield{type:"loop_complete",stopReason:g},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}}finally{await this.fireLifecycle("session_end")}}async fireLifecycle(e,t){if(!this.hookEngine)return;let o=await this.hookEngine.fire(e,{event:e,message:t});for(let r of o)r.output&&this.hookEngine.recordNotification(r.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let o=()=>{clearTimeout(r),t(!0)},r=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",o),t(!1)},e);this.abortSignal?.addEventListener("abort",o,{once:!0})})}async executeTools(e){let t=[],o=this.partitionToolCalls(e);for(let r of o){let s=await this.executeBatch(r.blocks,r.concurrent&&r.blocks.length>1);t.push(...s)}return t}partitionToolCalls(e){let t=[];for(let o of e){let r=this.registry.get(o.toolName),s=r?r.isConcurrencySafe?.(o.arguments??{})??r.category==="read":!1;s&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(o):t.push({concurrent:s,blocks:[o]})}return t}async executeBatch(e,t){let o=[],r=new S(this.registry,{workDir:this.workDir,abortSignal:this.abortSignal,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let s of e){if(this.abortSignal?.aborted){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:"Error: command interrupted",isError:!0,elapsed:0});continue}if(this.hookEngine){let u=await this.hookEngine.firePreToolHooks(s.toolName,s.arguments);if(u.rejected){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:`Rejected by hook: ${u.reason}`,isError:!0,elapsed:0});continue}}let l=this.registry.get(s.toolName)?.category??"command",d=this.checker.check(s.toolName,l,s.arguments);if(d.effect==="deny"){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:`Permission denied: ${d.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(d.effect==="ask"&&this.onPermissionRequest){let u=await this.onPermissionRequest(s.toolName,s.arguments,d);if(u==="deny"){o.push({type:"tool_result",toolName:s.toolName,toolId:s.toolUseId,output:C,isError:!0,elapsed:0});continue}u==="allowAlways"&&this.checker.allowAlways(s.toolName,s.arguments)}if(r.submit(s.toolUseId,s.toolName,s.arguments),!t){let u=await r.collectResults();for(let g of u)await this.processToolResult(g,e,o)}}if(t){let s=await r.collectResults();for(let i of s)await this.processToolResult(i,e,o)}return o}async processToolResult(e,t,o){if(!e.result.isError&&e.toolName==="ReadFile"&&!e.result.contentBlocks?.length){let r=t.find(i=>i.toolUseId===e.toolId),s=E(r?.arguments??{},"file_path");s&&this.recoveryState.recordFileRead(s,e.result.output)}if(o.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,...e.result.contentBlocks?.length?{contentBlocks:e.result.contentBlocks}:{},isError:e.result.isError,elapsed:e.elapsed}),this.hookEngine){let r=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let s of r)s.output&&this.hookEngine.recordNotification(s.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];W(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:D(t.toolUses)}:{},...t.toolResults?.length?{tool_results:O(t.toolResults)}:{}})}};function _e(n){if(!n)return 5e3;let e=parseInt(n,10);return Number.isNaN(e)?5e3:e*1e3}export{b as a,z as b,Ne as c,X as d,Me as e,Oe as f,Ue as g,He as h,he as i};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{I as y,L as u,N as T,R as f}from"./chunk-SIWLMWHH.js";import{b as g}from"./chunk-E55KH72M.js";var S=y({module:"mcp"}),p="mcp__",m="__";function a(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function _(e){return p+a(e)+m}function h(e,r){return _(e)+a(r)}var C=class{name;description;category="command";deferred=!0;mcpServerName;client;originalName;inputSchema;constructor(r,t,n){this.name=h(t,n.name),this.description=n.description,this.originalName=n.name,this.client=r,this.inputSchema=n.inputSchema,this.mcpServerName=t}mcpInputSchema(){return this.inputSchema??{}}setDeferLoading(r){this.deferred=r}schema(){return{name:this.name,description:this.description,input_schema:this.inputSchema}}async execute(r,t){try{return await this.client.callTool(this.originalName,t)}catch(n){return S.error({err:n},"mcp operation failed"),{output:`MCP tool error: ${T(n)}`,isError:!0}}}};function x(e,r){if(r==="string"&&typeof e=="number"&&Number.isFinite(e))return String(e);if((r==="integer"||r==="number")&&typeof e=="string"){let t=e.trim();if(t===""||!(r==="integer"?/^[+-]?\d+$/:/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/).test(t))return e;let s=r==="integer"?Number.parseInt(t,10):Number.parseFloat(t);return Number.isNaN(s)?e:s}if(r==="boolean"&&typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}return e}function d(e,r){if(typeof r!="object"||r===null)return e;let t=u(r),n=f(t,"type","");if(n==="object"&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let s=u(t.properties??{}),o={};for(let[i,c]of Object.entries(e))o[i]=i in s?d(c,s[i]):c;return o}if(n==="array"){let s=t.items??{},o=e;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.values(o);i.length===1&&Array.isArray(i[0])&&(o=i[0])}else typeof o=="string"&&(o=o.split(",").map(i=>i.trim()).filter(i=>i!==""));return Array.isArray(o)?o.map(i=>d(i,s)):o}return n!==""?x(e,n):e}function O(e,r){if(r.startsWith(p)){let t=r.slice(p.length),n=t.indexOf(m);if(n>=0)return a(t.slice(0,n))+m+a(t.slice(n+m.length))}return a(e)+m+a(r)}function M(e){return"mcpInputSchema"in e&&typeof e.mcpInputSchema=="function"}var b=class{constructor(r){this.registry=r}registry;name=g;description="Invoke a tool on a connected MCP server. Call ToolSearch first to load the tool's schema, then pass its arguments here exactly as that schema requires, using the same JSON types.";category="command";deferred=!1;schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{server:{type:"string",description:"MCP server name, e.g. 'linear'."},tool:{type:"string",description:"Full tool name as returned by ToolSearch, e.g. 'mcp__linear__create_issue'."},arguments:{type:"object",description:"The target tool's arguments. Must match that tool's input_schema exactly, including JSON types: bare numbers for integer fields, bare true/false for boolean fields, quoted strings for string fields, and plain JSON arrays for array fields."}},required:["server","tool","arguments"]}}}resolve(r,t){let n=this.registry.get(t)??this.registry.get(h(r,t));if(n)return n;let s=m+a(t),o=this.registry.listTools().filter(i=>i.name.startsWith(p)&&i.name.endsWith(s));return o.length===1?o[0]:void 0}availableNames(){return this.registry.listTools().filter(r=>r.name.startsWith(p)).map(r=>r.name).sort()}async execute(r,t){let n=f(t,"server",""),s=f(t,"tool","");if(s==="")return{output:"McpCall requires a 'tool' name",isError:!0};let o=this.resolve(n,s);if(!o){let c=this.availableNames(),l=c.length>0?c.join(", "):"(none connected)";return{output:`Unknown MCP tool '${s}' on server '${n}'. Available tools: ${l}`,isError:!0}}let i={};if(typeof t.arguments=="object"&&t.arguments!==null&&!Array.isArray(t.arguments)&&(i=u(t.arguments)),M(o)){let c=o.mcpInputSchema();if(Object.keys(c).length>0){let l=d(i,c);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(i=u(l))}}return o.execute(r,i)}};export{p as a,C as b,O as c,M as d,b as e};
|