@swifty.js/swifty 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-NX7ND57K.js → agent-KIMFD4RH.js} +1 -1
- package/dist/anthropic-K3YA64W4.js +4 -0
- package/dist/checker-RSBYV6EP.js +4 -0
- package/dist/chunk-32AZCTP4.js +4 -0
- package/dist/chunk-5CPQ6RWA.js +4 -0
- package/dist/chunk-6AOZQ3ON.js +354 -0
- package/dist/{chunk-GQ2COSTQ.js → chunk-6ZXBZB2Y.js} +1 -1
- package/dist/chunk-A3NIT2ZF.js +4 -0
- package/dist/{chunk-RNUCVDX2.js → chunk-CYMOBNZF.js} +26 -24
- package/dist/chunk-E55KH72M.js +4 -0
- package/dist/{chunk-MSJOPX6X.js → chunk-F24VPQ2I.js} +1 -1
- package/dist/{chunk-M5AOLYFS.js → chunk-J5LWUHF6.js} +14 -14
- package/dist/chunk-MNZYPUTY.js +4 -0
- package/dist/glob.wasm +0 -0
- package/dist/main.js +204 -203
- package/dist/{openai-L6LWA2MU.js → openai-HEG2P5DF.js} +1 -1
- package/dist/{server-TYLDPSLT.js → server-EXSHPT5H.js} +20 -20
- package/dist/tool-filter-334HOWZK.js +4 -0
- package/package.json +3 -3
- package/dist/anthropic-EAEDMTTA.js +0 -4
- package/dist/builtin/fullstack-interview/SKILL.md +0 -105
- package/dist/builtin/teach-me/SKILL.md +0 -399
- package/dist/builtin/teach-me/references/pedagogy.md +0 -244
- package/dist/checker-NNTNXNYP.js +0 -4
- package/dist/chunk-QNFMJDDO.js +0 -354
- package/dist/chunk-R7VREEYH.js +0 -4
- package/dist/chunk-UBV5T4TV.js +0 -4
- package/dist/glob_addon.node +0 -0
- package/dist/tool-filter-ERUPKZYV.js +0 -4
|
@@ -1,7 +1,7 @@
|
|
|
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 y,O as _,S as U,e as M,f as x}from"./chunk-
|
|
4
|
+
import{D as i,I as v,K as y,O as _,S as U,e as M,f as x}from"./chunk-J5LWUHF6.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
6
|
</system-reminder>`})}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.
|
|
@@ -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,n=[];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 r=s.schema();o?n.push({strict:!1,type:"function",name:r.name,description:r.description,parameters:r.input_schema,function:{name:r.name,description:r.description,parameters:r.input_schema}}):n.push(i?{...r,type:"custom",defer_loading:!0}:{...r,type:"custom"})}return n}getDeferredToolNames(){let e=[];for(let o of this.tools.values())o.deferred&&!this.discovered.has(o.name)&&e.push(o.name);return e}getDeferredTools(){return[...this.tools.values()].filter(e=>e.deferred&&!this.discovered.has(e.name))}searchDeferred(e,o=5){let t=e.toLowerCase(),n=[];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))&&(n.push(s),n.length>=o))break;return n}findDeferredByNames(e){let o=new Map;for(let[t,n]of this.tools)o.set(t.toLowerCase(),n);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"]),M=new Set(["TeamCreate","TeamDelete"]),m=new Set(["ExitPlanMode","Agent","AskUserQuestion","TaskStop"]),u=new Set(["ReadFile","Grep","Glob","Bash","EditFile","WriteFile","LoadSkill","SyntheticOutput","ToolSearch","EnterWorktree","ExitWorktree","McpCall"]);function g(a){return a.startsWith("mcp__")}function k(a,e,o,t,n=!1){let s=new Set(o??[]),i=new Set(e??[]),r=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)||n&&m.has(l)||t&&!u.has(l)||s.has(l)||r&&!i.has(l)||p.register(d)}return p}var A="agent:builtin:fork";function E(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,M as c,m as d,u as e,k as f,A as g,E as h};
|
|
@@ -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
|
|
4
|
+
import{b as L,c as O,d as D,f as U,l as W,m as Y,n as j}from"./chunk-6ZXBZB2Y.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 w,O as A,P as F,S}from"./chunk-J5LWUHF6.js";import{readFile as Ee}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
5
|
\u2026 (content truncated)`}var v=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=
|
|
7
|
+
`);for(let o of n){let i=B(o.content,5e3),a=new Date(o.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${o.path} (read ${a})
|
|
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 a=!1;for(let
|
|
14
|
+
`);let a=!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
|
-
${
|
|
16
|
+
${u}`),a=!0}a&&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
|
|
27
|
+
`))}};import{readFileSync as de,writeFileSync as pe,mkdirSync as me,existsSync as E}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&&E(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 Ne(){return!m||!E(m)?null:de(m,"utf-8")}function X(s){return!m||!E(m)?!1:K(m,s)?!0:(G.warn({planPath:m,workDir:s},"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
|
|
|
@@ -82,12 +82,12 @@ Because workers have Bash, git work belongs to them too. Merging a branch, cherr
|
|
|
82
82
|
|
|
83
83
|
Most tasks break down into four phases:
|
|
84
84
|
|
|
85
|
-
| Phase
|
|
86
|
-
|
|
87
|
-
| Research
|
|
88
|
-
| Synthesis
|
|
89
|
-
| Implementation | Workers
|
|
90
|
-
| Verification
|
|
85
|
+
| Phase | Who | Purpose |
|
|
86
|
+
|----------------|-----------------------|-------------------------------------------------------------------|
|
|
87
|
+
| Research | Workers (parallel) | Investigate codebase, find files, understand the problem |
|
|
88
|
+
| Synthesis | **You** (coordinator) | Read findings, understand the problem, craft implementation specs |
|
|
89
|
+
| Implementation | Workers | Make targeted changes per spec, commit |
|
|
90
|
+
| Verification | Workers. | Test that changes work |
|
|
91
91
|
|
|
92
92
|
### Concurrency
|
|
93
93
|
|
|
@@ -138,13 +138,13 @@ Include a brief purpose so workers can calibrate depth and emphasis:
|
|
|
138
138
|
|
|
139
139
|
### Choose continue vs. spawn by context overlap
|
|
140
140
|
|
|
141
|
-
| Situation
|
|
142
|
-
|
|
143
|
-
| Research explored exactly the files that need editing | **Continue** (SendMessage) | Worker already has the files in context
|
|
144
|
-
| Research was broad but implementation is narrow
|
|
145
|
-
| Correcting a failure or extending recent work
|
|
146
|
-
| Verifying code a different worker just wrote
|
|
147
|
-
| First attempt used the wrong approach entirely
|
|
141
|
+
| Situation | Mechanism | Why |
|
|
142
|
+
|-------------------------------------------------------|----------------------------|----------------------------------------------|
|
|
143
|
+
| Research explored exactly the files that need editing | **Continue** (SendMessage) | Worker already has the files in context |
|
|
144
|
+
| Research was broad but implementation is narrow | **Spawn fresh** (Agent) | Avoid dragging along exploration noise |
|
|
145
|
+
| Correcting a failure or extending recent work | **Continue** | Worker has the error context |
|
|
146
|
+
| Verifying code a different worker just wrote | **Spawn fresh** | Verifier should see the code with fresh eyes |
|
|
147
|
+
| First attempt used the wrong approach entirely | **Spawn fresh** | Wrong-approach context pollutes the retry |
|
|
148
148
|
|
|
149
149
|
### Prompt tips
|
|
150
150
|
|
|
@@ -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.`,
|
|
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 Q=`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,16 +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
|
+
`,ke="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%`,
|
|
225
|
+
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,ve="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 Z(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.`,t===1||Math.floor((t-1)/5)%5===0?
|
|
227
|
+
No plan file exists yet. You should create your plan at ${s} using the WriteFile tool.`,t===1||Math.floor((t-1)/5)%5===0?Q.replace("%PLAN_FILE_INFO%",n):ke.replace("%PLAN_PATH%",s)}function De(s,e){let t="";return e&&(t=` The plan file is located at ${s} if you need to reference it.`),we.replace("%EXTRA%",t)}function Ue(s,e){return e?ve.replace("%PLAN_PATH%",s):""}import{writeFileSync as Re,mkdirSync as be}from"fs";import{join as oe,resolve as ee}from"path";var Se=y({module:"tool-result"}),te=2e5;function ne(s,e){return oe(s,".swifty","sessions",e||"default","tool-results")}function se(s,e,t,n){let r=ne(s,e);be(r,{recursive:!0});let o=oe(r,t+".txt");try{Re(o,n,{encoding:"utf-8",flag:"wx"})}catch(i){if(Se.error({err:i},"tool-result operation failed"),F(i)&&"code"in i&&i.code!=="EEXIST")throw i}return o}var x=2e3;function re(s,e){let t=Math.floor(s.length/1024),n=s.slice(0,x),r=s.length>x,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
|
-
`+
|
|
234
|
+
</persisted-output>`,o}function ie(s,e,t,n){if(s!=="ReadFile"||!e)return!1;let r=e.file_path;return typeof r!="string"||!r?!1:ee(r).startsWith(ee(ne(t,n)))}function ae(s,e,t,n){let r=s.filter(a=>typeof a.content=="string"),o=r.reduce((a,h)=>a+(typeof h.content=="string"?h.content.length:0),0);if(o<=te)return;let i=r.toSorted((a,h)=>w(h.content).length-w(a.content).length);for(let a of i){if(o<=te)break;if(n?.has(a.toolUseId))continue;let h=w(a.content);if(h.length<=x)continue;let u;try{u=se(e,t,a.toolUseId,h)}catch{continue}let g=re(h,u);o-=h.length-g.length,a.content=g}}function le(s,e,t,n){let r;try{r=se(s,e,t,n)}catch{return n}return re(n,r)}var Te=y({module:"agent"}),R=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 xe=64e3,ce=3,Ie=5e4,he=class{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?D(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 v,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 a="",h=[],u=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let c=z(this.workDir);this.checker.planFilePath=c,this.conversation.addSystemReminder(Z(c,X(this.workDir),o))}this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(J(o));let I=this.registry.getDeferredToolNames();if(I.length>0){let c='The following deferred tools are available via ToolSearch. Their schemas are NOT loaded - use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas';c+=this.registry.mcpLoadingMode==="dispatch"?", then invoke them with the McpCall tool":" before calling them",this.conversation.addSystemReminder(c+`:
|
|
235
|
+
`+I.join(`
|
|
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 k=await Y(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);k.message&&(yield{type:"compact",message:k.message,boundary:k.boundary}),k.compacted&&this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection);try{let c=this.client.stream(this.conversation,e,this.abortSignal);for await(let l of c){if(this.abortSignal?.aborted){i=!1;break}switch(l.type){case"text_delta":a+=l.text,yield{type:"stream_text",text:l.text};break;case"thinking_delta":yield{type:"thinking_text",text:l.text};break;case"thinking_complete":h.push({thinking:l.thinking,signature:l.signature}),yield{type:"thinking_complete",thinking:l.thinking,signature:l.signature};break;case"tool_call_start":break;case"tool_call_complete":u.push({toolUseId:l.toolId,toolName:l.toolName,arguments:l.arguments}),yield{type:"tool_use",toolName:l.toolName,toolId:l.toolId,args:l.arguments};break;case"stream_end":g=l.stopReason,p=l.usage,yield{type:"usage",usage:l.usage};break}}}catch(c){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(c instanceof M)try{let l=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: "+l.message,boundary:l.boundary};continue}catch{yield{type:"error",error:c};return}if(c instanceof N){let l=Pe(S(C(c),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:l},await this.interruptibleSleep(l)){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){a&&(this.conversation.addAssistantFull(a,h,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",a),g==="max_tokens")if(n){if(r<ce){r++,this.conversation.addAssistantFull(a,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(ce)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(xe),n=!0,a&&(this.conversation.addAssistantFull(a,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(a,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 l=new Set;for(let d of u)ie(d.toolName,d.arguments,this.workDir,this.sessionId)&&l.add(d.toolUseId);let b=[];for(let d of c)if(d.type==="tool_result"){let f=d.output;typeof f=="string"&&f.length>Ie&&!l.has(d.toolId)&&(f=le(this.workDir,this.sessionId,d.toolId,f),l.add(d.toolId)),b.push({toolUseId:d.toolId,content:f,isError:d.isError})}ae(b,this.workDir,this.sessionId,l);let ue=u.some(d=>d.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(b),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=a.length>60?a.slice(0,60)+"...":a;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 R(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 a=this.registry.get(o.toolName)?.category??"command",h=this.checker.check(o.toolName,a,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=S(r?.arguments??{},"file_path");if(o)try{this.recoveryState.recordFileRead(o,await Ee(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:O(t.toolResults)}:{}})}};function Pe(s){if(!s)return 5e3;let e=parseInt(s,10);return Number.isNaN(e)?5e3:e*1e3}export{v as a,z as b,Ne as c,X as d,Me as e,De as f,Ue as g,he as h};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{a as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as u,c as m}from"./chunk-
|
|
4
|
+
import{a as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as u,c as m}from"./chunk-J5LWUHF6.js";import{existsSync as E,readFileSync as $}from"fs";import{homedir as I}from"os";import{join as l}from"path";function p(e){return!!e._zod}function c(e,n){return p(e)?u(e,n):e.safeParse(n)}async function ee(e,n){return p(e)?await m(e,n):await e.safeParseAsync(n)}function oe(e){if(!e)return;let n;if(p(e)?n=e._zod?.def?.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function ne(e){if(p(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(r!==void 0)return r}var g=S({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function N(e){return _.has(e)}var _=new Set(Object.keys(A)),d=class extends Error{constructor(n){super(n),this.name="ConfigError"}},P=o.object({name:o.string(),protocol:o.enum(["anthropic","openai","openai-compat"]),base_url:o.string(),model:o.string(),api_key:o.string().optional(),thinking:o.boolean().optional(),context_window:o.coerce.number().optional(),max_output_tokens:o.coerce.number().optional()}),V=[["1m",1e6],["gpt-4.1",1e6],["gpt-4o",128e3],["gpt-4-turbo",128e3],["o1",2e5],["o3",2e5],["o4",2e5],["gpt-3.5",16385],["claude",2e5]];function j(e){let n=e.toLowerCase();for(let[t,r]of V)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function de(e){return e.context_window&&e.context_window>0?e.context_window:j(e.model)}var w=new Map;async function pe(e,n){if(e.context_window&&e.context_window>0)return e.context_window;if(e.protocol==="anthropic"){let t=`${e.name}-${e.model}`,r=w.get(t);if(r===void 0){try{r=await(n??(await import("./anthropic-K3YA64W4.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(t,r)}if(r&&r>0)return r}return j(e.model)}function ue(e){return e.max_output_tokens&&e.max_output_tokens>0?e.max_output_tokens:e.thinking?64e3:8192}function me(e){if(e.api_key)return e.api_key;let n=N(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var O=o.object({name:o.string(),command:o.string().optional(),args:o.array(o.string()).optional(),url:o.string().optional(),transport:o.string().optional(),headers:o.record(o.string(),o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),z=o.object({id:o.string().optional(),event:o.string(),condition:o.string().optional(),action:o.object({type:o.string(),command:o.string().optional(),url:o.string().optional(),method:o.string().optional(),prompt:o.string().optional()}),reject:o.boolean().optional(),once:o.boolean().optional(),async:o.boolean().optional(),on_error:o.string().optional()}),M=o.object({enabled:o.boolean().optional(),auto_allow:o.boolean().optional(),network_enabled:o.boolean().optional()}),T=o.looseObject({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(O).default([]),hooks:o.array(z).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function Y(e){return typeof e=="object"&&e!==null}function C(e){let n=$(e,"utf-8"),t=x.load(n);if(!Y(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=c(T,t);if(r.success){let a=r.data;return{providers:a.providers,permission_mode:a.permission_mode,mcp_servers:a.mcp_servers,hooks:a.hooks}}g.error({error:r.error},"config error");let i=[],s,f=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=c(o.array(P),t.providers);a.success&&(i=a.data)}if("permission_mode"in t&&typeof t.permission_mode=="string"&&(s=t.permission_mode),"mcp_servers"in t){let a=c(o.array(O),t.mcp_servers);a.success&&(f=a.data)}if("hooks"in t){let a=c(o.array(z),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=c(M,t.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in t&&(b=!!t.enable_coordinator_mode),"enable_fork"in t&&(h=!!t.enable_fork),{providers:i,permission_mode:s,mcp_servers:f,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(e,n){if(n.providers.length>0&&(e.providers=n.providers),n.permission_mode&&(e.permission_mode=n.permission_mode),n.mcp_servers.length>0){let t=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];t.set(i.name,r)}for(let r of n.mcp_servers){let i=t.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),t.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...n.hooks],n.sandbox&&(e.sandbox={...e.sandbox,...n.sandbox}),n.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),n.enable_fork!==void 0&&(e.enable_fork=n.enable_fork),e}function k(e){if(e.providers.length===0)throw new d("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"];for(let t=0;t<e.providers.length;t++){let r=e.providers[t],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=n.filter(f=>!(f in i));if(s.length>0)throw new d(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new d(`Provider #${String(t+1)}: invalid protocol '${r.protocol}', MUST be one of: ${Array.from(_).join(", ")}`)}}function _e(e){if(e){let s=C(e);return k(s),s}let n=process.cwd(),t=I(),r=[l(t,".swifty","config.yml"),l(t,".swifty","config.yaml"),l(n,".swifty","config.yml"),l(n,".swifty","config.yaml"),l(n,".swifty","config.local.yml"),l(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let f=C(s);i?i=K(i,f):i=f}if(!i)throw new d("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{c as a,ee as b,oe as c,ne as d,de as e,pe as f,ue as g,me as h,ge as i,_e as j};
|