@swifty.js/swifty 0.0.17 → 0.0.19
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/README.md +4 -4
- package/dist/{agent-F365IUO3.js → agent-ZLM7IKHU.js} +1 -1
- package/dist/anthropic-XJ5BOCJA.js +4 -0
- package/dist/{checker-GWE2YS7P.js → checker-4RL4BTDA.js} +1 -1
- package/dist/{chunk-WF7FXRNB.js → chunk-5J4WCPY4.js} +15 -15
- package/dist/chunk-A2VR3BC4.js +4 -0
- package/dist/{chunk-QU55DC4L.js → chunk-ASZMSWK5.js} +9 -9
- package/dist/chunk-KSCFIYHH.js +4 -0
- package/dist/chunk-T5HVHWMQ.js +386 -0
- package/dist/chunk-T74SUDUF.js +4 -0
- package/dist/main.js +230 -229
- package/dist/{openai-UJZ5Z3CV.js → openai-LZ7SDDQU.js} +1 -1
- package/dist/{server-G5QRJ3FV.js → server-AVSPCHLH.js} +16 -16
- package/dist/{tool-filter-334HOWZK.js → tool-filter-NO7I3HFD.js} +1 -1
- package/package.json +3 -3
- package/dist/anthropic-BUA7M3KV.js +0 -4
- package/dist/chunk-4WDW4YOO.js +0 -355
- package/dist/chunk-A3NIT2ZF.js +0 -4
- package/dist/chunk-GM65WMIB.js +0 -4
- package/dist/chunk-JMPU45A5.js +0 -4
package/README.md
CHANGED
|
@@ -70,11 +70,11 @@ pnpm dev
|
|
|
70
70
|
|
|
71
71
|
Swifty reads YAML configuration files from multiple locations, merged in order:
|
|
72
72
|
|
|
73
|
-
1. ~/.swifty/config.
|
|
74
|
-
2. .swifty/config.
|
|
75
|
-
3. .swifty/config.local.
|
|
73
|
+
1. ~/.swifty/config.yaml
|
|
74
|
+
2. .swifty/config.yaml (project root)
|
|
75
|
+
3. .swifty/config.local.yaml (project root, gitignored)
|
|
76
76
|
|
|
77
|
-
At least one provider must be configured. Example config.
|
|
77
|
+
At least one provider must be configured. Example config.yaml:
|
|
78
78
|
|
|
79
79
|
```yaml
|
|
80
80
|
providers:
|
|
@@ -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-
|
|
4
|
+
import{h as a}from"./chunk-5J4WCPY4.js";import"./chunk-ASZMSWK5.js";import"./chunk-FZPTNGTU.js";import"./chunk-ZM2V2A7B.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 $}from"./chunk-3USGFIWF.js";import{g as P}from"./chunk-H7VXSMJR.js";import{k as C}from"./chunk-ASZMSWK5.js";import{e as H,g as Y,h as R}from"./chunk-KSCFIYHH.js";import{b as N,c as K,d as M,e as W,f as F,g as G}from"./chunk-FZPTNGTU.js";import"./chunk-P276SKAC.js";import"./chunk-7MHXMDYC.js";import{C as w,I as O,J as v,K as j,L as B,M as I,N as _,O as U,g as L}from"./chunk-ZM2V2A7B.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";function D(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 J(o){return o.some(t=>t.defer_loading)}var x=O({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 t=R(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,s=new AbortController,r=setTimeout(()=>{s.abort()},z);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 h=await c.json(),{success:g,error:f,data:d}=await L(V,h);if(!g)return x.warn({message:f.message},"model context window schema validation failed"),0;let k=d.max_input_tokens;return Math.max(k,0)}catch(c){return x.error({err:c},"failed to fetch model context window"),0}finally{clearTimeout(r)}}function Q(){return!0}function S(o){return typeof o=="string"?[{type:"text",text:o}]:o}function X(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:j(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.content});t.push({role:"user",content:n})}else{if(t.length===0){t.push({role:"user",content:S(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(...S(e.content))):t.push({role:"user",content:S(e.content)})}return t}var q=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(t,e){let n=R(t);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:t.base_url}),this.model=t.model,this.thinking=t.thinking??!0,this.systemPrompt=e,this.maxOutputTokens=Y(t),this.contextWindow=H(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.maxOutputTokens=t}async*stream(t,e,n){let s=X(N(t.getMessages())),r=J(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});D(c),Z(s);let h={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?Q()&&(h.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):h.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let g=0,f=0,d=0,k=0,E="end_turn",T="",b="",A=!1;try{let l=this.client.messages.stream(h,{...n?{signal:n}:{},...r?{headers:{"anthropic-beta":$}}:{}}),p="",u="",m="";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,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"?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 y=JSON.parse(m);a=B(y)?I(y):{[v]:m}}catch(y){x.error({err:y},"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&&(E=i.delta.stop_reason),i.usage.output_tokens&&(f=i.usage.output_tokens,i.usage.input_tokens&&(g=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(d=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(k=i.usage.cache_creation_input_tokens));break}case"message_start":{g=i.message.usage.input_tokens,f=i.message.usage.output_tokens,d=i.message.usage.cache_read_input_tokens??0,k=i.message.usage.cache_creation_input_tokens??0;break}}yield{type:"stream_end",stopReason:E,usage:{inputTokens:g,outputTokens:f,cacheReadInputTokens:d,cacheCreationInputTokens:k}}}catch(l){throw x.error({err:l},"llm operation failed"),tt(l)}}};function Z(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 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 t=I(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 W(e,t?_(t):void 0)}return new K(`Anthropic API error (${_(o.status)}): ${o.message}`)}return new F(`Network error: ${U(o)}`)}export{q as AnthropicClient,X as buildAnthropicMessages,pt as fetchModelContextWindow,Z as markLastUserTailForCache,D as markToolsForCache,J 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}from"./chunk-
|
|
4
|
+
import{a,b,c,d,e}from"./chunk-T74SUDUF.js";import"./chunk-P276SKAC.js";import"./chunk-7MHXMDYC.js";import"./chunk-ZM2V2A7B.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};
|
|
@@ -1,19 +1,19 @@
|
|
|
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{b as L,c as
|
|
5
|
-
\u2026 (content truncated)`}var
|
|
4
|
+
import{b as L,c as D,d as O,f as U,l as W,m as Y,n as j}from"./chunk-ASZMSWK5.js";import{a as P,e as N,g as M}from"./chunk-FZPTNGTU.js";import{I as y,K as _,M as C,N as R,O as A,P as F,S as E}from"./chunk-ZM2V2A7B.js";import{readFile as xe}from"fs/promises";function T(s){return s?Math.floor(s.length/3.5):0}function B(s,e){if(e<=0||!s||T(s)<=e)return s;let t=Math.floor(e*3.5);return t<=0||t>=s.length?s:s.slice(0,t)+`
|
|
5
|
+
\u2026 (content truncated)`}var b=class{files=new Map;skills=new Map;recordFileRead(e,t){this.files.set(e,{path:e,content:t,timestamp:Date.now()})}recordSkillInvocation(e,t){this.skills.set(e,{name:e,body:t,timestamp:Date.now()})}snapshotFiles(e=5){return[...this.files.values()].sort((n,r)=>r.timestamp-n.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],n=this.snapshotFiles();if(n.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 o of n){let i=B(o.content,5e3),
|
|
7
|
+
`);for(let o of n){let i=B(o.content,5e3),l=new Date(o.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${o.path} (read ${l})
|
|
8
8
|
|
|
9
9
|
\`\`\`
|
|
10
10
|
${i}${i.endsWith(`
|
|
11
11
|
`)?"":`
|
|
12
12
|
`}\`\`\``)}}let r=this.snapshotSkills();if(r.length>0){let o=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
|
|
14
|
+
`);let l=!1;for(let h of r){let u=B(h.body,5e3),g=T(u)+T(h.name)+8;if(o+g>25e3)break;o+=g,i.push(`### ${h.name}
|
|
15
15
|
|
|
16
|
-
${u}`),
|
|
16
|
+
${u}`),l=!0}l&&t.push(i.join(`
|
|
17
17
|
|
|
18
18
|
`))}return e.length>0&&t.push(`## Available tools
|
|
19
19
|
|
|
@@ -24,7 +24,7 @@ You still have access to the following tools \u2014 call them directly when the
|
|
|
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 x}from"fs";import{join as $,resolve as H}from"path";var G=y({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 s=V[Math.floor(Math.random()*V.length)],e=q[Math.floor(Math.random()*q.length)],t=Date.now().toString(36).slice(-4);return`${s}-${e}-${t}`}var m=null;function K(s,e){let t=H(e,".swifty","plans");return H(s).startsWith(t+"/")}function z(s){if(m&&x(m))if(!K(m,s))G.warn({planPath:m,workDir:s},"current plan path is not under work dir");else return m;let e=$(s,".swifty","plans");me(e,{recursive:!0});let t=ge();return m=$(e,`${t}.md`),pe(m,"","utf-8"),m}function Me(){return!m||!x(m)?null:de(m,"utf-8")}function X(s){return!m||!x(m)?!1:K(m,s)?!0:(G.warn({planPath:m,workDir:s},"current plan path is not under work dir"),!1)}function Le(){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
|
|
|
@@ -72,7 +72,7 @@ from={worker name}: {what the worker reported}
|
|
|
72
72
|
|
|
73
73
|
When calling Agent, use subagent_type \`general-purpose\` or a specific agent definition. Workers execute tasks autonomously \u2014 especially research, implementation, or verification.
|
|
74
74
|
|
|
75
|
-
Workers have access to standard tools: ReadFile, EditFile, WriteFile, Bash, Grep, Glob, plus the team coordination tools (TaskCreate, TaskGet, TaskList, TaskUpdate, SendMessage). Anything you cannot do yourself, a worker can do for you.
|
|
75
|
+
Workers have access to standard tools: ReadFile, EditFile, WriteFile, Bash, PowerShell, Grep, Glob, plus the team coordination tools (TaskCreate, TaskGet, TaskList, TaskUpdate, SendMessage). Anything you cannot do yourself, a worker can do for you.
|
|
76
76
|
|
|
77
77
|
Because workers have Bash, git work belongs to them too. Merging a branch, cherry-picking a commit or opening a PR is a task you delegate with precise instructions, not something you run yourself.
|
|
78
78
|
|
|
@@ -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(s=1){return s<=1||(s-1)%5===0?fe:ye}var
|
|
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(s=1){return s<=1||(s-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,18 @@ 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
|
+
`,we="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.",ve=`## Exited Plan Mode
|
|
224
224
|
|
|
225
|
-
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,
|
|
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(s,e,t){let n=`Plan file: ${s}`;return e?n+=`
|
|
226
226
|
A plan file already exists at ${s}. You can read it and make incremental edits using the EditFile tool.`:n+=`
|
|
227
|
-
No plan file exists yet. You should create your plan at ${s} using the WriteFile tool.`,
|
|
227
|
+
No plan file exists yet. You should create your plan at ${s} using the WriteFile tool.`,(t-1)%5===0?ke.replace("%PLAN_FILE_INFO%",n):we.replace("%PLAN_PATH%",s)}function Ue(s,e){let t="";return e&&(t=` The plan file is located at ${s} if you need to reference it.`),ve.replace("%EXTRA%",t)}function We(s,e){return e?Re.replace("%PLAN_PATH%",s):""}import{writeFileSync as be,mkdirSync as Se}from"fs";import{join as te,resolve as Z}from"path";var Ee=y({module:"tool-result"}),ee=2e5;function oe(s,e){return te(s,".swifty","sessions",e||"default","tool-results")}function ne(s,e,t,n){let r=oe(s,e);Se(r,{recursive:!0});let o=te(r,t+".txt");try{be(o,n,{encoding:"utf-8",flag:"wx"})}catch(i){if(Ee.error({err:i},"tool-result operation failed"),F(i)&&"code"in i&&i.code!=="EEXIST")throw i}return o}var I=2e3;function se(s,e){let t=Math.floor(s.length/1024),n=s.slice(0,I),r=s.length>I,o=`<persisted-output>
|
|
228
228
|
`;return o+=`Output too large (${String(t)}KB). Full content saved to:
|
|
229
229
|
${e}
|
|
230
230
|
|
|
231
231
|
`,o+=`Preview (first 2KB):
|
|
232
232
|
${n}`,r&&(o+=`
|
|
233
233
|
...`),o+=`
|
|
234
|
-
</persisted-output>`,o}function
|
|
235
|
-
`+
|
|
236
|
-
`))}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:
|
|
237
|
-
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let
|
|
234
|
+
</persisted-output>`,o}function re(s,e,t,n){if(s!=="ReadFile"||!e)return!1;let r=e.file_path;return typeof r!="string"||!r?!1:Z(r).startsWith(Z(oe(t,n)))}function ie(s,e,t,n){let r=s.filter(l=>typeof l.content=="string"),o=r.reduce((l,h)=>l+(typeof h.content=="string"?h.content.length:0),0);if(o<=ee)return;let i=r.toSorted((l,h)=>R(h.content).length-R(l.content).length);for(let l of i){if(o<=ee)break;if(n?.has(l.toolUseId))continue;let h=R(l.content);if(h.length<=I)continue;let u;try{u=ne(e,t,l.toolUseId,h)}catch{continue}let g=se(h,u);o-=h.length-g.length,l.content=g}}function ae(s,e,t,n){let r;try{r=ne(s,e,t,n)}catch{return n}return se(n,r)}var Te=y({module:"agent"}),S=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,n){this.pending.push({toolId:e,toolName:t,arguments:n})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async n=>{let r=this.registry.get(n.toolName),o=Date.now();if(!r)return{toolId:n.toolId,toolName:n.toolName,result:{output:`Error: unknown tool '${n.toolName}'`,isError:!0},elapsed:0};try{let i=await r.execute(this.ctx,n.arguments);return{toolId:n.toolId,toolName:n.toolName,result:i,elapsed:(Date.now()-o)/1e3}}catch(i){return Te.error({err:i},"agent operation failed"),{toolId:n.toolId,toolName:n.toolName,result:{output:`Error executing ${n.toolName}: ${A(i)}`,isError:!0},elapsed:(Date.now()-o)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};var Ie=64e3,le=3,Pe=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 W;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;skillSection;skillDeltaFn;memoryRecallPromise;memoryRecallConsumed=!1;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?O(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}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),n=!1,r=0,o=0;await this.fireLifecycle("session_start");try{let i=!0;for(;i;){if(o++,this.maxIterations>0&&o>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",h=[],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),o))}this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(J(o));let k=this.registry.getDeferredToolNames();if(k.length>0&&(k.length!==this.announcedDeferred.length||k.some((a,w)=>a!==this.announcedDeferred[w])||!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+`:
|
|
235
|
+
`+k.join(`
|
|
236
|
+
`)),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:
|
|
237
|
+
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let v=await Y(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);v.message&&(yield{type:"compact",message:v.message,boundary:v.boundary}),v.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":h.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 M)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 N){let a=_e(E(C(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,h,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),g==="max_tokens")if(n){if(r<le){r++,this.conversation.addAssistantFull(l,h,[]),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?.(Ie),n=!0,l&&(this.conversation.addAssistantFull(l,h,[]),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,h,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 d of c)yield d;let a=new Set;for(let d of u)re(d.toolName,d.arguments,this.workDir,this.sessionId)&&a.add(d.toolUseId);let w=[];for(let d of c)if(d.type==="tool_result"){let f=d.output;typeof f=="string"&&f.length>Pe&&!a.has(d.toolId)&&(f=ae(this.workDir,this.sessionId,d.toolId,f),a.add(d.toolId)),w.push({toolUseId:d.toolId,content:f,isError:d.isError})}ie(w,this.workDir,this.sessionId,a);let ue=u.some(d=>d.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(w),this.persistLastMessage(),this.memoryRecallPromise&&!this.memoryRecallConsumed)try{let d=await Promise.race([this.memoryRecallPromise.then(f=>({done:!0,value:f})),Promise.resolve({done:!1,value:""})]);d.done&&(d.value&&this.conversation.addSystemReminder(d.value),this.memoryRecallConsumed=!0)}catch{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 n=await this.hookEngine.fire(e,{event:e,message:t});for(let r of n)r.output&&this.hookEngine.recordNotification(r.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let n=()=>{clearTimeout(r),t(!0)},r=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",n),t(!1)},e);this.abortSignal?.addEventListener("abort",n,{once:!0})})}async executeTools(e){let t=[],n=this.partitionToolCalls(e);for(let r of n){let o=await this.executeBatch(r.blocks,r.concurrent&&r.blocks.length>1);t.push(...o)}return t}partitionToolCalls(e){let t=[];for(let n of e){let o=(this.registry.get(n.toolName)?.category??"command")==="read";o&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(n):t.push({concurrent:o,blocks:[n]})}return t}async executeBatch(e,t){let n=[],r=new S(this.registry,{workDir:this.workDir,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let o of e){if(this.hookEngine){let u=await this.hookEngine.firePreToolHooks(o.toolName,o.arguments);if(u.rejected){n.push({type:"tool_result",toolName:o.toolName,toolId:o.toolUseId,output:`Rejected by hook: ${u.reason}`,isError:!0,elapsed:0});continue}}let l=this.registry.get(o.toolName)?.category??"command",h=this.checker.check(o.toolName,l,o.arguments);if(h.effect==="deny"){n.push({type:"tool_result",toolName:o.toolName,toolId:o.toolUseId,output:`Permission denied: ${h.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(h.effect==="ask"&&this.onPermissionRequest){let u=await this.onPermissionRequest(o.toolName,o.arguments,h);if(u==="deny"){n.push({type:"tool_result",toolName:o.toolName,toolId:o.toolUseId,output:P,isError:!0,elapsed:0});continue}u==="allowAlways"&&this.checker.allowAlways(o.toolName,o.arguments)}if(r.submit(o.toolUseId,o.toolName,o.arguments),!t){let u=await r.collectResults();for(let g of u)await this.processToolResult(g,e,n)}}if(t){let o=await r.collectResults();for(let i of o)await this.processToolResult(i,e,n)}return n}async processToolResult(e,t,n){if(!e.result.isError&&e.toolName==="ReadFile"&&typeof e.result.output=="string"){let r=t.find(i=>i.toolUseId===e.toolId),o=E(r?.arguments??{},"file_path");if(o)try{this.recoveryState.recordFileRead(o,await xe(o,"utf-8"))}catch{}}if(n.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,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 o of r)o.output&&this.hookEngine.recordNotification(o.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];U(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:L(t.toolUses)}:{},...t.toolResults?.length?{tool_results:D(t.toolResults)}:{}})}};function _e(s){if(!s)return 5e3;let e=parseInt(s,10);return Number.isNaN(e)?5e3:e*1e3}export{b as a,z as b,Me as c,X as d,Le as e,Ue as f,We as g,he as h};
|
|
@@ -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 T,b as f}from"./chunk-E55KH72M.js";var c=class{tools=new Map;discovered=new Set;mcpLoadingMode="eager";exposeToolSearch=!1;exposeMcpCall=!1;register(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}listTools(){return[...this.tools.values()]}getAllSchemas(e="anthropic"){let o=e==="openai"||e==="openai-compat",t=this.mcpLoadingMode==="native"&&!o,r=[];for(let s of this.tools.values()){if(s.name===T&&!this.exposeToolSearch||s.name===f&&!this.exposeMcpCall)continue;let i=!!s.deferred&&!this.discovered.has(s.name);if(i&&!t)continue;let n=s.schema();o?r.push({strict:!1,type:"function",name:n.name,description:n.description,parameters:n.input_schema,function:{name:n.name,description:n.description,parameters:n.input_schema}}):r.push(i?{...n,type:"custom",defer_loading:!0}:{...n,type:"custom"})}return r}getDeferredToolNames(){let e=[];for(let o of this.tools.values())o.deferred&&!this.discovered.has(o.name)&&e.push(o.name);return e.sort()}getDeferredTools(){return[...this.tools.values()].filter(e=>e.deferred&&!this.discovered.has(e.name))}searchDeferred(e,o=5){let t=e.toLowerCase(),r=[];for(let s of this.tools.values())if(!(!s.deferred||this.discovered.has(s.name))&&(s.name.toLowerCase().includes(t)||s.description.toLowerCase().includes(t))&&(r.push(s),r.length>=o))break;return r}findDeferredByNames(e){let o=new Map;for(let[t,r]of this.tools)o.set(t.toLowerCase(),r);return e.map(t=>o.get(t.toLowerCase())).filter(t=>t?.deferred??!1)}markDiscovered(e){this.discovered.add(e)}isDiscovered(e){return this.discovered.has(e)}};var h=new Set(["ExitPlanMode","Agent","AskUserQuestion","TaskStop"]),w=new Set(["TeamCreate","TeamDelete"]),m=new Set(["ExitPlanMode","Agent","AskUserQuestion","TaskStop"]),u=new Set(["ReadFile","Grep","Glob","Bash","PowerShell","EditFile","WriteFile","LoadSkill","SyntheticOutput","ToolSearch","EnterWorktree","ExitWorktree","McpCall"]);function g(a){return a.startsWith("mcp__")}function M(a,e,o,t,r=!1){let s=new Set(o??[]),i=new Set(e??[]),n=i.size>0&&!(i.size===1&&i.has("*")),p=new c;for(let d of a.listTools()){let l=d.name;if(g(l)){p.register(d);continue}h.has(l)||r&&m.has(l)||t&&!u.has(l)||s.has(l)||n&&!i.has(l)||p.register(d)}return p}var A="agent:builtin:fork";function k(a){let e=new c;for(let o of a.listTools())if(o.name==="Agent"&&"querySource"in o){let t=Object.create(Object.getPrototypeOf(o),Object.getOwnPropertyDescriptors(o));t.querySource=A,e.register(t)}else e.register(o);return e}export{c as a,h as b,w as c,m as d,u as e,M as f,A as g,k as h};
|
|
@@ -1,9 +1,9 @@
|
|
|
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{D as i,I as v,K as
|
|
4
|
+
import{D as i,I as v,K as p,O as _,S as U,e as M,f as x}from"./chunk-ZM2V2A7B.js";var T=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,o,s,n){this.history.push({role:"assistant",content:e,toolUses:[{toolUseId:o,toolName:s,arguments:n}]})}addAssistantMessageWithTools(e,o){this.history.push({role:"assistant",content:e,toolUses:o})}addAssistantFull(e,o,s){this.history.push({role:"assistant",content:e,thinkingBlocks:o.length>0?o:void 0,toolUses:s.length>0?s:void 0})}addToolResultMessage(e,o,s){this.history.push({role:"user",content:"",toolResults:[{toolUseId:e,content:o,isError:s}]})}addToolResultsMessage(e){this.history.push({role:"user",content:"",toolResults:e})}addSystemReminder(e){this.history.push({role:"user",content:`<system-reminder>
|
|
5
5
|
${e}
|
|
6
|
-
</system-reminder>`})}injectLongTermMemory(e,o,s=""){if(this.longTermMemoryInjected)return;let n=[];if(e&&n.push(`# SWIFTY.md
|
|
6
|
+
</system-reminder>`})}hasReminderContaining(e){return this.history.some(o=>o.role==="user"&&p(o.content).includes(e))}injectLongTermMemory(e,o,s=""){if(this.longTermMemoryInjected)return;let n=[];if(e&&n.push(`# SWIFTY.md
|
|
7
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
8
|
|
|
9
9
|
`+e),o&&n.push(`# Auto Memory
|
|
@@ -18,14 +18,14 @@ ${n.join(`
|
|
|
18
18
|
`)}
|
|
19
19
|
|
|
20
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:a}),this.longTermMemoryInjected=!0}len(){return this.history.length}truncateTo(e){e<0&&(e=0),!(e>this.history.length)&&(this.history=this.history.slice(0,e))}getMessages(){return[...this.history]}replaceWithCompacted(e,o){this.history=[{role:"user",content:e},...o],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,o,s,n){let r=e+s+n+o;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 z}from"crypto";import{readFileSync as I,writeFileSync as H,readdirSync as W,mkdirSync as J,statSync as X,existsSync as A,unlinkSync as
|
|
22
|
-
`;H(n,r,{flag:"a",encoding:"utf-8"})}function
|
|
23
|
-
`))if(n.trim())try{let r=JSON.parse(n),{success:l,data:a,error:c}=x(B,r);l?!a.content&&!(a.tool_uses?.length??0)&&!(a.tool_results?.length??0)||s.push(a):b.error({err:c},"session operation failed")}catch(r){b.error({err:r},"session operation failed")}return s}function j(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function F(t){return t?.map(e=>({toolUseId:e.tool_use_id,content:e.content,isError:e.is_error}))}function
|
|
21
|
+
</system-reminder>`;this.history.unshift({role:"user",content:a}),this.longTermMemoryInjected=!0}len(){return this.history.length}truncateTo(e){e<0&&(e=0),!(e>this.history.length)&&(this.history=this.history.slice(0,e))}getMessages(){return[...this.history]}replaceWithCompacted(e,o){this.history=[{role:"user",content:e},...o],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,o,s,n){let r=e+s+n+o;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 z}from"crypto";import{readFileSync as I,writeFileSync as H,readdirSync as W,mkdirSync as J,statSync as X,existsSync as A,unlinkSync as Ce,rmSync as xe}from"fs";import{join as y}from"path";var S="compact_boundary";var E=i.object({tool_use_id:i.string(),tool_name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),k=i.union([i.string(),i.array(i.record(i.string(),i.unknown()))]),N=i.object({tool_use_id:i.string(),content:k,is_error:i.boolean().optional()}),B=i.object({role:i.string(),content:k.default(""),timestamp:i.number(),type:i.string().optional(),tool_uses:i.array(E).optional(),tool_results:i.array(N).optional()}),G=i.object({role:i.string(),content:k,tool_uses:i.array(E).optional(),tool_results:i.array(N).optional()});function O(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 L(t){return(t??[]).map(e=>({tool_use_id:e.toolUseId,content:e.content,...e.isError?{is_error:!0}:{}}))}var V=i.object({summary:i.string(),keep:i.array(G)}),b=v({module:"session"});function R(t){return y(t,".swifty","sessions")}function Ie(t,e){return y(R(t),e+".jsonl")}function Ae(){let t=Date.now().toString(36),e=z(4).toString("hex");return`${t}-${e}`}function Q(t,e,o){let s=R(t);J(s,{recursive:!0});let n=y(s,`${e}.jsonl`),r=JSON.stringify(o)+`
|
|
22
|
+
`;H(n,r,{flag:"a",encoding:"utf-8"})}function Ee(t,e,o){Q(t,e,{role:"system",content:JSON.stringify(o),timestamp:Math.floor(Date.now()/1e3),type:S})}function Ne(t,e){let o=y(R(t),`${e}.jsonl`);if(!A(o))return[];let s=[];for(let n of I(o,"utf-8").split(`
|
|
23
|
+
`))if(n.trim())try{let r=JSON.parse(n),{success:l,data:a,error:c}=x(B,r);l?!a.content&&!(a.tool_uses?.length??0)&&!(a.tool_results?.length??0)||s.push(a):b.error({err:c},"session operation failed")}catch(r){b.error({err:r},"session operation failed")}return s}function j(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function F(t){return t?.map(e=>({toolUseId:e.tool_use_id,content:e.content,isError:e.is_error}))}function Be(t){let e=-1;for(let s=t.length-1;s>=0;s--)if(t[s].type===S){e=s;break}let o=[];if(e>=0){let s=null;try{let n=t[e].content,r=typeof n=="string"?JSON.parse(n):null;s=M(V,r)}catch{s=null}if(s){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
24
|
|
|
25
25
|
`+s.summary;s.keep.length>0&&(n+=`
|
|
26
26
|
|
|
27
|
-
Recent messages have been preserved verbatim.`),o.push({role:"user",content:n});for(let r of s.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||o.push({role:r.role,content:r.content,toolUses:j(r.tool_uses),toolResults:F(r.tool_results)})}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===S)continue;let l=P(r);l&&o.push(l)}return o}for(let s of t){let n=P(s);n&&o.push(n)}return o}function P(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:t.content,toolUses:j(t.tool_uses),toolResults:F(t.tool_results)}}function
|
|
28
|
-
`)){if(!d.trim())continue;let m;try{let g=JSON.parse(d);m=M(B,g)}catch(g){b.error({err:g},"session operation failed");continue}u++,!c&&m.role==="user"&&m.content&&(c=
|
|
27
|
+
Recent messages have been preserved verbatim.`),o.push({role:"user",content:n});for(let r of s.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||o.push({role:r.role,content:r.content,toolUses:j(r.tool_uses),toolResults:F(r.tool_results)})}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===S)continue;let l=P(r);l&&o.push(l)}return o}for(let s of t){let n=P(s);n&&o.push(n)}return o}function P(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:t.content,toolUses:j(t.tool_uses),toolResults:F(t.tool_results)}}function Oe(t){let e=R(t);if(!A(e))return[];let o=W(e).filter(n=>n.endsWith(".jsonl")),s=[];for(let n of o){let r=y(e,n),l=X(r),a=n.replace(".jsonl",""),c="",u=0;try{for(let d of I(r,"utf-8").split(`
|
|
28
|
+
`)){if(!d.trim())continue;let m;try{let g=JSON.parse(d);m=M(B,g)}catch(g){b.error({err:g},"session operation failed");continue}u++,!c&&m.role==="user"&&m.content&&(c=p(m.content).slice(0,100))}}catch(d){b.error({err:d},"session operation failed");continue}s.push({id:a,firstMessage:c,messageCount:u,size:l.size,modTime:l.mtime})}return s.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),s}var D=3,Z=3,ee="[earlier conversation truncated for compaction retry]",te=3.5,oe=1e4,se=5,ne=4e4,re=2,ie=2e4,ae=13e3,le=3e3;function $(t,e,o=!1){return t-Math.min(e,ie)-(o?le:ae)}var q=class{consecutiveFailures=0},ce=7e3;function Y(t){if(typeof t=="string")return t.length;let e=0;for(let o of t)o.type==="text"?e+=U(o,"text").length:o.type==="image"&&(e+=ce);return e}function w(t){let e=0;for(let o of t){if(e+=Y(o.content),o.toolUses&&(e+=JSON.stringify(o.toolUses).length),o.toolResults)for(let s of o.toolResults)e+=Y(s.content);if(o.thinkingBlocks)for(let s of o.thinkingBlocks)e+=s.thinking.length}return Math.ceil(e/te)}function ue(t){return w(t.getMessages())}function C(t){return w([t])}function de(t){return t.role==="user"&&!!t.toolResults&&t.toolResults.length>0}function me(t){let e=0,o=0,s=t.length;for(let n=t.length-1;n>=0;n--){let r=C(t[n]);if(o>0&&e+r>ne||(s=n,e+=r,o++,e>=oe||o>=se))break}return s=he(t,s),s}function he(t,e){if(e<=0||e>=t.length||!de(t[e]))return e;let o=new Set((t[e].toolResults??[]).map(s=>s.toolUseId));for(let s=e-1;s>=0;s--){let n=t[s];if(n.role==="assistant"&&n.toolUses?.some(r=>o.has(r.toolUseId)))return s}return e}function ge(t,e){let o=e??t.usageAnchorState();if(!o)return ue(t);let s=t.getMessages(),n=Math.min(o.anchorCount,s.length);return o.baselineTokens+w(s.slice(n))}async function $e(t,e,o,s,n,r,l,a,c=""){let u=ge(t),d=$(o,s),m=$(o,s,!0);if(u<d)return{compacted:!1,message:""};if(!(u>=m)&&n.consecutiveFailures>=D)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(D)} consecutive failures`};try{let f=await K(t,e,r,l,a,c);return n.consecutiveFailures=0,f}catch(f){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${_(f)}`}}}async function qe(t,e,o,s,n,r=""){return K(t,e,o,s,n,r)}var fe=`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
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
30
|
|
|
31
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:
|
|
@@ -110,7 +110,7 @@ Here's an example of how your output should be structured:
|
|
|
110
110
|
|
|
111
111
|
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function pe(t){return fe+`
|
|
112
112
|
|
|
113
|
-
`+t}function ye(t){let e=[],o=[],s=!1;for(let n of t)n.role==="assistant"&&s&&o.length>0&&(e.push(o),o=[]),o.push(n),s=!!(n.toolResults&&n.toolResults.length>0);return o.length>0&&e.push(o),e}function Te(t,e){let o=ye(t);if(o.length<2)return null;let s;if(e>0){let r=0;s=0;for(let l of o)if(r+=l.reduce((a,c)=>a+C(c),0),s++,r>=e)break}else s=Math.max(1,Math.floor(o.length/5));if(s=Math.min(s,o.length-1),s<1)return null;let n=o.slice(s).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:ee}),n}function be(t){return t.map(e=>{let o=`[${e.role}]: ${
|
|
113
|
+
`+t}function ye(t){let e=[],o=[],s=!1;for(let n of t)n.role==="assistant"&&s&&o.length>0&&(e.push(o),o=[]),o.push(n),s=!!(n.toolResults&&n.toolResults.length>0);return o.length>0&&e.push(o),e}function Te(t,e){let o=ye(t);if(o.length<2)return null;let s;if(e>0){let r=0;s=0;for(let l of o)if(r+=l.reduce((a,c)=>a+C(c),0),s++,r>=e)break}else s=Math.max(1,Math.floor(o.length/5));if(s=Math.min(s,o.length-1),s<1)return null;let n=o.slice(s).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:ee}),n}function be(t){return t.map(e=>{let o=`[${e.role}]: ${p(e.content)}`;return e.toolUses&&(o+=`
|
|
114
114
|
[tools: ${e.toolUses.map(s=>s.toolName).join(", ")}]`),o}).join(`
|
|
115
115
|
|
|
116
116
|
`)}async function Re(t,e,o){let s=e;for(let n=0;;n++){let r=be(s),l=new T;l.addUserMessage(pe(r));try{let a="",c=t.stream(l,o);for await(let d of c)d.type==="text_delta"&&(a+=d.text);let u=/<summary>([\s\S]*?)<\/summary>/.exec(a);return u?u[1].trim():a}catch(a){let c=a instanceof Error?a.message.toLowerCase():"";if(!(c.includes("prompt")&&c.includes("long")||c.includes("too many")||c.includes("context_length"))||n>=Z)throw a;let d=s.reduce((g,f)=>g+C(f),0)/5,m=Te(s,d);if(!m)throw a;s=m}}}async function K(t,e,o,s,n,r=""){let l=t.getMessages(),a=me(l);if(a<=0||a<re)return{compacted:!1,message:`Compaction skipped: only ${String(a)} message(s) to summarize, kept verbatim`};let c=l.slice(0,a),u=l.slice(a),d=await Re(e,c,n),m=o?o.buildRecoveryAttachment(s):"",g=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
@@ -123,4 +123,4 @@ If you need specific details from before compaction (code snippets, error messag
|
|
|
123
123
|
|
|
124
124
|
---
|
|
125
125
|
|
|
126
|
-
${m}`),t.replaceWithCompacted(g,u);let f=u.filter(h=>(h.role==="user"||h.role==="assistant")&&(h.content||(h.toolUses?.length??0)||(h.toolResults?.length??0))).map(h=>({role:h.role,content:h.content,...h.toolUses?.length?{tool_uses:O(h.toolUses)}:{},...h.toolResults?.length?{tool_results:L(h.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(c.length)} messages into summary (${String(d.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:d,keep:f}}}export{T as a,O as b,L as c,
|
|
126
|
+
${m}`),t.replaceWithCompacted(g,u);let f=u.filter(h=>(h.role==="user"||h.role==="assistant")&&(h.content||(h.toolUses?.length??0)||(h.toolResults?.length??0))).map(h=>({role:h.role,content:h.content,...h.toolUses?.length?{tool_uses:O(h.toolUses)}:{},...h.toolResults?.length?{tool_results:L(h.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(c.length)} messages into summary (${String(d.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:d,keep:f}}}export{T as a,O as b,L as c,Ie as d,Ae as e,Q as f,Ee as g,Ne as h,Be as i,Oe as j,$ as k,q as l,$e as m,qe as n};
|
|
@@ -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 x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as p,c as u}from"./chunk-ZM2V2A7B.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-XJ5BOCJA.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};
|