@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.
@@ -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-M5AOLYFS.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>
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 M,c as L,d as O,f as D,l as U,m as W,n as Y}from"./chunk-GQ2COSTQ.js";import{a as I,e as F,g as N}from"./chunk-FZPTNGTU.js";import{I as y,K as P,M as _,N as w,O as A,P as C,S}from"./chunk-M5AOLYFS.js";import{readFile as Ee}from"fs/promises";function E(s){return s?Math.floor(s.length/3.5):0}function j(s,e){if(e<=0||!s||E(s)<=e)return s;let t=Math.floor(e*3.5);return t<=0||t>=s.length?s:s.slice(0,t)+`
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=j(o.content,5e3),a=new Date(o.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${o.path} (read ${a})
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 c of r){let h=j(c.body,5e3),g=E(h)+E(c.name)+8;if(o+g>25e3)break;o+=g,i.push(`### ${c.name}
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
- ${h}`),a=!0}a&&t.push(i.join(`
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 he,writeFileSync as de,mkdirSync as pe,existsSync as T}from"fs";import{join as B,resolve as $}from"path";var q=y({module:"plan-file"}),H=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],V=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function me(){let s=H[Math.floor(Math.random()*H.length)],e=V[Math.floor(Math.random()*V.length)],t=Date.now().toString(36).slice(-4);return`${s}-${e}-${t}`}var m=null;function G(s,e){let t=$(e,".swifty","plans");return $(s).startsWith(t+"/")}function K(s){if(m&&T(m))if(!G(m,s))q.warn({planPath:m,workDir:s},"current plan path is not under work dir");else return m;let e=B(s,".swifty","plans");pe(e,{recursive:!0});let t=me();return m=B(e,`${t}.md`),de(m,"","utf-8"),m}function Fe(){return!m||!T(m)?null:he(m,"utf-8")}function z(s){return!m||!T(m)?!1:G(m,s)?!0:(q.warn({planPath:m,workDir:s},"current plan path is not under work dir"),!1)}function Ne(){m=null}var ge=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
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 | 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 |
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 | 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 |
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.`,fe="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 X(s=1){return s<=1||(s-1)%5===0?ge:fe}var J=`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.
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
- `,ye="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.",ke=`## Exited Plan Mode
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%`,we="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+=`
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?J.replace("%PLAN_FILE_INFO%",n):ye.replace("%PLAN_PATH%",s)}function Oe(s,e){let t="";return e&&(t=` The plan file is located at ${s} if you need to reference it.`),ke.replace("%EXTRA%",t)}function De(s,e){return e?we.replace("%PLAN_PATH%",s):""}import{writeFileSync as ve,mkdirSync as Re}from"fs";import{join as te,resolve as Z}from"path";var be=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);Re(r,{recursive:!0});let o=te(r,t+".txt");try{ve(o,n,{encoding:"utf-8",flag:"wx"})}catch(i){if(be.error({err:i},"tool-result operation failed"),C(i)&&"code"in i&&i.code!=="EEXIST")throw i}return o}var x=2e3;function se(s,e){let t=Math.floor(s.length/1024),n=s.slice(0,x),r=s.length>x,o=`<persisted-output>
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 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(a=>typeof a.content=="string"),o=r.reduce((a,c)=>a+(typeof c.content=="string"?c.content.length:0),0);if(o<=ee)return;let i=r.toSorted((a,c)=>w(c.content).length-w(a.content).length);for(let a of i){if(o<=ee)break;if(n?.has(a.toolUseId))continue;let c=w(a.content);if(c.length<=x)continue;let h;try{h=ne(e,t,a.toolUseId,c)}catch{continue}let g=se(c,h);o-=c.length-g.length,a.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 Se=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 Se.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 Te=64e3,le=3,xe=5e4,ce=class{client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new U;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 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="",c=[],h=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let u=K(this.workDir);this.checker.planFilePath=u,this.conversation.addSystemReminder(Q(u,z(this.workDir),o))}if(this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(X(o)),this.hookEngine)for(let u of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(u);if(this.notificationFn)for(let u of this.notificationFn())this.conversation.addSystemReminder(u);if(this.skillDeltaFn){let u=this.skillDeltaFn();u&&this.conversation.addSystemReminder(`The following skills became available:
235
- `+u)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let k=await W(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 u=this.client.stream(this.conversation,e,this.abortSignal);for await(let l of u){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":c.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":h.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(u){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(u instanceof N)try{let l=await Y(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:u};return}if(u instanceof F){let l=Ie(S(_(u),"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:u instanceof Error?u:new Error(JSON.stringify(u))};return}if(this.abortSignal?.aborted){a&&(this.conversation.addAssistantFull(a,c,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",a),g==="max_tokens")if(n){if(r<le){r++,this.conversation.addAssistantFull(a,c,[]),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?.(Te),n=!0,a&&(this.conversation.addAssistantFull(a,c,[]),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,c,h),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),h.length>0){let u=await this.executeTools(h);for(let d of u)yield d;let l=new Set;for(let d of h)re(d.toolName,d.arguments,this.workDir,this.sessionId)&&l.add(d.toolUseId);let b=[];for(let d of u)if(d.type==="tool_result"){let f=d.output;typeof f=="string"&&f.length>xe&&!l.has(d.toolId)&&(f=ae(this.workDir,this.sessionId,d.toolId,f),l.add(d.toolId)),b.push({toolUseId:d.toolId,content:f,isError:d.isError})}ie(b,this.workDir,this.sessionId,l);let ue=h.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 u=a.length>60?a.slice(0,60)+"...":a;this.fileHistory.makeSnapshot(this.conversation.len(),u)}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 h=await this.hookEngine.firePreToolHooks(o.toolName,o.arguments);if(h.rejected){n.push({type:"tool_result",toolName:o.toolName,toolId:o.toolUseId,output:`Rejected by hook: ${h.reason}`,isError:!0,elapsed:0});continue}}let a=this.registry.get(o.toolName)?.category??"command",c=this.checker.check(o.toolName,a,o.arguments);if(c.effect==="deny"){n.push({type:"tool_result",toolName:o.toolName,toolId:o.toolUseId,output:`Permission denied: ${c.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(c.effect==="ask"&&this.onPermissionRequest){let h=await this.onPermissionRequest(o.toolName,o.arguments,c);if(h==="deny"){n.push({type:"tool_result",toolName:o.toolName,toolId:o.toolUseId,output:I,isError:!0,elapsed:0});continue}h==="allowAlways"&&this.checker.allowAlways(o.toolName,o.arguments)}if(r.submit(o.toolUseId,o.toolName,o.arguments),!t){let h=await r.collectResults();for(let g of h)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:P(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];D(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:M(t.toolUses)}:{},...t.toolResults?.length?{tool_results:L(t.toolResults)}:{}})}};function Ie(s){if(!s)return 5e3;let e=parseInt(s,10);return Number.isNaN(e)?5e3:e*1e3}export{v as a,K as b,Fe as c,z as d,Ne as e,Oe as f,De as g,ce as h};
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};
@@ -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
+ var o="ToolSearch",O="McpCall";export{o as a,O as b};
@@ -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-M5AOLYFS.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-EAEDMTTA.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(t,r)}if(r&&r>0)return r}return j(e.model)}function ue(e){return e.max_output_tokens&&e.max_output_tokens>0?e.max_output_tokens:e.thinking?64e3:8192}function me(e){if(e.api_key)return e.api_key;let n=N(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var O=o.object({name:o.string(),command:o.string().optional(),args:o.array(o.string()).optional(),url:o.string().optional(),transport:o.string().optional(),headers:o.record(o.string(),o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),z=o.object({id:o.string().optional(),event:o.string(),condition:o.string().optional(),action:o.object({type:o.string(),command:o.string().optional(),url:o.string().optional(),method:o.string().optional(),prompt:o.string().optional()}),reject:o.boolean().optional(),once:o.boolean().optional(),async:o.boolean().optional(),on_error:o.string().optional()}),M=o.object({enabled:o.boolean().optional(),auto_allow:o.boolean().optional(),network_enabled:o.boolean().optional()}),T=o.looseObject({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(O).default([]),hooks:o.array(z).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function Y(e){return typeof e=="object"&&e!==null}function C(e){let n=$(e,"utf-8"),t=x.load(n);if(!Y(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=c(T,t);if(r.success){let a=r.data;return{providers:a.providers,permission_mode:a.permission_mode,mcp_servers:a.mcp_servers,hooks:a.hooks}}g.error({error:r.error},"config error");let i=[],s,f=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=c(o.array(P),t.providers);a.success&&(i=a.data)}if("permission_mode"in t&&typeof t.permission_mode=="string"&&(s=t.permission_mode),"mcp_servers"in t){let a=c(o.array(O),t.mcp_servers);a.success&&(f=a.data)}if("hooks"in t){let a=c(o.array(z),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=c(M,t.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in t&&(b=!!t.enable_coordinator_mode),"enable_fork"in t&&(h=!!t.enable_fork),{providers:i,permission_mode:s,mcp_servers:f,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(e,n){if(n.providers.length>0&&(e.providers=n.providers),n.permission_mode&&(e.permission_mode=n.permission_mode),n.mcp_servers.length>0){let t=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];t.set(i.name,r)}for(let r of n.mcp_servers){let i=t.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),t.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...n.hooks],n.sandbox&&(e.sandbox={...e.sandbox,...n.sandbox}),n.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),n.enable_fork!==void 0&&(e.enable_fork=n.enable_fork),e}function k(e){if(e.providers.length===0)throw new d("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"];for(let t=0;t<e.providers.length;t++){let r=e.providers[t],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=n.filter(f=>!(f in i));if(s.length>0)throw new d(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new d(`Provider #${String(t+1)}: invalid protocol '${r.protocol}', MUST be one of: ${Array.from(_).join(", ")}`)}}function _e(e){if(e){let s=C(e);return k(s),s}let n=process.cwd(),t=I(),r=[l(t,".swifty","config.yml"),l(t,".swifty","config.yaml"),l(n,".swifty","config.yml"),l(n,".swifty","config.yaml"),l(n,".swifty","config.local.yml"),l(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let f=C(s);i?i=K(i,f):i=f}if(!i)throw new d("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{c as a,ee as b,oe as c,ne as d,de as e,pe as f,ue as g,me as h,ge as i,_e as j};
4
+ import{a as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as u,c as m}from"./chunk-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};